ank
The ank skills, served from the repository that carries the tool.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/haksolot/ank with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/haksolot/ank'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/haksolot--ank)HTML
<a href="/listings/haksolot--ank"><img src="/api/listings/haksolot--ank/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
npm install -g @haksolot/ank # the binary for your platform npx skills add haksolot/ank # the skills, for your agent
Linux, macOS and Windows; needs git 2.34 or newer. The shell installers and every other route are in [Install][install]. The version is `0.x` on purpose: the loop and the exit codes are specified, the storage format is not yet.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 15 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "ank",
- "description": "The ank skills, served from the repository that carries the tool.",
- "owner": {
- "name": "haksolot",
- "url": "https://github.com/haksolot"
- },
- "plugins": [
- {
- "name": "ank",
- "source": "./",
- "description": "Carries the six ank skills: the contract that teaches claiming work and finishing it with proof, and one policy each for planning, drift, the loop, test-first and diagnosis."
- }
- ]
- }
README.md · README · 83 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <p align="center"><picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/ank-dark.svg">
- <img src="assets/ank.svg" alt="" width="88" height="88"></picture></p>
- <h1 align="center">ank</h1>
- <p align="center"><strong>The stupid coordination tool</strong><br>
- Tasks and architecture decisions in your repo, behind one CLI any coding agent can call.</p>
- <p align="center"><a href="https://github.com/haksolot/ank/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/haksolot/ank/actions/workflows/ci.yml/badge.svg"></a>
- <a href="https://github.com/haksolot/ank/releases/latest"><img alt="Latest release" src="https://img.shields.io/github/v/release/haksolot/ank"></a>
- <a href="LICENSE"><img alt="Licence" src="https://img.shields.io/badge/licence-Apache--2.0-blue"></a></p>
- An agent can read every line of your code, but not your tracker, your wiki, or
- the thread where you decided that sessions must never be self-contained JWTs.
- Ank keeps those decisions and the work in `.ank/`, attached to the code they
- constrain, and serves them through one CLI.
- <p align="center"><picture>
- <source media="(prefers-color-scheme: dark)" srcset="assets/demo-dark.gif">
- <img src="assets/demo.gif" alt="A terminal session: ank context serves a constraint saying every refusal must name the command that fixes it; ank graph shows which task is takeable; a task is claimed and its criterion frozen; the code written next produces exactly that message; ank done runs the declared verifier and records a hashed proof."></picture></p>
- ## Install
- ```sh
- npm install -g @haksolot/ank # the binary for your platform
- npx skills add haksolot/ank # the skills, for your agent
- ```
- Linux, macOS and Windows; needs git 2.34 or newer. The shell installers and
- every other route are in [Install][install]. The version is `0.x` on purpose: the loop and
- the exit codes are specified, and so is the file format, by the accepted data-model
- spec listed in [the specification][spec]. The format may still change before 1.0,
- and a change arrives as a new `schema` value.
- ## The loop
- ```sh
- ank context <path> # what binds this perimeter, and what is takeable
- ank claim <id> # take a task and freeze its criterion
- ank show <id> # the entity whole
- ank log "<message>" # what you learned, while you work
- ank done # run the declared verifiers and record the proof
- ank release --reason "<why>" # hand the task back
- ```
- [The quickstart][start] walks it from `ank init` onward, with real output.
- ## What it is not
- - **Not a tracker.** No cycles, estimates, velocity or roadmap.
- - **Not a wiki.** Only what is actionable or binding for an agent goes in.
- - **Not a security boundary.** It protects against drift, not against an attacker.
- ## Documentation
- The documentation is published at <https://haksolot.github.io/ank/>, built from
- [`docs/`](https://github.com/haksolot/ank/tree/main/docs) on every merge.
- - **Using ank**: [Install][install], [the quickstart][start], [proof and
- verifiers](https://haksolot.github.io/ank/proof.html), [claims and
- identity](https://haksolot.github.io/ank/claims.html), [reading `ank
- check`](https://haksolot.github.io/ank/check.html), [CI](https://haksolot.github.io/ank/ci.html),
- [multi-agent work](https://haksolot.github.io/ank/multi-agent.html)
- - **Reference**: [exit codes](https://haksolot.github.io/ank/exit-codes.html),
- [the file format](https://haksolot.github.io/ank/format.html),
- [environment variables](https://haksolot.github.io/ank/environment.html),
- [the specification](https://haksolot.github.io/ank/specification.html)
- - **Integrating**: [the machine surface](https://haksolot.github.io/ank/integrating.html),
- [the MCP server](https://haksolot.github.io/ank/mcp.html),
- [the watcher](https://haksolot.github.io/ank/watch.html)
- - **Maintaining**: [ratifying](https://haksolot.github.io/ank/ratifying.html),
- [releasing](https://haksolot.github.io/ank/releasing.html),
- [CI jobs](https://haksolot.github.io/ank/ci-jobs.html)
- - [Contributing](https://github.com/haksolot/ank/blob/main/CONTRIBUTING.md) · [Security](https://github.com/haksolot/ank/blob/main/SECURITY.md) · [Code of Conduct](https://github.com/haksolot/ank/blob/main/CODE_OF_CONDUCT.md)
- ## Licence
- Apache-2.0. See [LICENSE](LICENSE).
- [install]: https://haksolot.github.io/ank/install.html
- [start]: https://haksolot.github.io/ank/quickstart.html
- [spec]: https://haksolot.github.io/ank/specification.html
install.ps1 · Bundled script · 1,332 lines · 6 findings marked
- <#
- Install ank from a GitHub release.
- irm https://raw.githubusercontent.com/haksolot/ank/main/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 4 on GitHub
- & ([scriptblock]::Create((irm https://raw.githubusercontent.com/haksolot/ank/main/install.ps1))) -Version v0.2.0
- The Windows counterpart of install.sh, and the same contract: fetch the archive
- the release published, verify it against the .sha256 published beside it, unpack
- it, and never end in silence. What differs is only what Windows spells
- differently.
- One executable lands: ank.exe. The protocol surface and the watcher are verbs
- of it (ADR-1ea31c2f3c5a), so there is no second file for this script to place
- and no way for one to fail to arrive.
- -Version reaches releases published before that was true, whose archive carries
- a second executable beside ank.exe. Nothing here asks: the archive is unpacked,
- ank.exe is taken out of it, and whatever else the directory holds goes with the
- temporary directory. So an old release installs the one file this script
- promises, by the same code path a new one does.
- Windows PowerShell 5.1 is the floor, because that is what a clean Windows ships
- and this channel exists for the machine that has nothing installed yet. Two
- consequences run through the file: TLS 1.2 is turned on explicitly, since 5.1
- still defaults to protocols GitHub refuses, and every cmdlet used here is one
- 5.1 carries.
- Exit codes, so a caller can branch on the failure rather than on the message:
- 1 usage, or a directory that cannot be written
- 2 unsupported platform
- 3 the download failed, or the release does not carry this archive
- 4 the checksum did not match the one the release published, or the build
- provenance was checked and did not verify
- 5 a runtime this script needs is missing, gh included under
- -RequireProvenance
- -NoWelcome, or ANK_NO_WELCOME in the environment, turns off everything this
- script draws for a human and everything it asks one, and leaves only the lines
- a machine reads. It is absent from the list above on purpose: the welcome is
- drawn before the first request goes out and the offer comes after the binary is
- on disk and verified, so neither is on the path to any of them -- a flag able
- to change one of these five codes would be a flag that made the install depend
- on it.
- They are the codes install.sh returns for the same failures, and they reach a
- caller who runs this as a file. The one-liner above runs it through `iex`, where
- `exit` would close the window the caller is typing in -- so under `iex` a
- failure throws instead, after printing the same diagnosis. That branch is the
- whole reason $PSCommandPath is read below: it is empty exactly when this text is
- not being run as a file.
- #>
- param(
- [string]$Version,
- [string]$Dir,
- [switch]$NoWelcome,
- [switch]$RequireProvenance,
- [switch]$Help
- )
- # No Set-StrictMode here, and it is not an oversight. Under `iex` this text runs
- # in the caller's own session, where a strict mode set by an installer would
- # outlive it and change how their next commands behave -- and unlike the two
- # settings restored in the finally below, there is nothing to read it back from.
- $Repo = 'haksolot/ank'
- $RawUrl = "https://raw.githubusercontent.com/$Repo/main/install.ps1"
- $ReleasesUrl = "https://github.com/$Repo/releases"
- $DefaultBaseUrl = "$ReleasesUrl/download"
- # The one target release.yml builds for Windows. Written once and read by both
- # the refusal and the help text: a list that says one thing when it refuses and
- # another when it is asked is worse than no list at all.
- $WindowsTarget = 'x86_64-pc-windows-msvc'
- # Empty exactly when this text is not running as a file -- `irm | iex`, or a
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 78 on GitHub
- # scriptblock built from it. Probed rather than assumed, including from inside
- # another script, which is the case a CI step is.
- $RunningAsFile = -not [string]::IsNullOrEmpty($PSCommandPath)
- # ---------------------------------------------------------------------------
- # Output
- # ---------------------------------------------------------------------------
- # Write-Host and not Write-Output, for the reason install.sh sends everything to
- # stderr: under `iex` this runs in the caller's own session, and a diagnosis
- # written to the pipeline would land in whatever they were assembling.
- # -Color is a console attribute set through the host and never an escape
- # sequence, which is the same reason Show-Logo moves the cursor through RawUI:
- # Windows PowerShell 5.1 in conhost prints an ESC[36m instead of obeying it. So
- # a transcript records the words and no sequence at all, on any run.
- function Say {
- param([string]$Line = '', [switch]$NoNewline, [string]$Color = '')
- $paint = @{}
- if ($Color) { $paint['ForegroundColor'] = $Color }
- if ($NoNewline) { Write-Host -NoNewline $Line @paint } else { Write-Host $Line @paint }
- }
- # Colour and the marker, behind the gate the logo is drawn behind, exactly as
- # install.sh holds them: empty until Enable-Ui runs, so a console-less caller
- # reads the bytes it read before this file learned about either.
- #
- # DarkGray and not a lighter grey for the dim: it is the one shade that reads as
- # quieter against a black console and against a white one, which is the whole of
- # what "dim" has to survive here. There is no bold to be had -- a console host
- # has a foreground and no weight -- so what install.sh writes bold is written in
- # the console's own foreground, and the contrast comes from what is dimmed
- # around it.
- $UiDim = ''
- $UiCyan = ''
- $UiGreen = ''
- $UiPad = ''
- $UiTick = ''
- function Enable-Ui {
- $script:UiPad = ' '
- $script:UiTick = if (Test-GlyphSurvives 0x2713) { "$([char]0x2713) " } else { '- ' }
- if ($env:NO_COLOR) { return }
- $script:UiDim = 'DarkGray'
- $script:UiCyan = 'Cyan'
- $script:UiGreen = 'Green'
- }
- # `Ok <line>`: a step that finished. The marker and the indent are drawn for a
- # person and for nobody else -- what a transcript reads is the sentence alone,
- # written by the one call the line used to be, rather than by three that happen
- # to concatenate to it.
- function Ok {
- param([string]$Line)
- if (-not $UiTick) {
- Say $Line
- return
- }
- Say -NoNewline $UiPad
- Say -NoNewline -Color $UiGreen $UiTick
- Say $Line
- }
- # `Fail <code> <lines>`: the code carries the kind of failure, the lines carry
- # what to do next. Nothing here ever ends in silence -- that is the one thing an
- # install script cannot do, since the caller is otherwise left with no binary
- # and no idea why.
- function Fail {
- param([int]$Code, [string[]]$Lines)
- Say "ank: $($Lines[0])"
- for ($i = 1; $i -lt $Lines.Count; $i++) { Say $Lines[$i] }
- if ($RunningAsFile) { exit $Code }
- # Under `iex` the caller is at their own prompt: `exit` would take the
- # session with it, which is a worse outcome than the failed install.
- throw "ank: install failed (code $Code)"
- }
- function Show-Usage {
- Say 'install ank from a GitHub release'
- Say ''
- Say 'One executable lands in the install directory: ank.exe. The protocol'
- Say 'surface and the watcher are verbs of it -- ank mcp, ank watch -- so'
- Say 'there is nothing further to fetch and nothing further to configure a'
- Say 'client against.'
- Say ''
- Say 'usage:'
- Say " irm $RawUrl | iex"
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 166 on GitHub
- Say ''
- Say ' with arguments, since a pipe into iex cannot carry them:'
- Say " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0"
- Say ''
- Say 'options:'
- Say ' -Version <version> install this release instead of the latest one;'
- Say ' "v0.2.0" and "0.2.0" both work'
- Say ' -Dir <path> install into <path> instead of'
- Say ' $env:LOCALAPPDATA\Programs\ank'
- Say ' -NoWelcome draw nothing and ask nothing; install exactly what an'
- Say ' interactive run that declined every offer installs'
- Say ' -RequireProvenance refuse unless gh verifies the build provenance of the'
- Say ' archive; without it, provenance is checked when a'
- Say ' signed-in gh is on PATH and the checksum stands alone'
- Say ' otherwise'
- Say ' -Help print this and exit'
- Say ''
- Say 'environment:'
- Say ' ANK_VERSION same as -Version'
- Say ' ANK_INSTALL_DIR same as -Dir'
- Say ' ANK_NO_WELCOME same as -NoWelcome, for a caller that pipes this script'
- Say ' into iex and cannot pass a switch to it'
- Say ' ANK_BASE_URL where the archives are fetched from, for a mirror or a'
- Say ' staged release; requires -Version, since only GitHub'
- Say ' can be asked which release is the latest'
- Say ' ANK_REQUIRE_PROVENANCE'
- Say ' same as -RequireProvenance'
- Say ''
- Say 'platforms:'
- Say " Windows x64 $WindowsTarget"
- Say ''
- Say ' Linux and macOS are installed by install.sh:'
- Say " curl -fsSL https://raw.githubusercontent.com/$Repo/main/install.sh | sh"
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 199 on GitHub
- Say ''
- Say 'the two questions:'
- Say ' With a console attached, once ank is installed and verified, this asks two'
- Say ' things and nothing else. The first offers to run:'
- Say ' ank skills --install'
- Say ' which teaches an agent how to use ank. The second offers to print three'
- Say ' prompts that adopt ank in a repository that already has code and no .ank;'
- Say ' they are in docs/quickstart.md too, and printing them writes nothing'
- Say ' anywhere.'
- Say ' Enter accepts each, declining either does nothing at all, and nothing'
- Say ' either does can change any of the codes below.'
- Say ''
- Say 'exit codes:'
- Say ' 1 usage 2 unsupported platform 3 download 4 checksum 5 missing runtime'
- }
- # ---------------------------------------------------------------------------
- # Welcome
- # ---------------------------------------------------------------------------
- # The logo, from assets/ank.svg read as pixels: twenty-four columns by ten rows,
- # one cell per pixel column and one row per pair of pixel rows, which is the
- # ratio that makes a console cell square. The same shape install.sh holds and
- # the same twelve lines, because it is the same logo and two spellings of it
- # would drift. That file is the reference and nothing here reads it -- an
- # installer that fetches a logo before it fetches the binary is an installer
- # with a second way to fail before doing anything useful, so the shape is bytes
- # in this file.
- #
- # The block is not assumed, and it is not refused either. The old reading of
- # this was that a Windows PowerShell 5.1 in conhost cannot draw U+2588, and it
- # is wrong twice over: codepage 437 carries the full block at 0xDB, and a
- # console that is genuinely UTF-8 carries it too. What actually decides is
- # whether the encoder the console is using can carry the character at all, and
- # that is a question with an answer -- Test-GlyphSurvives asks it rather than
- # guessing from a codepage number. The tick is asked the same way and gets a
- # different answer on 437, which has no U+2713.
- $LogoWidth = 24
- # Eleven spaces: columns 0 to 10, what stands left of the stem on a row whose
- # leg has not grown yet. Every such row is the same width, so this is a constant
- # rather than something measured.
- $LogoPad11 = ' '
- # Whether a character reaches the console as itself: encoded through whatever
- # the console is using and decoded back, and equal to what went in.
- #
- # The round trip and not a search for a question mark, because measuring it
- # showed the question mark is the case that does not happen. .NET best-fits
- # instead, and it best-fits to something plausible and wrong: codepage 437 turns
- # U+2713 into 0xFB, which is a square root sign, and codepage 1252 turns U+2588
- # into 0xA6, which is a broken bar. A check for `?` passes both and ships a logo
- # made of broken bars and a tick that is a radical -- worse than the fence of
- # hashes this replaced. The round trip refuses both and accepts codepage 437's
- # block at 0xDB, which is genuinely the character asked for.
- #
- # Asked once per run, never inside a frame.
- function Test-GlyphSurvives {
- param([int]$CodePoint)
- try {
- $want = [string][char]$CodePoint
- $encoding = [Console]::OutputEncoding
- return $encoding.GetString($encoding.GetBytes($want)) -eq $want
- } catch {
- return $false
- }
- }
- # One of rows 6 to 9: <pad><leg><gap><stem><gap><leg>, where a part that has not
- # grown yet gives its columns up to the eleven-space pad, so the parts that have
- # stay where they are. A segment is its text and whether it is dimmed, because a
- # leg and the stem share these rows and can be in different states.
- function Get-LogoBand {
- param(
- [int]$Legs, [int]$LegsAt, [int]$Stem, [int]$StemAt,
- [string]$Run, [string]$Gap, [string]$Pair,
- [bool]$DimLegs, [bool]$DimStem
- )
- $hasLegs = $Legs -ge $LegsAt
- $hasStem = $Stem -ge $StemAt
- if (-not $hasLegs -and -not $hasStem) { return , @() }
- $out = @()
- if ($hasLegs) {
- $out += @{ T = ' '; D = $false }
- $out += @{ T = $Run; D = $DimLegs }
- $out += @{ T = $Gap; D = $false }
- } else {
- $out += @{ T = $LogoPad11; D = $false }
- }
- if ($hasStem) {
- $out += @{ T = $Pair; D = $DimStem }
- } elseif ($hasLegs) {
- $out += @{ T = ' '; D = $false }
- }
- if ($hasLegs) {
- $out += @{ T = $Gap; D = $false }
- $out += @{ T = $Run; D = $DimLegs }
- }
- return , $out
- }
- # One frame as twelve rows of segments. The arguments are the state of the build
- # and not a frame number: base is on or off, legs and stem are how many of their
- # rows have grown, loop is on or off, soft names the part still arriving, name is
- # the wordmark. A timeline written as states can be re-timed without recomputing
- # which row is which.
- function Get-LogoFrame {
- param(
- [int]$Base, [int]$Legs, [int]$Stem, [int]$Loop,
- [string]$Soft, [bool]$Name,
- [string]$B2, [string]$B4, [string]$B14
- )
- $dimAll = $Soft -eq 'all'
- $dimLoop = $dimAll -or $Soft -eq 'loop'
- $dimStem = $dimAll -or $Soft -eq 'stem'
- $dimLegs = $dimAll -or $Soft -eq 'legs'
- $dimBase = $dimAll -or $Soft -eq 'base'
- # Rows 1 and 4, then 2 and 3: the loop is columns 10-13, then 8-9 with 14-15.
- if ($Loop) {
- $r1 = @(@{ T = ' '; D = $false }, @{ T = $B4; D = $dimLoop })
- $r2 = @(
- @{ T = ' '; D = $false }, @{ T = $B2; D = $dimLoop },
- @{ T = ' '; D = $false }, @{ T = $B2; D = $dimLoop }
- )
- } else {
- $r1 = @()
- $r2 = @()
- }
- # Row 5, the stem alone, the last of its five rows to grow.
- if ($Stem -ge 5) {
- $r5 = @(@{ T = ' '; D = $false }, @{ T = $B2; D = $dimStem })
- } else {
- $r5 = @()
- }
- $r6 = Get-LogoBand $Legs 4 $Stem 4 $B4 ' ' $B2 $dimLegs $dimStem
- $r7 = Get-LogoBand $Legs 3 $Stem 3 $B2 ' ' $B2 $dimLegs $dimStem
- $r8 = Get-LogoBand $Legs 2 $Stem 2 $B2 ' ' $B2 $dimLegs $dimStem
- $r9 = Get-LogoBand $Legs 1 $Stem 1 $B2 ' ' $B2 $dimLegs $dimStem
- # Row 10, the base, columns 5-18.
- if ($Base) {
- $r10 = @(@{ T = ' '; D = $false }, @{ T = $B14; D = $dimBase })
- } else {
- $r10 = @()
- }
- if ($Name) {
- $r12 = @(@{ T = ' ank'; D = $false })
- } else {
- $r12 = @()
- }
- return , @($r1, $r2, $r2, $r1, $r5, $r6, $r7, $r8, $r9, $r10, @(), $r12)
- }
- # The cursor is moved through $Host.UI.RawUI and not with an escape sequence,
- # and that is the Windows half of this decision rather than a preference.
- # Windows PowerShell 5.1 in conhost does not turn on virtual terminal
- # processing for its own output, so an ESC[12A written there is printed as
- # glyphs instead of obeyed: the animation would become exactly the mess it
- # exists to avoid, on precisely the shell this file claims as its floor. RawUI
- # is the interface both hosts implement, and it emits no escape sequence at
- # all, on any run.
- function Show-Logo {
- $ui = $Host.UI.RawUI
- # A window narrower than the art wraps every line, and a block that is
- # taller than twelve rows is a block the redraw moves back over the middle
- # of. Nothing is written before this is known.
- if ($ui.WindowSize.Width -lt $LogoWidth) { return }
- # The cell and the three runs the shape is made of, built once. Seventeen
- # frames are drawn and none of them may repeat this.
- $cell = if (Test-GlyphSurvives 0x2588) { [string][char]0x2588 } else { '#' }
- $b2 = $cell * 2
- $b4 = $cell * 4
- $b14 = $cell * 14
- $rows = 12
- # The blank lines are written before the position is read, so that a window
- # with the prompt at its bottom does its scrolling now: a coordinate saved
- # while the buffer is still moving points at the wrong row for every frame
- # after it.
- for ($i = 0; $i -lt $rows; $i++) { Say '' }
- $top = $ui.CursorPosition.Y - $rows
- if ($top -lt 0) { return }
- $origin = New-Object System.Management.Automation.Host.Coordinates 0, $top
- $savedCursor = $true
- try {
- $savedCursor = [Console]::CursorVisible
- [Console]::CursorVisible = $false
- } catch {
- # A host that will not say whether its cursor is visible still draws.
- }
- # Bottom up: the base arrives dim and settles, the legs and then the stem
- # grow out of it a row at a time, the loop crowns them, and the whole shape
- # blinks twice before the name appears. That last beat is what the animation
- # exists for -- it costs the time it takes to read the name of the tool and
- # not a second more.
- #
- # The two parts that appear whole come in dim; the two that grow do not,
- # since growing a row at a time is already motion and dimming it as well
- # would say the same thing twice.
- #
- # base legs stem loop soft name ms
- $script = @(
- @(1, 0, 0, 0, 'base', $false, 100),
- @(1, 0, 0, 0, 'none', $false, 100),
- @(1, 1, 0, 0, 'none', $false, 45),
- @(1, 2, 0, 0, 'none', $false, 45),
- @(1, 3, 0, 0, 'none', $false, 45),
- @(1, 4, 0, 0, 'none', $false, 45),
- @(1, 4, 1, 0, 'none', $false, 45),
- @(1, 4, 2, 0, 'none', $false, 45),
- @(1, 4, 3, 0, 'none', $false, 45),
- @(1, 4, 4, 0, 'none', $false, 45),
- @(1, 4, 5, 0, 'none', $false, 45),
- @(1, 4, 5, 1, 'loop', $false, 100),
- @(1, 4, 5, 1, 'none', $false, 100),
- @(1, 4, 5, 1, 'all', $false, 45),
- @(1, 4, 5, 1, 'none', $false, 45),
- @(1, 4, 5, 1, 'all', $false, 45),
- @(1, 4, 5, 1, 'none', $true, 450)
- )
- try {
- foreach ($step in $script) {
- $ui.CursorPosition = $origin
- $frame = Get-LogoFrame $step[0] $step[1] $step[2] $step[3] `
- $step[4] $step[5] $b2 $b4 $b14
- foreach ($row in $frame) { Write-LogoRow $row }
- Start-Sleep -Milliseconds $step[6]
- }
- } finally {
- try { [Console]::CursorVisible = $savedCursor } catch { }
- }
- # One blank line under the block, so what the install says next does not
- # start on the line the name ends on.
- Say ''
- }
- # One row of a frame. Padded to the full width rather than erased: there is no
- # clear-to-end-of-line without an escape sequence, and writing the spaces says
- # the same thing in the alphabet this function is restricted to.
- #
- # Adjacent segments in the same state are written as one, and that is not
- # tidiness. conhost turns every write that changes an attribute into a console
- # API call, and a row is almost always one state throughout: segment by segment
- # the seventeen frames cost 649 writes for 94 actual changes of attribute, so
- # 555 of them bought nothing. Coalesced, a row in one state is one write.
- function Write-LogoRow {
- param($Segments)
- $runs = @()
- $width = 0
- foreach ($seg in $Segments) {
- $segDim = [bool]($seg.D -and $UiDim)
- if ($runs.Count -gt 0 -and $runs[-1].D -eq $segDim) {
- $runs[-1].T += $seg.T
- } else {
- $runs += @{ T = $seg.T; D = $segDim }
- }
- $width += $seg.T.Length
- }
- # The padding closes the line and carries no state of its own, so it joins
- # the last run when that run is not dimmed and stands alone when it is.
- $pad = ''
- if ($width -lt $LogoWidth) { $pad = ' ' * ($LogoWidth - $width) }
- if ($runs.Count -gt 0 -and -not $runs[-1].D) {
- $runs[-1].T += $pad
- $pad = $null
- }
- for ($i = 0; $i -lt $runs.Count; $i++) {
- $last = ($i -eq $runs.Count - 1) -and ($null -eq $pad)
- if ($runs[$i].D) {
- if ($last) { Say -Color $UiDim $runs[$i].T }
- else { Say -NoNewline -Color $UiDim $runs[$i].T }
- } else {
- if ($last) { Say $runs[$i].T }
- else { Say -NoNewline $runs[$i].T }
- }
- }
- if ($null -ne $pad) { Say $pad }
- }
- # ADR-5fbd99bf6fd5 read as an absence: where no human is looking, this script
- # draws nothing at all and asks nothing at all.
- #
- # Both streams are tested and not only one. `irm ... | iex` leaves stdout and
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 504 on GitHub
- # stderr on the console, which is the case that must animate; redirecting
- # either of them into a file is the case that must not, since a transcript full
- # of padding and repositioning is the noise this exists to avoid. The host is
- # asked last, and by trying rather than by name: a host with no console answers
- # the two properties above happily and then throws on the first cursor it is
- # asked to place.
- #
- # The logo and the offer read this same answer, which is what makes -NoWelcome
- # and an interactive run that declined everything leave the same machine
- # behind: one predicate, so there is no second gate to disagree with this one.
- # The width belongs to the block of art alone and is asked inside Show-Logo,
- # since a console too narrow to hold the logo is still a console with a person
- # in front of it.
- function Test-HumanAtTerminal {
- if ($NoWelcome) { return $false }
- if ($env:ANK_NO_WELCOME) { return $false }
- # A runner sets this, and a runner is a machine with no human at it.
- if ($env:CI) { return $false }
- try {
- if ([Console]::IsOutputRedirected) { return $false }
- if ([Console]::IsErrorRedirected) { return $false }
- $null = $Host.UI.RawUI.CursorPosition
- } catch {
- return $false
- }
- return $true
- }
- # ---------------------------------------------------------------------------
- # The skills
- # ---------------------------------------------------------------------------
- # ADR-5fbd99bf6fd5's offer, and the last thing this script does. Everything
- # else has already happened by then: the binary is on disk, verified, reported,
- # and the PATH advice given. That ordering is the decision rather than a layout
- # -- an installation that stops to ask something is an installation that can be
- # abandoned half-done, and half-done is the worst state for a tool whose next
- # action is `ank context`.
- #
- # The question is this script's and the answer is the binary's
- # (ADR-e1d750884b82). `ank skills --install` writes out the skills it carries
- # and hands them to the skills CLI, which serves every agent it knows about
- # rather than one, and the verb already decides what to say when node is
- # missing and what a failure means. A second copy of that logic here would be
- # a second copy to drift.
- #
- # Nothing in here is allowed to reach the caller as a failure. The call site
- # wraps it, and the exit code is stamped after it returns.
- function Invoke-SkillOffer {
- param([Parameter(Mandatory = $true)][string]$Ank)
- if (-not (Test-HumanAtTerminal)) { return }
- Say ''
- Say "${UiPad}The skills teach an agent how to use ank: the contract, and one policy"
- Say "${UiPad}per activity. They install through the skills CLI, which puts them where"
- Say "${UiPad}each agent looks."
- Say ''
- Say -Color $UiCyan "$UiPad ank skills --install"
- Say ''
- # [Console]::ReadLine and not Read-Host, which is where Windows differs
- # from the /dev/tty install.sh opens and why the two files spell this step
- # differently. `irm ... | iex` runs this text through a pipeline in the
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 568 on GitHub
- # caller's own session: Console.In is the console and never that pipeline,
- # so a question asked here cannot consume what they piped. $null is end of
- # input -- nothing was typed, so nothing is assumed.
- Say -NoNewline "${UiPad}Install them now? [Y/n] "
- $answer = $null
- try { $answer = [Console]::ReadLine() } catch { $answer = $null }
- if ($null -eq $answer) {
- Say ''
- return
- }
- # Enter is yes and everything unrecognised is no, in that order: a default
- # the criterion names, and a decline for anything else because asking twice
- # is asking twice.
- $reply = $answer.Trim()
- if ($reply -ne '' -and $reply -notmatch '^(y|yes)$') { return }
- # The binary just installed, by the path it was installed at: the directory
- # may not be on PATH, and a different ank found there would answer for a
- # build this script did not place.
- #
- # Nothing is printed on success, and that is deliberate: the verb exits 0
- # both when the skills went in and when node is missing and it printed the
- # command to run instead, so a line of this script's own would be claiming
- # something only the verb's output knows.
- $code = 0
- try {
- $global:LASTEXITCODE = 0
- # Through Say for the reason Say exists: under `iex` output written to
- # the pipeline lands in whatever the caller was assembling. 2>&1 so the
- # verb's diagnosis arrives as text rather than as error records a
- # caller's $ErrorActionPreference could turn into an exception.
- & $Ank skills --install 2>&1 | ForEach-Object { Say "$_" }
- $code = $LASTEXITCODE
- } catch {
- Say " $($_.Exception.Message)"
- $code = 9
- }
- if ($code -ne 0) {
- Say ''
- Say "ank skills --install exited $code, so the skills are not installed."
- Say 'ank is, and it is exactly the ank this script installs when nobody is'
- Say 'asked anything at all.'
- Say ''
- Say 'Run it again when you want them:'
- Say -Color $UiCyan "$UiPad ank skills --install"
- }
- }
- # ---------------------------------------------------------------------------
- # Adopting ank where there is already code
- # ---------------------------------------------------------------------------
- # ADR-5fbd99bf6fd5's second offer, and the last question this script asks.
- # Installing ank is the easy half. The half nobody had written down is what to
- # say to an agent so that a repository with two years of history acquires a
- # corpus worth having, and the moment after an install is the one moment the
- # person is certainly reading.
- #
- # Three prompts, because the adoption has three moments: state as ADRs what the
- # code already decided, so the constraints that exist implicitly become
- # readable; turn a list of intentions into tasks carrying a scope and a
- # criterion; and check what came out. The first one is the one the reader judges
- # the tool on, which is why it is first.
- #
- # The same three prose blocks live in install.sh and in docs/quickstart.md,
- # and a test holds the three copies character for character
- # (crates/ank-cli/tests/adopt.rs). Prose duplicated in three files diverges, and
- # this is the prose where divergence is worst: an installer teaching a prompt the
- # documentation has since corrected. The markers below are what the test reads;
- # the block between them is the one to edit, and the other two follow.
- #
- # A single-quoted here-string, so nothing in it is expanded: the text carries $
- # and backticks in no place today, and a literal block is what keeps that from
- # becoming a rule somebody has to remember. Its terminator sits at column zero
- # because Windows PowerShell 5.1 requires it there.
- # adopt-prompts:begin
- $AdoptWalkthrough = @'
- In a repository that already has code and no .ank, start with:
- ank init
- Then paste these three into your agent, one at a time, and read what each
- one produces before you send the next.
- 1. What the code already decided:
- Read this repository and write, as ank ADRs, the decisions its code
- has already made: the ones a newcomer would break without knowing
- they existed. One ADR per decision, each with a scope glob covering
- the files it binds and a constraint stated as a rule. Leave them
- proposed; I ratify them myself.
- 2. What is still owed:
- Read the TODOs, the open issues and the README of this repository,
- and turn what they promise into ank tasks. Give each one a scope
- glob and a done_criteria a test could settle, and use blocked_by
- only where a task genuinely waits on another.
- 3. What you now have:
- Run ank check and ank review here, then read every ADR back against
- the code its scope matches. Tell me which constraints the code
- already breaks and which scopes match no file, and change nothing
- until I have read your answer.
- The same three are in docs/quickstart.md, which says what to expect
- from each:
- https://github.com/haksolot/ank/blob/main/docs/quickstart.md
- '@
- # adopt-prompts:end
- # The second question, asked on the same terms as the first: only with a human
- # at a console, through [Console]::ReadLine so that a caller's `iex` pipeline is
- # never what answers it, and with a default Enter accepts. Declining prints
- # nothing -- not a shortened version, not a pointer to one. An offer that
- # answers a no with half of a yes is an offer that was not really asked.
- #
- # Nothing in here is allowed to reach the caller as a failure. The call site
- # wraps it, and the exit code is stamped after it returns.
- function Invoke-AdoptionOffer {
- if (-not (Test-HumanAtTerminal)) { return }
- Say ''
- Say -NoNewline "${UiPad}Print the three prompts that adopt ank in a repository you already have? [Y/n] "
- $answer = $null
- try { $answer = [Console]::ReadLine() } catch { $answer = $null }
- if ($null -eq $answer) {
- Say ''
- return
- }
- $reply = $answer.Trim()
- if ($reply -ne '' -and $reply -notmatch '^(y|yes)$') { return }
- Say ''
- # Split on either ending rather than on [Environment]::NewLine: this file is
- # fetched by `irm` on one machine and checked out by git on another, and the
- # bytes between two lines are not the same in both.
- foreach ($line in ($AdoptWalkthrough -split "\r?\n")) { Say $line }
- Say ''
- }
- # ---------------------------------------------------------------------------
- # Platform
- # ---------------------------------------------------------------------------
- # Read out of the environment rather than off RuntimeInformation, and that is
- # the deliberate half: an environment variable is what lets the refusal below be
- # exercised on a machine that is not the platform being refused, so the test
- # runs the real code path instead of a flag that bypasses it.
- #
- # PROCESSOR_ARCHITEW6432 is read first because a 32-bit PowerShell on 64-bit
- # Windows reports x86 in the other variable, and installing nothing on a machine
- # that is x64 would be a refusal about the process rather than about the
- # hardware.
- function Get-Architecture {
- if ($env:PROCESSOR_ARCHITEW6432) { return $env:PROCESSOR_ARCHITEW6432.ToUpperInvariant() }
- if ($env:PROCESSOR_ARCHITECTURE) { return $env:PROCESSOR_ARCHITECTURE.ToUpperInvariant() }
- return 'UNKNOWN'
- }
- # ARM64 takes the x64 archive on purpose. No native arm64 build is published,
- # and Windows on ARM runs x64 under emulation transparently -- so refusing there
- # would leave a working machine with no install to protect it from nothing. What
- # is refused is the architecture that genuinely cannot run this binary: a 32-bit
- # x86 Windows, where the emulation runs the other way and does not exist.
- function Resolve-Target {
- $arch = Get-Architecture
- switch ($arch) {
- 'AMD64' { return @{ Target = $WindowsTarget; Emulated = $false } }
- 'ARM64' { return @{ Target = $WindowsTarget; Emulated = $true } }
- default {
- Fail 2 @(
- "no release archive for Windows/$arch.",
- '',
- "PROCESSOR_ARCHITECTURE reported: $arch",
- '',
- 'The release carries one Windows build:',
- " Windows x64 $WindowsTarget",
- '',
- 'A 64-bit Windows runs it natively and Windows on ARM runs it under',
- 'emulation; a 32-bit Windows runs neither.',
- '',
- 'Everything the release carries is listed at:',
- " $ReleasesUrl",
- '',
- 'Nothing was installed.'
- )
- }
- }
- }
- # ---------------------------------------------------------------------------
- # Hashing and unpacking
- # ---------------------------------------------------------------------------
- # Get-FileHash and Expand-Archive would both read better here, and neither is
- # used, for a reason worth recording: they live in modules PowerShell autoloads,
- # and autoloading is the part of this that can be broken by the environment
- # rather than by the machine. Measured while writing this file -- a 5.1 started
- # from a session whose PSModulePath pointed at PowerShell 7's module directories
- # resolved neither cmdlet, and the install died after downloading the archive,
- # on the step that exists to verify it.
- #
- # The .NET types below are in the runtime itself. Nothing is searched for, so
- # there is nothing to shadow, and the two operations this script must never
- # skip are the two that stop depending on a lookup.
- function Get-Sha256 {
- param([string]$Path)
- $sha = [System.Security.Cryptography.SHA256]::Create()
- $stream = [System.IO.File]::OpenRead($Path)
- try {
- $bytes = $sha.ComputeHash($stream)
- } finally {
- $stream.Dispose()
- $sha.Dispose()
- }
- return ([System.BitConverter]::ToString($bytes) -replace '-', '').ToLowerInvariant()
- }
- function Expand-Zip {
- param([string]$Path, [string]$Destination)
- # Built into PowerShell 7; on 5.1 the assembly is present and simply has to
- # be asked for. Loading one already loaded is a no-op, so this is not
- # guarded by a version test that would be one more thing to be wrong.
- Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction SilentlyContinue
- [System.IO.Compression.ZipFile]::ExtractToDirectory($Path, $Destination)
- }
- # Windows locks a running executable, so an upgrade run while another shell has
- # one of these open cannot write over the file -- but it can rename it, which is
- # the one thing Windows does allow. The old binary is moved aside and the new
- # one takes the name; the stale copies are swept on the next run, since the
- # process holding one is still holding it now.
- #
- # A function rather than an inlined block: what it does is subtle enough to be
- # worth reading on its own, and its one caller is easier to read for not
- # carrying it. Returns the message of the failure it could not work around, or
- # $null.
- function Move-IntoPlace {
- param([string]$Source, [string]$Destination, [string]$Name)
- # Out-Null and not for tidiness: what this function returns is read as a
- # message, so a pipeline above it that emitted anything would turn that
- # message into an array and the caller's `if` into a lie.
- Get-ChildItem -Path (Split-Path -Parent $Destination) -Filter "$Name.old-*" `
- -ErrorAction SilentlyContinue |
- ForEach-Object { Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue } |
- Out-Null
- try {
- Move-Item -Path $Source -Destination $Destination -Force -ErrorAction Stop
- return $null
- } catch {
- $aside = "$Destination.old-" + [System.IO.Path]::GetRandomFileName()
- try {
- Move-Item -Path $Destination -Destination $aside -Force -ErrorAction Stop
- Move-Item -Path $Source -Destination $Destination -Force -ErrorAction Stop
- Say "the running $Name was moved aside; it is swept on the next install"
- return $null
- } catch {
- return "$($_.Exception.Message)"
- }
- }
- }
- # ---------------------------------------------------------------------------
- # Downloading
- # ---------------------------------------------------------------------------
- # Returns the HTTP status when the request produced one, so that "this release
- # does not carry that archive" and "the network is down" stay different
- # messages: the 404 is what tells them apart.
- function Get-File {
- param([string]$Url, [string]$OutFile)
- try {
- Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing -ErrorAction Stop
- return @{ Ok = $true; Status = '' }
- } catch [System.Net.WebException] {
- $status = ''
- if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
- return @{ Ok = $false; Status = "$status" }
- } catch {
- # PowerShell 7 wraps the failure in HttpResponseException instead, and
- # keeps the status on the same property.
- $status = ''
- if (($_.Exception | Get-Member -Name Response) -and $_.Exception.Response) {
- $status = [int]$_.Exception.Response.StatusCode
- }
- return @{ Ok = $false; Status = "$status" }
- }
- }
- # The tag of the latest release, read off the redirect rather than through the
- # API: /releases/latest redirects to /releases/tag/<tag>, which costs no rate
- # limit, where api.github.com allows sixty unauthenticated calls an hour per
- # address and an office NAT can be out of them before anyone types this.
- #
- # HttpWebRequest and not Invoke-WebRequest, because -MaximumRedirection 0 is one
- # of the places 5.1 and 7 disagree: one returns the response and the other
- # throws, and reading the Location header off the raw request behaves the same
- # on both.
- function Resolve-LatestTag {
- $tag = ''
- try {
- $request = [System.Net.HttpWebRequest]::Create("$ReleasesUrl/latest")
- $request.AllowAutoRedirect = $false
- $request.Method = 'HEAD'
- $request.UserAgent = 'ank-install.ps1'
- $response = $request.GetResponse()
- $location = $response.Headers['Location']
- $response.Close()
- if ($location) { $tag = $location.Split('/')[-1] }
- } catch {
- $tag = ''
- }
- if ($tag -notmatch '^v') {
- Fail 3 @(
- 'could not work out which release is the latest.',
- '',
- 'Name one instead:',
- " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0",
- '',
- 'The releases are listed at:',
- " $ReleasesUrl"
- )
- }
- return $tag
- }
- # ---------------------------------------------------------------------------
- # Arguments
- # ---------------------------------------------------------------------------
- if ($Help) {
- Show-Usage
- return
- }
- # 5.1 is what a clean Windows 10 or 11 ships and what CI runs this against, so
- # it is the floor this file claims. Older is refused rather than attempted: the
- # .NET types above reach back further, but nothing here has ever been run there
- # and an install that half works is worse than one that says no. Checked before
- # anything is downloaded, so a machine that cannot finish is told before it
- # spends the bytes.
- if ($PSVersionTable.PSVersion.Major -lt 5) {
- Fail 5 @(
- "this script needs PowerShell 5.1 or newer, and this is $($PSVersionTable.PSVersion).",
- '',
- 'Windows 10 and 11 ship 5.1. On an older Windows, install either:',
- ' Windows Management Framework 5.1, or',
- ' PowerShell 7: https://aka.ms/powershell',
- '',
- 'Nothing was installed.'
- )
- }
- if (-not $Version -and $env:ANK_VERSION) { $Version = $env:ANK_VERSION }
- if (-not $Dir -and $env:ANK_INSTALL_DIR) { $Dir = $env:ANK_INSTALL_DIR }
- $BaseUrl = $env:ANK_BASE_URL
- if ($env:ANK_REQUIRE_PROVENANCE) { $RequireProvenance = $true }
- if ($BaseUrl) {
- if ($BaseUrl -notmatch '^https?://') {
- Fail 1 @(
- "ANK_BASE_URL must start with http:// or https://, got: $BaseUrl",
- '',
- 'Unset it to fetch from the GitHub release:',
- ' $env:ANK_BASE_URL = $null'
- )
- }
- if (-not $Version) {
- Fail 1 @(
- 'ANK_BASE_URL is set, so the version has to be named.',
- '',
- 'Only GitHub can be asked which release is the latest; a mirror cannot.',
- " & ([scriptblock]::Create((irm $RawUrl))) -Version v0.2.0"
- )
- }
- }
- # ---------------------------------------------------------------------------
- # Welcome, then install
- # ---------------------------------------------------------------------------
- # Before anything is asked of the network, which is what "before the download
- # starts" has to mean here: the first request this script makes is the HEAD
- # that resolves the latest tag, and it is below.
- #
- # Wrapped, because a host that cannot place a cursor is not a reason to fail an
- # install: nothing has been downloaded yet and nothing below depends on a frame
- # having been drawn.
- if (Test-HumanAtTerminal) {
- # The colour is turned on by the presence of a human and not by the width of
- # their window, which is why this is here and the width test is inside
- # Show-Logo: a console too narrow for the logo is still a console with a
- # person in front of it.
- Enable-Ui
- try { Show-Logo } catch { }
- }
- # Both of these are session state, and under `iex` the session belongs to the
- # caller: they are restored in the finally below rather than left changed by an
- # install. TLS 1.2 because 5.1 defaults to protocols GitHub no longer accepts,
- # and the progress bar because on 5.1 it costs more time than the download.
- $savedProtocol = [Net.ServicePointManager]::SecurityProtocol
- $savedProgress = $ProgressPreference
- $tmp = ''
- try {
- [Net.ServicePointManager]::SecurityProtocol = `
- [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
- $ProgressPreference = 'SilentlyContinue'
- $resolved = Resolve-Target
- $target = $resolved.Target
- if ($Version) {
- # "v0.2.0" and "0.2.0" are the same request. The tag carries the v and
- # the archive name does not, and making the caller know which is which
- # is the kind of detail a released script gets to absorb.
- $tag = 'v' + ($Version -replace '^v', '')
- } else {
- $tag = Resolve-LatestTag
- }
- $bare = $tag -replace '^v', ''
- $archive = "ank-$bare-$target.zip"
- $root = if ($BaseUrl) { $BaseUrl } else { $DefaultBaseUrl }
- $url = "$root/$tag/$archive"
- Say -NoNewline "$UiPad" ; Say -NoNewline "ank $tag "
- Say -Color $UiDim "$target"
- if ($resolved.Emulated) {
- Say 'no native arm64 build is published; Windows runs this one under emulation'
- }
- $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("ank-install-" + [System.IO.Path]::GetRandomFileName())
- New-Item -ItemType Directory -Path $tmp -Force | Out-Null
- # The checksum first: it is the smaller of the two files, so a release that
- # does not carry this target says so before megabytes move. It is also the
- # request that answers "is this platform in this release", which is a
- # question the caller deserves answered rather than left as a stalled
- # download.
- $shaPath = Join-Path $tmp 'sha256'
- $got = Get-File -Url "$url.sha256" -OutFile $shaPath
- if (-not $got.Ok) {
- if ($got.Status -eq '404') {
- Fail 3 @(
- "$tag does not carry an archive for this platform.",
- '',
- " looked for: $archive",
- " at: $url",
- '',
- 'The platform is one this project builds for, so this is about the',
- "release and not about the machine. What $tag carries is listed at:",
- " $ReleasesUrl/tag/$tag",
- '',
- 'Pick a release that carries it:',
- " & ([scriptblock]::Create((irm $RawUrl))) -Version <version>",
- '',
- 'Nothing was installed.'
- )
- }
- $suffix = if ($got.Status) { " (HTTP $($got.Status))" } else { '' }
- Fail 3 @(
- "could not download the checksum for $archive$suffix.",
- '',
- " $url.sha256",
- '',
- 'Nothing was installed.'
- )
- }
- # sha256sum's own format, which is what release.yml publishes: the hash,
- # whitespace, the file name.
- $firstLine = (Get-Content -Path $shaPath -TotalCount 1)
- $expected = ''
- if ($firstLine) { $expected = ($firstLine.Trim() -split '\s+')[0].ToLowerInvariant() }
- # A captive portal answering every request with a login page is a real way
- # to get a .sha256 that parses into something. Sixty-four hex characters, or
- # this was not the release answering.
- if ($expected -notmatch '^[0-9a-f]{64}$') {
- $readBack = if ($expected) { $expected } else { '<empty>' }
- Fail 4 @(
- "the published checksum for $archive is not a SHA-256.",
- '',
- " $url.sha256",
- " read back: $readBack",
- '',
- 'Something other than the release answered that request. Nothing was',
- 'unpacked and nothing was installed.'
- )
- }
- $archivePath = Join-Path $tmp $archive
- $got = Get-File -Url $url -OutFile $archivePath
- if (-not $got.Ok) {
- $suffix = if ($got.Status) { " (HTTP $($got.Status))" } else { '' }
- Fail 3 @(
- "could not download $archive$suffix.",
- '',
- " $url",
- '',
- 'Nothing was installed.'
- )
- }
- $actual = Get-Sha256 -Path $archivePath
- # Before unpacking, and this is what the file is for. A script that
- # downloads an executable over the network and runs it without checking the
- # hash published beside it is a supply chain with a hole in the middle.
- #
- # What the check buys, stated honestly: it catches a truncated or corrupted
- # download, a mirror serving the wrong file, and an archive that is not the
- # one the release recorded. It is not a signature -- the hash comes from the
- # same host as the archive -- which is why the default host is GitHub over
- # TLS and why ANK_BASE_URL is documented as a mirror rather than as a
- # default.
- if ($expected -ne $actual) {
- Fail 4 @(
- "checksum mismatch, refusing to unpack $archive.",
- '',
- " expected: $expected",
- " actual: $actual",
- " published: $url.sha256",
- '',
- 'The download does not match the hash the release published beside it.',
- 'Nothing was unpacked and nothing was installed.',
- '',
- 'Retry once, in case the transfer was truncated. If it happens again, do',
- 'not install this archive, and say so:',
- " https://github.com/$Repo/security"
- )
- }
- Ok "checksum ok $actual"
- # Build provenance, which is what the checksum is not, on the terms
- # install.sh states at the same place: whoever can replace an archive on
- # the release page can replace its .sha256, and cannot forge the
- # attestation GitHub signs for the workflow run that built it. A signed-in
- # gh is asked, pinned to this repository and to that workflow, and a failure
- # refuses with or without -RequireProvenance. A release at or below 0.9.4
- # predates the attestations. Which check was made is said in one line.
- $attestedAfter = [version]'0.9.4'
- $signer = "$Repo/.github/workflows/release.yml"
- $releaseNumber = $null
- try { $releaseNumber = [version](($bare -split '[-+]')[0]) } catch { }
- $provenance = ''
- if (-not $releaseNumber -or $releaseNumber -le $attestedAfter) {
- $provenance = "$tag predates build provenance"
- } elseif (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
- $provenance = 'gh is not on PATH, so provenance was not checked'
- } else {
- $global:LASTEXITCODE = 0
- try { & gh auth status 2>&1 | Out-Null } catch { }
- if ($LASTEXITCODE -ne 0) {
- $provenance = 'gh is not signed in, so provenance was not checked'
- } else {
- $global:LASTEXITCODE = 0
- $said = @()
- try {
- $said = @(& gh attestation verify $archivePath --repo $Repo --signer-workflow $signer 2>&1 |
- ForEach-Object { "$_" })
- } catch {
- $said += "$($_.Exception.Message)"
- $global:LASTEXITCODE = 1
- }
- if ($LASTEXITCODE -ne 0) {
- Say ''
- foreach ($line in $said) { Say " $line" }
- Fail 4 @(
- "the build provenance of $archive did not verify, refusing to unpack it.",
- '',
- " gh attestation verify $archive --repo $Repo --signer-workflow $signer",
- '',
- 'The archive matches the checksum published beside it, and no attestation',
- "of this repository's release workflow vouches for it. Nothing was",
- 'unpacked and nothing was installed. Do not install this archive, and say so:',
- " https://github.com/$Repo/security"
- )
- }
- }
- }
- if ($provenance -and $RequireProvenance) {
- if ($provenance -like '*predates*') {
- Fail 4 @(
- "-RequireProvenance: $provenance.",
- '',
- "Releases above v$attestedAfter carry an attestation per archive. Pick one:",
- " & ([scriptblock]::Create((irm $RawUrl))) -Version <version> -RequireProvenance",
- '',
- 'Nothing was installed.'
- )
- }
- Fail 5 @(
- "-RequireProvenance: $provenance.",
- '',
- 'The check is gh attestation verify, which needs gh signed in:',
- ' https://cli.github.com',
- ' gh auth login',
- '',
- 'Nothing was installed.'
- )
- }
- if ($provenance) {
- Ok "verified: sha256 only ($provenance)"
- } else {
- Ok 'verified: sha256 and provenance'
- }
- try {
- Expand-Zip -Path $archivePath -Destination $tmp
- } catch {
- Fail 3 @(
- "could not unpack $archive.",
- '',
- " $($_.Exception.Message)",
- '',
- 'Nothing was installed.'
- )
- }
- # The layout release.yml packages: one directory named after the archive,
- # carrying the executable beside README.md, LICENSE and SKILL.md.
- #
- # ank.exe is required and the rest of the directory is not read at all. An
- # archive published before ADR-1ea31c2f3c5a carries a second executable
- # there, and the answer to it is the same as the answer to README.md: it is
- # not what was asked for, so it is not moved anywhere. A check that refused
- # an archive holding more than this would refuse every release published so
- # far.
- $unpacked = Join-Path $tmp "ank-$bare-$target"
- $binary = Join-Path $unpacked 'ank.exe'
- if (-not (Test-Path -Path $binary -PathType Leaf)) {
- Fail 3 @(
- "$archive does not contain ank.exe where this script expected it.",
- '',
- " looked for: ank-$bare-$target\ank.exe",
- '',
- 'Nothing was installed.'
- )
- }
- if (-not $Dir) {
- if (-not $env:LOCALAPPDATA) {
- Fail 1 @(
- 'LOCALAPPDATA is not set, so there is no default install directory.',
- '',
- 'Name one:',
- " & ([scriptblock]::Create((irm $RawUrl))) -Dir C:\tools\ank"
- )
- }
- $Dir = Join-Path $env:LOCALAPPDATA 'Programs\ank'
- }
- try {
- New-Item -ItemType Directory -Path $Dir -Force -ErrorAction Stop | Out-Null
- } catch {
- Fail 1 @(
- "could not create $Dir.",
- '',
- " $($_.Exception.Message)",
- '',
- 'Install somewhere writable, or run this from a shell that can write there:',
- " & ([scriptblock]::Create((irm $RawUrl))) -Dir `$env:LOCALAPPDATA\Programs\ank"
- )
- }
- $destination = Join-Path $Dir 'ank.exe'
- $failure = Move-IntoPlace -Source $binary -Destination $destination -Name 'ank.exe'
- if ($failure) {
- Fail 1 @(
- "could not write $destination.",
- '',
- " $failure",
- '',
- 'Something is holding the file open and it could not be renamed either.',
- 'Close any shell running ank and try again.',
- '',
- 'Nothing was installed.'
- )
- }
- $installedVersion = ''
- try {
- $installedVersion = (& $destination --version 2>$null | Select-Object -First 1)
- } catch {
- $installedVersion = ''
- }
- Say ''
- Ok "installed $destination"
- if ($installedVersion) { Say -Color $UiDim "$UiPad$UiPad $installedVersion" }
- # The last way left to leave a caller without a working `ank`: a binary in a
- # directory nothing looks in. Naming the command to run is the difference
- # between an install that worked and an install that appears not to have
- # run. The user PATH is not written by this script: it is a persistent
- # change to the caller's account, and an installer that makes one without
- # being asked is one they cannot undo by deleting what it installed.
- $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
- $onPath = ($env:Path -split ';' | Where-Object { $_.TrimEnd('\') -ieq $Dir.TrimEnd('\') })
- if ($onPath) {
- Say ''
- Say -NoNewline "$UiPad$Dir is on your PATH. Run: "
- Say -Color $UiCyan 'ank help'
- } else {
- Say ''
- Say "$UiPad$Dir is not on your PATH, so ``ank`` is not a command yet."
- Say "${UiPad}Add it for your account by running this once:"
- Say ''
- Say -Color $UiCyan "$UiPad [Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path','User') + ';$Dir', 'User')"
- Say ''
- Say "${UiPad}then open a new terminal. In this one:"
- Say ''
- Say -Color $UiCyan "$UiPad `$env:Path += ';$Dir'"
- if ($userPath -and $userPath.Length -gt 1800) {
- Say ''
- Say "${UiPad}Your user PATH is close to the length Windows truncates at, so check it"
- Say "${UiPad}after adding: a truncated PATH loses entries other tools put there."
- }
- }
- # Wrapped, and it is the whole guarantee in two lines rather than one.
- #
- # The try is the half install.sh spells `offer_skills || :`: a question
- # asked after a successful install may not turn that install into a
- # failure, so nothing thrown in there gets out of here.
- #
- # The stamp is the half that has no counterpart in install.sh, and it is
- # the one that would have been missed by reading. `pwsh -File install.ps1`
- # exits with $LASTEXITCODE, which every native command run above sets: with
- # nothing here, a skill step that failed would silently become this script's
- # exit code and the caller would read a green install as red. Assigned in the
- # global scope, because an assignment inside a script writes a script-local
- # variable that shadows it and changes nothing the host reads.
- try { Invoke-SkillOffer -Ank $destination } catch { }
- try { Invoke-AdoptionOffer } catch { }
- $global:LASTEXITCODE = 0
- } finally {
- if ($tmp -and (Test-Path -Path $tmp)) {
- Remove-Item -Path $tmp -Recurse -Force -ErrorAction SilentlyContinue
- }
- $ProgressPreference = $savedProgress
- [Net.ServicePointManager]::SecurityProtocol = $savedProtocol
- }
install.sh · Bundled script · 1,221 lines · 2 findings marked
- #!/bin/sh
- #
- # Install ank from a GitHub release.
- #
- # curl -fsSL https://raw.githubusercontent.com/haksolot/ank/main/install.sh | sh
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 5 on GitHub
- # curl -fsSL https://raw.githubusercontent.com/haksolot/ank/main/install.sh | sh -s -- --version v0.2.0
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 6 on GitHub
- #
- # One executable lands: `ank`. The protocol surface and the watcher are verbs of
- # it (ADR-1ea31c2f3c5a), so there is no second file for this script to place and
- # no way for one to fail to arrive.
- #
- # `--version` reaches releases published before that was true, whose archive
- # carries a second executable beside `ank`. Nothing here asks: the archive is
- # unpacked, `ank` is taken out of it, and whatever else the directory holds goes
- # with the temporary directory. So an old release installs the one file this
- # script promises, by the same code path a new one does -- an installer that
- # only worked on releases that do not exist yet would not be a working
- # installer.
- #
- # POSIX sh and no bashisms, deliberately. This is the channel for the Linux
- # distribution that will never have a native package, and the smallest of those
- # ship busybox ash with no bash at all. The binary is a static musl build, so
- # one archive covers every distribution -- but only if the script that fetches
- # it runs there too.
- #
- # Exit codes, so a caller can branch on the failure rather than on the message:
- #
- # 1 usage, or a directory that cannot be written
- # 2 unsupported platform
- # 3 the download failed, or the release does not carry this archive
- # 4 the checksum did not match the one the release published, or the
- # build provenance was checked and did not verify
- # 5 a tool this script needs is missing, gh included under
- # --require-provenance
- #
- # --no-welcome, or ANK_NO_WELCOME in the environment, turns off everything this
- # script draws for a human and everything it asks one, and leaves only the
- # lines a machine reads. It is absent from the list above on purpose: the
- # welcome is drawn before the first request goes out and the offer comes after
- # the binary is on disk and verified, so neither is on the path to any of them
- # -- a flag able to change one of these five codes would be a flag that made
- # the install depend on it.
- #
- set -eu
- repo="haksolot/ank"
- raw_url="https://raw.githubusercontent.com/${repo}/main/install.sh"
- releases_url="https://github.com/${repo}/releases"
- default_base_url="${releases_url}/download"
- # --------------------------------------------------------------------------
- # Output
- # --------------------------------------------------------------------------
- # Everything informational goes to stderr, because the interesting use of this
- # script is `curl ... | sh` and the caller may well be reading stdout.
- say() {
- printf '%s\n' "$*" >&2
- }
- # Colour and the marker, behind the gate the logo is drawn behind. Empty until
- # ui_enable runs, which is what keeps ADR-5fbd99bf6fd5's promise to a caller
- # with nobody at the end of it: a pipe reads the bytes it read before this file
- # learned about either.
- #
- # Every call site below spells the sequences out rather than asking a function
- # for them, so a line that is half plain and half painted is one string and not
- # a concatenation of three -- and the plain reading of it, with every variable
- # empty, is the line that used to be there.
- ui_off="" ui_bold="" ui_dim="" ui_cyan="" ui_green=""
- ui_pad="" ui_tick=""
- # `ok <line>`: a step that finished. The marker and the indent are drawn for a
- # person and for nobody else -- what a pipe reads is the sentence alone, which
- # is why the two live in variables rather than in the format string.
- ok() {
- say "${ui_pad}${ui_green}${ui_tick}${ui_off}$*"
- }
- # `die <code> <line>...`: the code carries the kind of failure, the lines carry
- # what to do next. Nothing here ever ends in silence -- that is the one thing
- # an install script cannot do, since the caller is otherwise left with no
- # binary and no idea why.
- die() {
- die_code=$1
- shift
- say "ank: $1"
- shift
- for die_line in "$@"; do
- say "$die_line"
- done
- exit "$die_code"
- }
- # --------------------------------------------------------------------------
- # Welcome
- # --------------------------------------------------------------------------
- # The logo, from assets/ank.svg read as pixels: twenty-four columns by ten
- # rows, one cell per pixel column and one row per pair of pixel rows, which is
- # the ratio that makes a terminal cell square. That file is the reference for
- # the shape and nothing here reads it: an installer that fetches a logo before
- # it fetches the binary is an installer with a second way to fail before doing
- # anything useful, so the shape is bytes in this file.
- #
- # U+2588 where the locale says UTF-8, `#` where it does not, decided once in
- # logo_charset. The hedge is the one the shebang makes -- this runs on busybox
- # under a locale nobody chose, and a logo that arrives as question marks is
- # worse than no logo at all -- but a locale that announces UTF-8 is a locale
- # that can draw a block, and the block is the whole difference between a logo
- # and a fence of hashes.
- #
- # \033 and not \e: the octal escape is the one POSIX printf guarantees, and \e
- # is a bashism in a file that has none.
- logo_esc=$(printf '\033')
- # Eleven spaces: columns 0 to 10, which is what stands to the left of the stem
- # on a row whose leg has not grown yet. Every such row is the same width, so
- # the padding is a constant rather than something measured -- ${#s} counts
- # bytes, and the moment the cell is U+2588 that is three times the answer.
- logo_pad11=" "
- # The cell, and the three runs the shape is made of, built once. A frame is
- # drawn seventeen times and must not repeat this work inside the loop.
- logo_charset() {
- case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
- *UTF-8* | *utf-8* | *UTF8* | *utf8*) logo_cell='█' ;;
- *) logo_cell='#' ;;
- esac
- logo_b2=$(logo_run 2)
- logo_b4=$(logo_run 4)
- logo_b14=$(logo_run 14)
- }
- logo_run() {
- logo_run_n=$1
- logo_run_s=""
- while [ "$logo_run_n" -gt 0 ]; do
- logo_run_s="${logo_run_s}${logo_cell}"
- logo_run_n=$((logo_run_n - 1))
- done
- printf '%s' "$logo_run_s"
- }
- # The mark carries no colour of its own. assets/ank.svg is #1f2328 and
- # assets/ank-dark.svg is #e6edf3 -- the same shape, black on a light ground and
- # white on a dark one -- and \033[39m is how a terminal spells that: the
- # foreground the reader already chose. A hue picked here would be a third logo
- # neither asset agrees with, and would be the one thing on the screen that does
- # not belong to the person running the installer.
- #
- # So the animation is built on the one axis that survives not knowing the
- # background: dim against normal. Brighter does not survive it -- bold on a
- # glyph that is already a solid block does nothing at all in a terminal that
- # does not render bold as bright, and white on a light ground is invisible. A
- # part therefore arrives dim and settles, and the shape blinks by going dim,
- # which reads the same on either ground.
- #
- # NO_COLOR empties all four rather than branching at each of the places they are
- # used, so a run without colour draws the same shape through the same code, on
- # the growth alone.
- logo_palette() {
- if [ -n "${NO_COLOR:-}" ]; then
- logo_lit="" logo_soft="" logo_name="" logo_off=""
- return
- fi
- logo_lit="${logo_esc}[39m"
- logo_soft="${logo_esc}[2;39m"
- logo_name="${logo_esc}[1m"
- logo_off="${logo_esc}[0m"
- }
- # The lines the install prints after the logo, which are not the mark and may
- # therefore carry a hue: bold for what landed, dim for what is incidental, cyan
- # for a command the reader is meant to run, green for a step that finished. Five
- # of the eight the binary allows itself, and the mark still uses none of them.
- #
- # The marker is U+2713 where the locale says
- # UTF-8 and `- ` where it does not, on the reasoning logo_charset is written
- # out for: a tick that arrives as a question mark is worse than no tick.
- #
- # The marker survives NO_COLOR, and that is the point of it being a character.
- # Nothing here is carried by colour alone -- take every sequence away and the
- # steps are still marked, and still say what they say.
- ui_enable() {
- ui_pad=" "
- ui_tick="- "
- case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
- *UTF-8* | *utf-8* | *UTF8* | *utf8*) ui_tick="✓ " ;;
- esac
- [ -z "${NO_COLOR:-}" ] || return 0
- ui_off="${logo_esc}[0m"
- ui_bold="${logo_esc}[1m"
- ui_dim="${logo_esc}[2m"
- ui_cyan="${logo_esc}[36m"
- ui_green="${logo_esc}[32m"
- }
- # One of rows 6 to 9: `<pad><leg><gap><stem><gap><leg>`, where a part that has
- # not grown yet gives up its columns to the eleven-space pad, so the parts that
- # have stay where they are. The trailing pad is never drawn -- \033[K ends the
- # line, and spaces that reach the right edge of a narrow window wrap it.
- logo_band() {
- lb_legs=$1 lb_legs_at=$2 lb_stem=$3 lb_stem_at=$4
- lb_run=$5 lb_gap=$6 lb_legs_c=$7 lb_stem_c=$8
- if [ "$lb_legs" -ge "$lb_legs_at" ]; then
- lb_left=" ${lb_legs_c}${lb_run}${logo_off}${lb_gap}"
- lb_right="${lb_gap}${lb_legs_c}${lb_run}${logo_off}"
- else
- lb_left=$logo_pad11
- lb_right=""
- fi
- if [ "$lb_stem" -ge "$lb_stem_at" ]; then
- lb_mid="${lb_stem_c}${logo_b2}${logo_off}"
- elif [ -n "$lb_right" ]; then
- lb_mid=" "
- else
- lb_left="" lb_mid=""
- fi
- printf '%s%s%s' "$lb_left" "$lb_mid" "$lb_right"
- }
- # One frame, whole, in one write. Twelve separate writes to a terminal are
- # twelve chances for a person to catch the logo half-drawn, and that flicker is
- # what makes an animation look cheap.
- #
- # The arguments are the state of the build and not a frame number: base is on or
- # off, legs and stem are how many of their rows have grown, loop is on or off,
- # soft names the part still arriving this frame, name is the wordmark. A
- # timeline written as states can be re-timed without recomputing which row is
- # which.
- #
- # Every sequence is closed on the run that opened it. A frame that ends with one
- # still open is a terminal somebody has to repair with `reset`.
- logo_frame() {
- lf_base=$1 lf_legs=$2 lf_stem=$3 lf_loop=$4 lf_soft=$5 lf_name=$6
- lf_loop_c=$logo_lit lf_stem_c=$logo_lit lf_legs_c=$logo_lit lf_base_c=$logo_lit
- case $lf_soft in
- loop) lf_loop_c=$logo_soft ;;
- stem) lf_stem_c=$logo_soft ;;
- legs) lf_legs_c=$logo_soft ;;
- base) lf_base_c=$logo_soft ;;
- all)
- lf_loop_c=$logo_soft lf_stem_c=$logo_soft
- lf_legs_c=$logo_soft lf_base_c=$logo_soft
- ;;
- esac
- # Rows 1 and 4, then 2 and 3: the loop is columns 10-13, then 8-9 with 14-15.
- if [ "$lf_loop" = 1 ]; then
- lf_r1=" ${lf_loop_c}${logo_b4}${logo_off}"
- lf_r2=" ${lf_loop_c}${logo_b2}${logo_off} ${lf_loop_c}${logo_b2}${logo_off}"
- else
- lf_r1="" lf_r2=""
- fi
- # Row 5, the stem alone, the last of its five rows to grow.
- if [ "$lf_stem" -ge 5 ]; then
- lf_r5=" ${lf_stem_c}${logo_b2}${logo_off}"
- else
- lf_r5=""
- fi
- # Rows 6-9 carry a leg on each side and the stem between them, and the three
- # arrive at different moments.
- lf_r6=$(logo_band "$lf_legs" 4 "$lf_stem" 4 "$logo_b4" " " "$lf_legs_c" "$lf_stem_c")
- lf_r7=$(logo_band "$lf_legs" 3 "$lf_stem" 3 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
- lf_r8=$(logo_band "$lf_legs" 2 "$lf_stem" 2 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
- lf_r9=$(logo_band "$lf_legs" 1 "$lf_stem" 1 "$logo_b2" " " "$lf_legs_c" "$lf_stem_c")
- # Row 10, the base, columns 5-18.
- if [ "$lf_base" = 1 ]; then
- lf_r10=" ${lf_base_c}${logo_b14}${logo_off}"
- else
- lf_r10=""
- fi
- if [ "$lf_name" = 1 ]; then
- lf_r12=" ${logo_name}ank${logo_off}"
- else
- lf_r12=""
- fi
- # \033[K clears what the previous frame left to the right of each line, which
- # is what lets a row shrink. Twelve lines every time, including the empty
- # ones: the redraw moves back over a fixed block, and a frame that were
- # shorter would leave the tail of the one before it on the screen.
- printf '%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n%s\033[K\n\033[K\n%s\033[K\n' \
- "$lf_r1" "$lf_r2" "$lf_r2" "$lf_r1" "$lf_r5" \
- "$lf_r6" "$lf_r7" "$lf_r8" "$lf_r9" "$lf_r10" "$lf_r12" >&2
- }
- # A frame, its delay, and the move back over the block it drew, so the caller's
- # timeline reads as states and never as cursor arithmetic. The last frame is
- # drawn by the caller instead, because it is the one that has to stay.
- logo_step() {
- logo_frame "$1" "$2" "$3" "$4" "$5" 0
- [ -z "$logo_delay" ] || sleep "$logo_delay"
- printf '\033[12A' >&2
- }
- # Bottom up: the base arrives dim and settles, the legs and then the stem grow
- # out of it a row at a time, the loop crowns them, and the whole shape blinks
- # twice before the name appears. That last beat is what the animation exists for
- # -- it costs the time it takes to read the name of the tool and not a second
- # more.
- draw_logo() {
- logo_charset
- logo_palette
- # POSIX sleep takes an integer, and every sleep this script is likely to meet
- # -- coreutils, BSD, busybox built with the fancy option -- takes a fraction.
- # The ones that do not are told apart by asking rather than by guessing:
- # without a delay the frames still draw, in the order they draw, as fast as
- # the terminal will take them.
- logo_fast=0.045 logo_beat=0.10 logo_hold=0.45
- sleep 0.01 2>/dev/null || { logo_fast="" logo_beat="" logo_hold=""; }
- # The cursor would otherwise blink in the middle of the drawing. Restored on
- # the way out and on the two signals a human sends, because a terminal left
- # with an invisible cursor is a terminal somebody has to repair with `reset`.
- # The reset travels with it: a ^C between the opening of a colour and its
- # close would otherwise leave the shell prompt dim.
- trap 'printf "%s[0m%s[?25h\n" "$logo_esc" "$logo_esc" >&2; exit 130' INT
- trap 'printf "%s[0m%s[?25h\n" "$logo_esc" "$logo_esc" >&2; exit 143' TERM
- printf '\033[?25l' >&2
- # The two parts that appear whole -- the base and the loop -- come in dim and
- # settle. The two that grow do not: growing a row at a time is already motion,
- # and dimming it as well would say the same thing twice.
- #
- # base legs stem loop soft
- logo_delay=$logo_beat
- logo_step 1 0 0 0 base
- logo_step 1 0 0 0 none
- logo_delay=$logo_fast
- logo_step 1 1 0 0 none
- logo_step 1 2 0 0 none
- logo_step 1 3 0 0 none
- logo_step 1 4 0 0 none
- logo_step 1 4 1 0 none
- logo_step 1 4 2 0 none
- logo_step 1 4 3 0 none
- logo_step 1 4 4 0 none
- logo_step 1 4 5 0 none
- logo_delay=$logo_beat
- logo_step 1 4 5 1 loop
- logo_step 1 4 5 1 none
- logo_delay=$logo_fast
- logo_step 1 4 5 1 all
- logo_step 1 4 5 1 none
- logo_step 1 4 5 1 all
- # The name, on the frame that stays. No move back after it, so what the
- # install says next begins under the logo rather than over it.
- logo_frame 1 4 5 1 none 1
- [ -z "$logo_hold" ] || sleep "$logo_hold"
- # The cursor comes back first and the blank line after it, so the last byte
- # this function writes is a newline: whatever the install says next starts on
- # a line of its own rather than behind an escape sequence.
- printf '\033[?25h\n' >&2
- trap - INT TERM
- }
- # ADR-5fbd99bf6fd5 read as an absence: where no human is looking, this script
- # draws nothing at all and asks nothing at all.
- #
- # Both streams are tested and not only one. Under `curl ... | sh` stdin is the
- # script and both of the others are the terminal, which is the case that must
- # animate; under `sh install.sh > install.log` stderr is still a terminal, and
- # a log file full of cursor movements is exactly the noise this must never
- # produce. /dev/tty is the third test and the one the decision names: no
- # controlling terminal means a provisioning script, a Dockerfile or a runner,
- # whatever the streams happen to say.
- #
- # The logo and the offer read this same answer, which is what makes
- # --no-welcome and an interactive run that declined everything leave the same
- # machine behind: one predicate, so there is no second gate to disagree with
- # this one.
- human_at_terminal() {
- [ "$no_welcome" = no ] || return 1
- [ -t 1 ] || return 1
- [ -t 2 ] || return 1
- # A runner sets this, and some runner images hand their steps a pty.
- [ -z "${CI:-}" ] || return 1
- # A terminal that says it cannot move a cursor is taken at its word.
- case "${TERM:-}" in
- "" | dumb) return 1 ;;
- esac
- # A subshell: a redirection that fails on a special builtin is fatal to the
- # shell itself, and this test exists to be answered no.
- ( : > /dev/tty ) 2>/dev/null || return 1
- }
- # The width is about the block of art and about nothing else, so it is here and
- # not above: a window too narrow to hold the logo is still a window with a
- # person in front of it, and a question fits in twenty columns.
- welcome_wanted() {
- human_at_terminal || return 1
- # A window narrower than the art wraps every line, and a block that is taller
- # than twelve rows is a block the redraw moves back over the middle of. Asked
- # of tput, and only believed when it answers a number: a machine without it
- # is a machine this refuses to guess about in the direction of drawing.
- logo_cols=$(tput cols 2>/dev/null) || logo_cols=""
- case "$logo_cols" in
- "" | *[!0-9]*) : ;;
- *) [ "$logo_cols" -ge 24 ] || return 1 ;;
- esac
- }
- # --------------------------------------------------------------------------
- # Platforms
- # --------------------------------------------------------------------------
- # The targets release.yml builds, minus Windows, which ships a .zip that this
- # script has no business unpacking. Written once and read by both the refusal
- # and the help text: a list that says one thing when it refuses and another
- # when it is asked is worse than no list at all.
- supported_lines() {
- cat <<'EOF'
- Linux x86_64 x86_64-unknown-linux-musl
- Linux arm64 aarch64-unknown-linux-musl
- Darwin arm64 aarch64-apple-darwin
- Darwin x86_64 x86_64-apple-darwin
- EOF
- }
- usage() {
- cat >&2 <<EOF
- install ank from a GitHub release
- One executable lands in the install directory: ank. The protocol surface and
- the watcher are verbs of it -- ank mcp, ank watch -- so there is nothing
- further to fetch and nothing further to configure a client against.
- usage:
- install.sh [--version <version>] [--dir <path>]
- curl -fsSL ${raw_url} | sh
- curl -fsSL ${raw_url} | sh -s -- --version v0.2.0
- options:
- --version <version> install this release instead of the latest one;
- "v0.2.0" and "0.2.0" both work
- --dir <path> install into <path> instead of \$HOME/.local/bin
- --no-welcome draw nothing and ask nothing; install exactly what an
- interactive run that declined every offer installs
- --require-provenance refuse unless gh verifies the archive's build
- provenance; without it, provenance is checked when a
- signed-in gh is on PATH and the checksum stands alone
- otherwise
- -h, --help print this and exit
- environment:
- ANK_VERSION same as --version
- ANK_INSTALL_DIR same as --dir
- ANK_NO_WELCOME same as --no-welcome, for a caller that pipes this
- script into sh and cannot pass an argument to it
- ANK_BASE_URL where the archives are fetched from, for a mirror or a
- staged release; requires --version, since only GitHub
- can be asked which release is the latest
- ANK_REQUIRE_PROVENANCE
- same as --require-provenance
- platforms:
- $(supported_lines)
- Windows is published as a .zip and this script does not install it:
- ${releases_url}
- the two questions:
- With a terminal attached, once ank is installed and verified, this asks
- two things and nothing else. The first offers to run:
- ank skills --install
- which teaches an agent how to use ank. The second offers to print three
- prompts that adopt ank in a repository that already has code and no
- .ank; they are in docs/quickstart.md too, and printing them writes
- nothing anywhere.
- Enter accepts each, declining either does nothing at all, and nothing
- either does can change any of the codes below.
- exit codes:
- 1 usage 2 unsupported platform 3 download 4 checksum or provenance
- 5 missing tool
- EOF
- }
- # Sets \$target, or refuses naming the pair it saw. uname -m is normalised
- # first, because one machine answers differently depending on the distribution:
- # amd64 and x86_64 are one target, aarch64 and arm64 are another.
- detect_target() {
- detect_os=$(uname -s 2>/dev/null) || detect_os=unknown
- detect_raw=$(uname -m 2>/dev/null) || detect_raw=unknown
- detect_arch=$detect_raw
- case "$detect_arch" in
- x86_64 | amd64) detect_arch=x86_64 ;;
- aarch64 | arm64) detect_arch=arm64 ;;
- esac
- case "${detect_os}/${detect_arch}" in
- Linux/x86_64) target=x86_64-unknown-linux-musl ;;
- Linux/arm64) target=aarch64-unknown-linux-musl ;;
- Darwin/arm64) target=aarch64-apple-darwin ;;
- Darwin/x86_64) target=x86_64-apple-darwin ;;
- *)
- say "ank: no release archive for ${detect_os}/${detect_arch}."
- say ""
- say "uname reported: ${detect_os} ${detect_raw}"
- say ""
- say "The release carries these:"
- supported_lines >&2
- say ""
- say "Windows is published as a .zip and this script does not install it."
- say "Everything the release carries is listed at:"
- say " ${releases_url}"
- say ""
- say "Nothing was installed."
- exit 2
- ;;
- esac
- }
- # --------------------------------------------------------------------------
- # Tools
- # --------------------------------------------------------------------------
- have() {
- command -v "$1" >/dev/null 2>&1
- }
- # curl or wget, whichever is there. Both are missing often enough on a minimal
- # container image that naming the two that would work is worth the lines.
- pick_downloader() {
- if have curl; then
- downloader=curl
- elif have wget; then
- downloader=wget
- else
- die 5 "neither curl nor wget is installed, so nothing can be downloaded." \
- "" \
- "Install one of them and run this again:" \
- " apt-get install -y curl # debian, ubuntu" \
- " apk add curl # alpine" \
- " dnf install -y curl # fedora, rhel"
- fi
- }
- # sha256sum on Linux, shasum on macOS, openssl as the fallback that is on
- # nearly everything else. If none of the three is present the script stops
- # here rather than installing unverified: skipping the check is the failure
- # this whole file is shaped to avoid, so it is not allowed to be the thing
- # that degrades quietly.
- pick_sha_tool() {
- if have sha256sum; then
- sha_tool=sha256sum
- elif have shasum; then
- sha_tool=shasum
- elif have openssl; then
- sha_tool=openssl
- else
- die 5 "no way to compute a SHA-256 on this machine." \
- "" \
- "The release publishes a .sha256 beside every archive and this script" \
- "refuses to unpack one it could not verify. Install any of these:" \
- " sha256sum (coreutils), shasum (perl), openssl" \
- "" \
- "Nothing was installed."
- fi
- }
- sha256_of() {
- case "$sha_tool" in
- sha256sum) sha256sum "$1" | awk '{print $1}' ;;
- shasum) shasum -a 256 "$1" | awk '{print $1}' ;;
- openssl) openssl dgst -sha256 "$1" | awk '{print $NF}' ;;
- esac
- }
- lower() {
- printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
- }
- # `newer_than <a> <b>`: whether release a is above release b, read as
- # MAJOR.MINOR.PATCH with any prerelease or build suffix set aside. awk rather
- # than `sort -V`, which busybox and macOS do not both have.
- newer_than() {
- awk -v a="${1%%[-+]*}" -v b="${2%%[-+]*}" 'BEGIN {
- split(a, x, "."); split(b, y, ".")
- for (i = 1; i <= 3; i++) {
- if (x[i] + 0 > y[i] + 0) exit 0
- if (x[i] + 0 < y[i] + 0) exit 1
- }
- exit 1
- }'
- }
- # --------------------------------------------------------------------------
- # Downloading
- # --------------------------------------------------------------------------
- # `fetch <url> <path>`. Returns non-zero on failure and leaves the HTTP status
- # in \$fetch_status when it has one, because "this release does not carry that
- # archive" and "the network is down" are different messages and the 404 is
- # what tells them apart.
- fetch() {
- fetch_url=$1
- fetch_out=$2
- fetch_status=""
- if [ "$downloader" = curl ]; then
- # No -f: with it curl returns non-zero and the status is harder to read
- # back out. The status is checked here instead, which is the same
- # guarantee with a better message.
- fetch_status=$(curl -sSL --retry 3 --retry-delay 1 \
- -o "$fetch_out" -w '%{http_code}' "$fetch_url" 2>/dev/null) || fetch_status=""
- case "$fetch_status" in
- 2??) return 0 ;;
- *) return 1 ;;
- esac
- else
- # wget does not hand the status back, so the caller falls through to the
- # general message. Parsing wget's stderr for it is not more reliable than
- # saying less.
- wget -q -O "$fetch_out" "$fetch_url" 2>/dev/null || return 1
- return 0
- fi
- }
- # The tag of the latest release, read off the redirect rather than through the
- # API: /releases/latest redirects to /releases/tag/<tag>, which costs no rate
- # limit, where api.github.com allows sixty unauthenticated calls an hour per
- # address and a shared CI runner or an office NAT can be out of them before
- # anyone types this.
- resolve_latest() {
- if [ "$downloader" = curl ]; then
- resolved=$(curl -sSL -o /dev/null -w '%{url_effective}' \
- "${releases_url}/latest" 2>/dev/null) || resolved=""
- tag=${resolved##*/}
- else
- # wget does not report the URL it landed on, so the one place the API is
- # called is here, on the machine that has no curl.
- tag=$(wget -q -O - "https://api.github.com/repos/${repo}/releases/latest" 2>/dev/null |
- sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' |
- head -1) || tag=""
- fi
- case "$tag" in
- v*) : ;;
- *)
- die 3 "could not work out which release is the latest." \
- "" \
- "Name one instead:" \
- " install.sh --version v0.2.0" \
- "" \
- "The releases are listed at:" \
- " ${releases_url}"
- ;;
- esac
- }
- # --------------------------------------------------------------------------
- # Arguments
- # --------------------------------------------------------------------------
- version=${ANK_VERSION:-}
- install_dir=${ANK_INSTALL_DIR:-}
- base_url=${ANK_BASE_URL:-}
- no_welcome=no
- [ -z "${ANK_NO_WELCOME:-}" ] || no_welcome=yes
- require_provenance=no
- [ -z "${ANK_REQUIRE_PROVENANCE:-}" ] || require_provenance=yes
- while [ $# -gt 0 ]; do
- case "$1" in
- --version)
- [ $# -ge 2 ] ||
- die 1 "--version needs a value." "" " install.sh --version v0.2.0"
- version=$2
- shift 2
- ;;
- --version=*)
- version=${1#--version=}
- shift
- ;;
- --dir)
- [ $# -ge 2 ] ||
- die 1 "--dir needs a value." "" " install.sh --dir \$HOME/.local/bin"
- install_dir=$2
- shift 2
- ;;
- --dir=*)
- install_dir=${1#--dir=}
- shift
- ;;
- --no-welcome)
- no_welcome=yes
- shift
- ;;
- --require-provenance)
- require_provenance=yes
- shift
- ;;
- -h | --help)
- usage
- exit 0
- ;;
- *)
- die 1 "unknown option: $1" \
- "" \
- "Run it with --help to see what it takes:" \
- " install.sh --help"
- ;;
- esac
- done
- if [ -n "$base_url" ]; then
- case "$base_url" in
- http://* | https://*) : ;;
- *)
- die 1 "ANK_BASE_URL must start with http:// or https://, got: ${base_url}" \
- "" \
- "Unset it to fetch from the GitHub release:" \
- " unset ANK_BASE_URL"
- ;;
- esac
- if [ -z "$version" ]; then
- die 1 "ANK_BASE_URL is set, so the version has to be named." \
- "" \
- "Only GitHub can be asked which release is the latest; a mirror cannot." \
- " install.sh --version v0.2.0"
- fi
- fi
- # --------------------------------------------------------------------------
- # Install
- # --------------------------------------------------------------------------
- # Before anything is asked of the network, which is what "before the download
- # starts" has to mean here: the first request this script makes is the redirect
- # that resolves the latest tag, and it is below.
- # The colour is turned on by the presence of a human and not by the width of
- # their window: a terminal too narrow for the logo is still a terminal, and the
- # sentence it is too narrow for is the one nobody wrote yet.
- if human_at_terminal; then
- ui_enable
- fi
- if welcome_wanted; then
- draw_logo
- fi
- pick_downloader
- pick_sha_tool
- detect_target
- # The second form is BSD mktemp's, which wants a template where GNU's is happy
- # without one. Both spellings rather than the one that works on the machine
- # this was written on.
- tmp=$(mktemp -d 2>/dev/null) || tmp=$(mktemp -d -t ank 2>/dev/null) || tmp=""
- [ -n "$tmp" ] || die 5 "could not create a temporary directory."
- # On the ordinary exit as well, so a refusal below leaves nothing behind.
- trap 'rm -rf "$tmp"' EXIT
- trap 'rm -rf "$tmp"; exit 130' INT
- trap 'rm -rf "$tmp"; exit 143' TERM
- if [ -n "$version" ]; then
- # "v0.2.0" and "0.2.0" are the same request. The tag carries the v and the
- # archive name does not, and making the caller know which is which is the
- # kind of detail a released script gets to absorb.
- tag=v${version#v}
- else
- resolve_latest
- fi
- bare=${tag#v}
- archive="ank-${bare}-${target}.tar.gz"
- url="${base_url:-$default_base_url}/${tag}/${archive}"
- say "${ui_pad}${ui_bold}ank ${tag}${ui_off} ${ui_dim}${target}${ui_off}"
- # The checksum first: it is the smaller of the two files, so a release that
- # does not carry this target says so before megabytes move. It is also the
- # request that answers "is this platform in this release", which is a question
- # the caller deserves answered rather than left as a stalled download.
- if ! fetch "${url}.sha256" "${tmp}/sha256"; then
- if [ "$fetch_status" = 404 ]; then
- die 3 "${tag} does not carry an archive for this platform." \
- "" \
- " looked for: ${archive}" \
- " at: ${url}" \
- "" \
- "The platform is one this project builds for, so this is about the" \
- "release and not about the machine. What ${tag} carries is listed at:" \
- " ${releases_url}/tag/${tag}" \
- "" \
- "Pick a release that carries it:" \
- " install.sh --version <version>" \
- "" \
- "Nothing was installed."
- fi
- die 3 "could not download the checksum for ${archive}${fetch_status:+ (HTTP ${fetch_status})}." \
- "" \
- " ${url}.sha256" \
- "" \
- "Nothing was installed."
- fi
- expected=$(lower "$(awk 'NR==1 {print $1}' "${tmp}/sha256")")
- # A captive portal answering every request with a login page is a real way to
- # get a .sha256 that parses into something. Sixty-four hex characters, or this
- # was not the release answering.
- case "$expected" in
- *[!0-9a-f]* | "") expected_ok=no ;;
- *) [ "${#expected}" -eq 64 ] && expected_ok=yes || expected_ok=no ;;
- esac
- if [ "$expected_ok" = no ]; then
- die 4 "the published checksum for ${archive} is not a SHA-256." \
- "" \
- " ${url}.sha256" \
- " read back: ${expected:-<empty>}" \
- "" \
- "Something other than the release answered that request. Nothing was" \
- "unpacked and nothing was installed."
- fi
- if ! fetch "$url" "${tmp}/${archive}"; then
- die 3 "could not download ${archive}${fetch_status:+ (HTTP ${fetch_status})}." \
- "" \
- " ${url}" \
- "" \
- "Nothing was installed."
- fi
- actual=$(lower "$(sha256_of "${tmp}/${archive}")")
- # Before unpacking, and this is what the file is for. A script that downloads
- # an executable over the network and runs it without checking the hash
- # published beside it is a supply chain with a hole in the middle.
- #
- # What the check buys, stated honestly: it catches a truncated or corrupted
- # download, a mirror serving the wrong file, and an archive that is not the
- # one the release recorded. It is not a signature -- the hash comes from the
- # same host as the archive -- which is why the default host is GitHub over TLS
- # and why ANK_BASE_URL is documented as a mirror rather than as a default.
- if [ "$expected" != "$actual" ]; then
- die 4 "checksum mismatch, refusing to unpack ${archive}." \
- "" \
- " expected: ${expected}" \
- " actual: ${actual}" \
- " published: ${url}.sha256" \
- "" \
- "The download does not match the hash the release published beside it." \
- "Nothing was unpacked and nothing was installed." \
- "" \
- "Retry once, in case the transfer was truncated. If it happens again, do" \
- "not install this archive, and say so:" \
- " https://github.com/${repo}/security"
- fi
- ok "checksum ok ${ui_dim}${actual}${ui_off}"
- # Build provenance, which is what the checksum is not. Whoever can replace an
- # archive on the release page can replace the .sha256 beside it; neither can
- # forge the attestation release.yml records for every archive it builds,
- # because that is signed by GitHub for the workflow run that built the file.
- # So a gh that can ask the API is asked, pinned to this repository and to the
- # workflow that builds, and a failure is a refusal whether or not the caller
- # asked for the check: an archive that matched its hash and failed the
- # stronger test is the one case this exists for.
- #
- # A release at or below 0.9.4 was published before the attestations, so for it
- # the question has no answer to ask for. Which check was made is said in one
- # line, every time, so a log shows what an install rested on.
- attested_after=0.9.4
- signer="${repo}/.github/workflows/release.yml"
- if ! newer_than "$bare" "$attested_after"; then
- provenance="${tag} predates build provenance"
- elif ! have gh; then
- provenance="gh is not on PATH, so provenance was not checked"
- elif ! gh auth status >/dev/null 2>&1; then
- provenance="gh is not signed in, so provenance was not checked"
- elif gh attestation verify "${tmp}/${archive}" --repo "$repo" \
- --signer-workflow "$signer" >"${tmp}/attestation" 2>&1; then
- provenance=""
- else
- say ""
- sed 's/^/ /' "${tmp}/attestation" >&2
- die 4 "the build provenance of ${archive} did not verify, refusing to unpack it." \
- "" \
- " gh attestation verify ${archive} --repo ${repo} --signer-workflow ${signer}" \
- "" \
- "The archive matches the checksum published beside it, and no attestation" \
- "of this repository's release workflow vouches for it. Nothing was" \
- "unpacked and nothing was installed. Do not install this archive, and say so:" \
- " https://github.com/${repo}/security"
- fi
- if [ -n "$provenance" ] && [ "$require_provenance" = yes ]; then
- case "$provenance" in
- *predates*)
- die 4 "--require-provenance: ${provenance}." \
- "" \
- "Releases above v${attested_after} carry an attestation per archive. Pick one:" \
- " install.sh --version <version> --require-provenance" \
- "" \
- "Nothing was installed."
- ;;
- *)
- die 5 "--require-provenance: ${provenance}." \
- "" \
- "The check is gh attestation verify, which needs gh signed in:" \
- " https://cli.github.com" \
- " gh auth login" \
- "" \
- "Nothing was installed."
- ;;
- esac
- fi
- if [ -n "$provenance" ]; then
- ok "verified: sha256 only ${ui_dim}(${provenance})${ui_off}"
- else
- ok "verified: sha256 and provenance"
- fi
- tar xzf "${tmp}/${archive}" -C "$tmp" ||
- die 3 "could not unpack ${archive}." "" "Nothing was installed."
- # The layout release.yml packages: one directory named after the archive,
- # carrying the executable beside README.md, LICENSE and SKILL.md.
- #
- # `ank` is required and the rest of the directory is not read at all. An
- # archive published before ADR-1ea31c2f3c5a carries a second executable there,
- # and the answer to it is the same as the answer to README.md: it is not what
- # was asked for, so it is not moved anywhere. A check that refused an archive
- # holding more than this would refuse every release published so far.
- unpacked="${tmp}/ank-${bare}-${target}"
- binary="${unpacked}/ank"
- if [ ! -f "$binary" ]; then
- die 3 "${archive} does not contain ank where this script expected it." \
- "" \
- " looked for: ank-${bare}-${target}/ank" \
- "" \
- "Nothing was installed."
- fi
- if [ -z "$install_dir" ]; then
- [ -n "${HOME:-}" ] ||
- die 1 "HOME is not set, so there is no default install directory." \
- "" \
- "Name one:" \
- " install.sh --dir /usr/local/bin"
- install_dir="${HOME}/.local/bin"
- fi
- mkdir -p "$install_dir" 2>/dev/null ||
- die 1 "could not create ${install_dir}." \
- "" \
- "Install somewhere writable, or run this with the rights to write there:" \
- " install.sh --dir \$HOME/.local/bin"
- [ -w "$install_dir" ] ||
- die 1 "${install_dir} is not writable." \
- "" \
- "Install somewhere writable, or run this with the rights to write there:" \
- " install.sh --dir \$HOME/.local/bin"
- chmod +x "$binary"
- # A rename into place rather than a copy over the file: on Linux, replacing a
- # binary that is currently running is fine, writing into it is not.
- mv -f "$binary" "${install_dir}/ank" ||
- die 1 "could not write ${install_dir}/ank." "" "Nothing was installed."
- installed_version=$("${install_dir}/ank" --version 2>/dev/null | head -1) ||
- installed_version=""
- say ""
- ok "installed ${ui_bold}${install_dir}/ank${ui_off}"
- if [ -n "$installed_version" ]; then
- say "${ui_pad}${ui_pad} ${ui_dim}${installed_version}${ui_off}"
- fi
- # The last way left to leave a caller without a working `ank`: a binary in a
- # directory nothing looks in. Naming the line to add is the difference between
- # an install that worked and an install that appears not to have run.
- case ":${PATH}:" in
- *":${install_dir}:"*)
- say ""
- say "${ui_pad}${install_dir} is on your PATH. Run: ${ui_cyan}ank help${ui_off}"
- ;;
- *)
- case "${SHELL:-}" in
- */fish)
- path_line="fish_add_path ${install_dir}"
- path_file="~/.config/fish/config.fish"
- ;;
- */zsh)
- path_line="export PATH=\"${install_dir}:\$PATH\""
- path_file="~/.zshrc"
- ;;
- */bash)
- path_line="export PATH=\"${install_dir}:\$PATH\""
- path_file="~/.bashrc"
- ;;
- *)
- path_line="export PATH=\"${install_dir}:\$PATH\""
- path_file="your shell's startup file"
- ;;
- esac
- say ""
- say "${ui_pad}${install_dir} is not on your PATH, so \`ank\` is not a command yet."
- say "${ui_pad}Add this line to ${ui_bold}${path_file}${ui_off}:"
- say ""
- say "${ui_pad} ${ui_cyan}${path_line}${ui_off}"
- say ""
- say "${ui_pad}then open a new shell, or run that line now in this one."
- ;;
- esac
- # --------------------------------------------------------------------------
- # The skills
- # --------------------------------------------------------------------------
- # ADR-5fbd99bf6fd5's offer, and the last thing this script does. Everything
- # above has already happened: the binary is on disk, verified, reported, and
- # the PATH advice given. That ordering is the decision rather than a layout --
- # an installation that stops to ask something is an installation that can be
- # abandoned half-done, and half-done is the worst state for a tool whose next
- # action is `ank context`.
- #
- # The question is this script's and the answer is the binary's
- # (ADR-e1d750884b82). `ank skills --install` writes out the skills it carries
- # and hands them to the skills CLI, which serves every agent it knows about
- # rather than one, and the verb already decides what to say when node is
- # missing and what a failure means. A second copy of that logic here would be
- # a second copy to drift.
- offer_skills() {
- human_at_terminal || return 0
- say ""
- say "${ui_pad}The skills teach an agent how to use ank: the contract, and one policy"
- say "${ui_pad}per activity. They install through the skills CLI, which puts them where"
- say "${ui_pad}each agent looks."
- say ""
- say "${ui_pad} ${ui_cyan}ank skills --install${ui_off}"
- say ""
- # /dev/tty and nowhere else, which is the trap ADR-5fbd99bf6fd5 exists to
- # name. Under `curl ... | sh` standard input is this script: a plain `read`
- # would consume the rest of the file and execute none of it, and it would do
- # so only on the route people actually use, having worked in every local test
- # where the script was run from a file.
- # Three calls, and the question is a literal in the middle one. Written as a
- # single format string with the emphasis as placeholders, the sentence is
- # split across them and stops being a sentence anyone can find: the tests
- # count this string in this file to know it is asked exactly once, and a
- # question that cannot be counted is a question that can quietly be asked
- # twice. What a pipe reads is unchanged either way -- the first and last call
- # write nothing at all until ui_enable has run.
- printf '%s%s' "$ui_pad" "$ui_bold" >&2
- printf 'Install them now? [Y/n] ' >&2
- printf '%s' "$ui_off" >&2
- if ! IFS= read -r offer_answer < /dev/tty; then
- # End of input rather than an answer. Nothing was typed, so nothing is
- # assumed, and the newline is ours because no Enter was pressed to echo
- # one.
- say ""
- return 0
- fi
- # Enter is yes and everything unrecognised is no, in that order: a default
- # the criterion names, and a decline for anything else because asking twice
- # is asking twice.
- case "$offer_answer" in
- "" | y | Y | yes | Yes | YES) : ;;
- *) return 0 ;;
- esac
- # The binary just installed, by the path it was installed at: the directory
- # may not be on PATH, and a different `ank` found there would answer for a
- # build this script did not place.
- #
- # Two redirections, each doing something this cannot work without.
- #
- # `< /dev/null` because standard input is still this script under
- # `curl ... | sh`: the verb asks nothing and reads nothing, and this is what
- # makes that a guarantee rather than a property of one build of it.
- #
- # `>&2` for the reason `say` writes there: stdout belongs to whoever is
- # reading `curl ... | sh`. A redirection and not a pipe, so nothing is
- # buffered and the terminal shows the skills CLI working while it works.
- #
- # Nothing is printed on success, and that is deliberate: the verb exits 0
- # both when the skills went in and when node is missing and it printed the
- # command to run instead, so a line of this script's own would be claiming
- # something only the verb's output knows.
- offer_code=0
- "${install_dir}/ank" skills --install < /dev/null >&2 || offer_code=$?
- if [ "$offer_code" -ne 0 ]; then
- say ""
- say "ank skills --install exited ${offer_code}, so the skills are not"
- say "installed. ank is, and it is exactly the ank this script installs when"
- say "nobody is asked anything at all."
- say ""
- say "Run it again when you want them:"
- say "${ui_pad} ${ui_cyan}ank skills --install${ui_off}"
- fi
- }
- # --------------------------------------------------------------------------
- # Adopting ank where there is already code
- # --------------------------------------------------------------------------
- # ADR-5fbd99bf6fd5's second offer, and the last question this script asks.
- # Installing ank is the easy half. The half nobody had written down is what to
- # say to an agent so that a repository with two years of history acquires a
- # corpus worth having, and the moment after an install is the one moment the
- # person is certainly reading.
- #
- # Three prompts, because the adoption has three moments: state as ADRs what the
- # code already decided, so the constraints that exist implicitly become
- # readable; turn a list of intentions into tasks carrying a scope and a
- # criterion; and check what came out. The first one is the one the reader
- # judges the tool on, which is why it is first.
- #
- # The same three prose blocks live in install.ps1 and in docs/quickstart.md,
- # and a test holds the three copies character for character
- # (crates/ank-cli/tests/adopt.rs). Prose duplicated in three files diverges, and
- # this is the prose where divergence is worst: an installer teaching a prompt
- # the documentation has since corrected. The markers below are what the test
- # reads; the block between them is the one to edit, and the other two follow.
- # adopt-prompts:begin
- adopt_walkthrough() {
- cat >&2 <<'ADOPT_EOF'
- In a repository that already has code and no .ank, start with:
- ank init
- Then paste these three into your agent, one at a time, and read what each
- one produces before you send the next.
- 1. What the code already decided:
- Read this repository and write, as ank ADRs, the decisions its code
- has already made: the ones a newcomer would break without knowing
- they existed. One ADR per decision, each with a scope glob covering
- the files it binds and a constraint stated as a rule. Leave them
- proposed; I ratify them myself.
- 2. What is still owed:
- Read the TODOs, the open issues and the README of this repository,
- and turn what they promise into ank tasks. Give each one a scope
- glob and a done_criteria a test could settle, and use blocked_by
- only where a task genuinely waits on another.
- 3. What you now have:
- Run ank check and ank review here, then read every ADR back against
- the code its scope matches. Tell me which constraints the code
- already breaks and which scopes match no file, and change nothing
- until I have read your answer.
- The same three are in docs/quickstart.md, which says what to expect
- from each:
- https://github.com/haksolot/ank/blob/main/docs/quickstart.md
- ADOPT_EOF
- }
- # adopt-prompts:end
- # The second question, asked on the same terms as the first: only with a human
- # at a terminal, from /dev/tty and nowhere else, with a default Enter accepts.
- # Declining prints nothing -- not a shortened version, not a pointer to one.
- # An offer that answers a no with half of a yes is an offer that was not really
- # asked.
- offer_adoption() {
- human_at_terminal || return 0
- say ""
- # One literal in one call, for the reason the skills question is: the tests
- # count this sentence in this file, and emphasis written as placeholders cuts
- # it in half.
- printf '%s%s' "$ui_pad" "$ui_bold" >&2
- printf 'Print the three prompts that adopt ank in a repository you already have? [Y/n] ' >&2
- printf '%s' "$ui_off" >&2
- if ! IFS= read -r adopt_answer < /dev/tty; then
- # End of input rather than an answer. The newline is ours because no Enter
- # was pressed to echo one.
- say ""
- return 0
- fi
- case "$adopt_answer" in
- "" | y | Y | yes | Yes | YES) : ;;
- *) return 0 ;;
- esac
- say ""
- # To stderr, for the reason `say` writes there: the interesting use of this
- # script is `curl ... | sh`, and stdout belongs to whoever is reading it.
- adopt_walkthrough
- say ""
- }
- # `|| :` on each and not a bare call, and it is the whole guarantee in two
- # lines. These are the last commands in the file, so the script's status is the
- # status of the last of them: with `set -e` in force a single failure anywhere
- # inside either would become the exit code of an install that has already
- # succeeded. Called this way, the failure is tested rather than fatal, `set -e`
- # is suspended for the duration, and the status this script leaves with is the
- # status it had before the first question was asked.
- offer_skills || :
- offer_adoption || :
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.