Files
ruflo/plugins/ruflo-console/hooks/data/adr-write.ts
T
Mario JauvinandRuFlo 3a650ce747 fix(ruflo-console): Windows fixes from running every view on a real Windows machine (console 0.49.1, cost-tracker 0.28.3) (#4490)
* fix(ruflo-console): Plugin Catalog reads a Windows marketplace clone (0.47.1)

Claude Code records the ruflo marketplace clone's installLocation as a drive
path (C:\Users\...\marketplaces\ruflo). readCatalog refused any location not
starting with "/", so the catalog showed "the clone's marketplace.json is not
readable" with the file in place.

- readCatalog uses isAbsolutePath / hasParentSegment from paths.ts.
- The catalog's plugin folders, manifests, skill/agent/command reads and the
  snapshot's marketplace.json read (freshness row) build paths with joinPath
  instead of a hardcoded "/".
- tests/windows-drive-path-sites.spec.ts: a Windows clone lists its plugins,
  reads a skill file, and still refuses a relative or climbing location. The
  new tests fail without the fix.
- Version 0.47.0 -> 0.47.1 in plugin.json, hooks/version.ts, scripts/smoke.sh
  and CHANGELOG.md.

The other ruflo-console specs fail the same 12 tests with and without this
change on this machine (mission-cost, menu-entry, tui-ai-page, write-argv).

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): forget-history actions and TUI colour work on Windows

- Events "forget history" and Workflows "forget saved views" ran `rm -f`, which
  Windows does not have (write-flavor.ts: no delete on host-fs). On host-fs they
  now empty the file(s) through the host file API (new emptyFiles in
  write-via.ts; forgetSpec carries a `write` op like event-export does). The
  saved-views file is rewritten as a valid empty document, and the forget is
  verified by what the file holds. Linux/macOS keep the rm argv.
- depthOf returned "none" whenever TERM was unset. Windows Terminal, PowerShell
  and cmd leave TERM unset (COLORTERM=truecolor, OS=Windows_NT), so the
  standalone TUI drew without colour. On Windows only an explicit TERM=dumb or
  NO_COLOR turns colour off.

Tests: both forget actions in host-fs flavor (files emptied, no rm run, refusal
reported, missing file left alone), forgetSpec verification, depthOf on Windows.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): ADR status edits on CRLF records, and codex detection, on Windows

- withStatus / withSupersedes compared whole lines ("---") and checked
  startsWith("---\n"), so a MADR record checked out with CRLF (git autocrlf is on
  by default on Windows) failed with "the front matter is not closed", and other
  formats got mixed line endings. Records with CRLF are now edited as LF text and
  written back with CRLF.
- The Conversation board looked for codex with `which`, which Windows lacks, so
  codex was never offered there. A Windows home (drive path or share) uses
  `where`.

Tests: CRLF records for all three ADR formats (same edit as LF, CRLF kept, MADR
front matter found, supersede link), and the finder per platform. The ADR tests
fail without the fix.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): keep the Windows fixes under the size rule, skip POSIX-only specs on Windows (0.47.2)

- Move the forget-history spec out of events-ui.ts into events-forget.ts: the
  Windows branch had taken events-ui.ts to 521 lines (smoke step 11 caps files at
  500). Move the codex-finder test out of wf-control-views.spec.ts (514 lines)
  into wf-convo-finder.spec.ts.
- wf-replay-views: the Forget button asks one tick later now that it awaits the
  write flavor; the spec waits for it.
- write-argv.spec.ts: the real-disk POSIX script specs check Unix mode bits and
  FIFOs, which NTFS has not; Windows writes through the host file API. Skipped
  there. tui-ai-page.spec.ts: the --plain spec needs a runnable fake codex (a
  shebang script), which Windows cannot run; it asserts the codex line exists.
- Version 0.47.1 -> 0.47.2 in plugin.json, hooks/version.ts, scripts/smoke.sh and
  CHANGELOG.md (the entry lists every Windows fix of this branch).

Verified: the specs of the changed areas pass; the remaining failures in a full
run are menu-entry (a circular import, not Windows-specific, fails on the
baseline), the *.test.ts kit files (need claude-code/testing), and two
timing-sensitive specs that pass alone.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-cost-tracker): the ledger scripts run on Windows (0.28.3)

ledger.mjs, advise.mjs and local-cost.mjs ran only when
import.meta.url === `file://${process.argv[1]}`. On Windows that is
file:///C:/... against C:\..., never equal, so every call exited 0 with no
output and the plugin's own test-ledger.mjs failed 7 tests. They compare against
pathToFileURL(process.argv[1]).href now.

Two more breaks sat behind it for the ruflo console's mission spend:
- ledger.mjs --project required a leading "/", so a Windows project exited 2.
- inProject matched with "/" and exact case; transcripts record C:\Users\x\proj.
  A drive-lettered path now compares with either separator and any letter case;
  POSIX matching is unchanged (exact, directory boundary).

Tests: test-ledger.mjs gains Windows rows and cases (drive path in both
separator styles and letter cases, relative or climbing drive paths still exit 2,
POSIX rule stays exact). Version 0.28.2 -> 0.28.3 in plugin.json, smoke.sh and
CHANGELOG.md. smoke.sh still fails 5 steps on a Windows Git Bash for a reason
that predates this (it hands /c/... paths to a Windows node), unchanged here.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): the autopilot's text checks know Windows paths, commands and shells

Groundwork for the Windows-aware path checks that ap-windows-gate.spec.ts names as
the follow-up (an autopilot start is still refused on Windows). Each rule only
parks or refuses more; none allows anything that was refused before.

- classifyTask read only POSIX paths from a task's text, so a task naming
  C:\Windows\..., \\srv\share\..., ..\..\x, ~\x, %USERPROFILE%\x or
  $env:USERPROFILE\x was not checked against the envelope folders. It is now.
- delete-outside-worktree knew the POSIX recursive-delete forms but not the
  Windows ones: rmdir /s, del on a drive, the drive-format command,
  Remove-Item -Recurse, or a recursive rm on a drive or a variable.
- verifyProblem took the program name by splitting on "/" only, so
  C:\Windows\System32\cmd.exe, bash.exe or powershell passed the banned-program
  check. It uses either separator, drops .exe/.cmd/.bat/.ps1, and a second set
  bans the Windows shells, script hosts and destructive or system tools.

Tests (ap-windows-guard.spec.ts): path extraction and the envelope check, the deny
forms and ordinary text that must not match, verify programs allowed and refused.
Four of them fail without the change; the POSIX behaviour is asserted unchanged.
CHANGELOG: added to the unreleased 0.47.2 entry.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): the Overview heading shortens a Windows project path

"ruflo state in <last two folders>" split the cwd on "/" only, so a Windows cwd
(C:\Users\x\proj) printed whole. tailOf in paths.ts splits on either separator;
the overview uses it. Test in paths.spec.ts. CHANGELOG: added to the unreleased
0.47.2 entry.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ruflo-console): transcript search, model keys and peer sends on Windows; smoke under Git Bash

The last Windows gaps of the sweep, each tested.

- Stopping or messaging a workflow run reads the run's task id from the session
  transcript; over 2 MB that was `grep -o`, which Windows lacks. Windows now runs
  PowerShell's Select-String (windowsSearchArgv in data/wf-control.ts). The path
  and the pattern ride inside the script as base64, so a path with a space, a
  quote, $, & or ; is only data and the script holds no double quote. Tested
  against a real PowerShell on a 5 MB-class file through such a path.
- taskIdOf returned the FIRST launch when a search printed two launches of one
  run (a resume), because the pattern's `[^}]` ran across both matches (nothing
  prints a closing brace between them). It takes the last task id in the match.
  This also affected `grep -o` on Linux and macOS.
- A model key for an HTTP endpoint was read with `printenv`, which Windows lacks.
  Host gains an optional `env` (register.ts: $.env.get, already used for other
  names) and SendDeps an optional `readEnv`, set only for a Windows home; elsewhere
  `printenv` is unchanged.
- A send to a federation peer runs `bash <helper>`. On a Windows PATH `bash` is
  the WSL launcher (System32\bash.exe), which cannot open a C:\ script path, so
  the send failed obscurely. On a Windows home it now refuses, running nothing,
  and says why.
- ruflo-cost-tracker scripts/smoke.sh builds ROOT with `pwd -W` under Git Bash:
  a Windows node could not open /c/... paths, which failed 5 steps (now 66/0).

Checked and left alone: the npx launcher. The installed Claude Code (a native
binary with the host code inside it) runs $.process.run through a bundled execa
on cross-spawn, which finds `npx` as npx.cmd through PATHEXT and runs it via
cmd.exe /d /s /c with its own argument escaping, so ['npx', ...] works on
Windows. The same lookup is why `bash` there is the first bash.exe on the PATH
(the WSL launcher on this machine), which the peer refusal above relies on.

CHANGELOG: both plugins' unreleased entries (0.47.2, 0.28.3) list these.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* fix(ruflo-console): what running every view on a real Windows machine turned up

The previous commits came from pattern scans. This one comes from running the
console's own readers against a real Windows machine (every view through the
standalone terminal; the plugin catalog, ADR loader and workflow reader called
directly), plus a complete triage of the path-handling patterns in hooks/.

Found by the real run:
- The standalone terminal left state.configDir null when CLAUDE_CONFIG_DIR was
  unset (the usual case), so the installed plugins, the marketplaces and the
  workflow runs were all "unreadable". It now falls back to <home>/.claude, as
  register.ts does in the engine. Not Windows-specific.
- research.ts kept its own POSIX-only safeInstallPath, so ruflo-goals was never
  found on Windows. It uses the Windows-aware one in cost-ledger.ts (same
  character set on POSIX); on this machine goalsOf now answers ready with the
  real C:\ root.

Found by triaging every `split('/')`, `lastIndexOf('/')` and `startsWith('/')`:
- isRunPath, isRunFile and isUnder checked for ".." only between slashes, so a
  segment written with a backslash passed on Windows; a config folder ending in
  a backslash did not match. They use hasParentSegment / trimTrailing, as does
  under().
- The menu and the boot screen named the project by splitting cwd on "/", which
  printed a whole C:\ path. baseOf in paths.ts.

Test-suite and cycle fixes so the smoke's own command passes here:
- views/pane built BODIES = { menu: menuView, ... } at load time, but
  views/menu reaches pane through mission-control > mission-claude > model-tools,
  so loading menu first left menuView undefined under the test runner (native
  ESM hoists the function; the app loads pane first). It is read at call time.
- tui-actions waited a fixed 1.2 s for a 1 s retry plus a redraw, and failed
  under CPU contention in a full run (also on the baseline). It waits for the
  outcome it asserts, up to 10 s.

Verified: the smoke's exact command (every spec, 30 s timeout) is 239 files
passed, 0 failed, 3486 tests; the console smoke is 20 passed, 0 failed; all 34
views render with exit 0 and no stderr; an ADR project with a space in its path
and CRLF records loads and plans a status change keeping its CRLF.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* fix(ruflo-console): the install record of a plugin that applies to this project, compared the Windows way

installed_plugins.json holds one record per install of a plugin, and a project-scope
record names the project it was made for. The snapshot took entries[0], so a plugin
installed for several projects showed another project's version and install folder.
On a real Windows machine ruflo-console@ruflo has five records (four project, one
user) and the first is a different project's 0.44.7; everything derived from it,
the version shown and the installPath used to find a plugin's scripts, could point
at the wrong copy.

- parseInstalled(text, cwd) picks the project or local record whose projectPath is
  the session folder or holds it, else the user record, else the first.
- insideOrSame in paths.ts is that comparison, Windows-aware (case, either
  separator, a folder inside the project); hooks/updates.ts decides which installs
  to update with it too. It compared with === and startsWith(path + "/"), so on
  Windows a session in a subfolder of the project, or with a different drive-letter
  case, did not count the project's own install and left it stale.

tui-actions: "a read runs at once" waited a fixed 500 ms for a stand-in CLI process
to start; it waits for the run it asserts, and its neighbour, which failed only
because that run landed late in the shared log, no longer does.

Tests (windows-path-guards.spec.ts): the record chosen for the project under both
separators, other letter case, a subfolder, a sibling sharing the prefix, no match,
no user record, no cwd; the updater's rule; insideOrSame. Verified: the smoke's
exact command (every spec, 30 s timeout) is 239 files passed, 0 failed, 3491 tests.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* test(ruflo-console): the focus-lost spec waits for the output to go quiet before it asserts silence

"stops drawing while the terminal reports focus lost" marked the output length 60 ms
after the focus-lost report and then expected no growth. A frame already in flight
when focus was lost lands after that mark on a busy machine, which reads as the page
still drawing; the smoke's first vitest pass failed on it and only the retry passed.
It now waits until the output stops changing before it marks, still asserts 500 ms of
silence after that, and waits for the redraw on focus regained instead of a fixed
300 ms. Passes 4 of 4 isolated runs.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* test(ruflo-console): the hostile-regex spec bounds the scan's CPU time, not the wall clock

"a slow pattern over ten thousand 200-character events stops at its budget" asserted
that the scan finished in under 2500 ms of wall-clock time. The scan is CPU-bound, and
the wall clock also counts every other worker of a parallel run, so the spec passed
alone (all 12 specs of the file in 316 ms) and failed in full runs, including both
tries of the smoke's step 14 on the previous HEAD. It now bounds the scan's CPU time
(process.cpuUsage) at the same 2500 ms and keeps a 30 s wall-clock bound as a guard
against a hang. The product code is untouched.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* test(ruflo-console): the host-boundary spec does not scan the mutation specs' temporary files

tui-boundary.spec.ts reads every .ts under hooks/ when it loads. adr-mutation and
mission-advisor-mutation make temporary .mut-N-*.ts copies of hooks modules inside
hooks/ and delete them, in other workers of the same run. Two ways that disturbs this
spec: a copy that is still there is checked as if it were a hooks module (shown with a
throwaway .mut- file that imports a Node module: the spec failed before this change,
passes after), and a copy listed and then deleted can throw at load, which fails the
whole file (the smoke's step 14 showed one such file-level failure that did not repeat;
six runs of the three specs together did not reproduce it, so that part is the likely
cause, not a demonstrated one).

The walk skips .mut- names and tolerates a file that vanishes. A real violation in
hooks/ is still caught (checked with a throwaway file).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* fix(ruflo-console): the mod loads again: $.env.get takes a literal name

An earlier commit on this branch (f54772424) gave the host an `env` read that was
`async name => $.env.get(name)`. The engine lists the variables a module reads, so
`claude plugin validate` refuses a computed name:

  $.env.get takes a literal name as its first argument ...

and when it refuses register.ts the mod does not load at all: no /ruflo command, no
pane. Vitest never runs the engine's validator, so no test caught it; it showed up
when the branch was installed into a real Claude Code.

- register.ts reads only the one key it can name literally,
  $.env.get('OPENROUTER_API_KEY'); any other name answers undefined.
- wf-send says, for a custom endpoint key on Windows, that it cannot be read here and
  that only $OPENROUTER_API_KEY can, instead of claiming the variable is unset. The
  OpenRouter key keeps the "is not set" wording.
- tui-boundary.spec.ts: no $.env.get/set in hooks/ may take a non-literal name (fails on
  the old line, passes on the fix).
- smoke.sh step 21 runs `claude plugin validate` on the plugin when the CLI is present
  (passes now; reports "Validation failed" against the old line).
- CHANGELOG corrected: it described the broken behaviour.

Verified with the real validator: before, "Found 1 error"; after, "Validation passed",
and the hook list shows command.run{command=ruflo}. The 9 "gating hook without .catch"
notes it prints are identical on upstream/main.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

* test(ruflo-console): specs remove their temp folder with a retry, so a still-exiting child does not fail the file on Windows

After the merge, tui-actions.spec.ts was reported as a failed FILE with all 8 of its
tests passing:

  EBUSY: resource busy or locked, rmdir '...\tui-actions-XXXX\project'

On Windows a folder cannot be deleted while a process started in it is still running,
and these specs start the stand-in CLI and terminal sessions with the project folder as
their working directory. force: true does not cover EBUSY, and neither does maxRetries
on rmSync: measured on Node 22 with a child holding the folder for 1.2 s, rmSync fails
in 3 ms with or without maxRetries, while fs.promises.rm with maxRetries (and a manual
loop) removes it after about a second.

- tests/fixtures/rm-tree.ts: removeTree(), the async rm with up to ~5 s of retries.
- The ten specs that start processes or sessions in their temp folder (tui-actions,
  tui-ai-host, tui-ai-page, tui-host, tui-nav, tui-pagebar, tui-parity, tui-pictures,
  tui-session, wf-control-windows) use it in afterAll.
- tests/rm-tree.spec.ts: removes a tree and an already-gone one; on Windows, a real child
  holding the folder makes rmSync fail with EBUSY and removeTree wait it out.

All eleven files pass.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n

---------

Co-authored-by: RuFlo <ruv@ruv.net>
2026-10-25 13:00:56 -04:00

308 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Writing ADRs in the project's own convention (ADR-480): detect the style from the ADRs already there (or take the person's setting),
* allocate the next number, render a new record, change a record's status as the smallest edit that its format allows, and show the
* change as a diff. Pure: nothing here touches a disk. The caller (hooks/adr.ts) writes only what a person confirmed, re-reads the file
* first and refuses if it moved since the diff was shown.
*/
import { checkLimit, type Limit } from '../full-text'
import { plain } from './parse'
import { type AdrDoc, type AdrFormat, type AdrStatus } from './adr'
export type StyleName = 'madr' | 'nygard' | 'ruflo'
export const STYLES: readonly StyleName[] = ['madr', 'nygard', 'ruflo']
export type Style = {
name: StyleName
/** Digits in the number of a file name (`0005` is 4). */
width: number
/** The file name pattern: `{n}` is the number, `{slug}` the title, and the name ends in .md. */
pattern: string
source: 'setting' | 'detected' | 'default'
}
export const DEFAULT_STYLE: Style = { name: 'nygard', width: 4, pattern: '{n}-{slug}.md', source: 'default' }
const PATTERN = /^[A-Za-z0-9_.{}-]{3,80}$/
/** A pattern the person typed, or null: it must hold {n} and {slug}, end in .md and use only name characters. */
export function patternOf(text: string): string | null {
const value = text.trim()
return PATTERN.test(value) && value.includes('{n}') && value.includes('{slug}') && value.endsWith('.md') && !value.includes('..') ? value : null
}
const FORMAT_STYLE: Record<AdrFormat, StyleName> = { madr: 'madr', nygard: 'nygard', inline: 'ruflo', bare: 'nygard' }
const mode = <T>(values: readonly T[]): T | undefined => {
const counts = new Map<T, number>()
for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1)
return [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]
}
/**
* The style to write in: the person's setting first (a style name, a pattern, either or both), else what the project's ADRs do (the
* commonest format, the width of their numbers, an `ADR-` prefix), else the default (Nygard, four digits, `0001-slug.md`).
*/
export function detectStyle(docs: readonly AdrDoc[], setting: { style: StyleName | 'auto'; pattern: string } = { style: 'auto', pattern: '' }): Style {
const numbered = docs.filter(doc => doc.number !== null)
const sampled = numbered.slice(-40)
const detectedName = mode(sampled.filter(doc => doc.format !== 'bare').map(doc => FORMAT_STYLE[doc.format])) ?? (sampled.length > 0 ? 'nygard' : undefined)
const widths = sampled.map(doc => /^(?:adr[-_ ]?)?(\d+)/i.exec(doc.file)?.[1]?.length ?? 0).filter(width => width > 0)
const width = mode(widths) ?? DEFAULT_STYLE.width
const prefixed = sampled.length > 0 && sampled.filter(doc => /^adr[-_ ]/i.test(doc.file)).length * 2 > sampled.length
const detectedPattern = `${prefixed ? 'ADR-' : ''}{n}-{slug}.md`
const pattern = patternOf(setting.pattern)
const name = setting.style !== 'auto' ? setting.style : (detectedName ?? DEFAULT_STYLE.name)
const isSet = setting.style !== 'auto' || pattern !== null
return {
name,
width: Math.max(1, Math.min(8, width)),
pattern: pattern ?? (sampled.length > 0 ? detectedPattern : DEFAULT_STYLE.pattern),
source: isSet ? 'setting' : sampled.length > 0 ? 'detected' : 'default',
}
}
/** A folder name inside the project as the person typed it, or null: relative, no `..`, no backslash or control character, name characters only. '' is "find it". */
export function adrDirText(text: string): string | null {
const value = text.trim().replace(/\/+$/, '').replace(/^\.\//, '')
if (value === '') return ''
return value.length <= 120 && /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(value) && !value.split('/').some(part => part === '..' || part === '.') ? value : null
}
export const slugOf = (title: string): string =>
title
.toLowerCase()
.normalize('NFKD')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 60)
.replace(/-+$/, '') || 'untitled'
/** The longest title a person may give a new record: its heading and its file name (ADR-481: longer is refused with the count, never cut). */
export const ADR_TITLE_MAX = 120
/** The longest title a draft takes from a mission's objective; the shortening is said on the confirm card and the objective is in the record. */
export const DRAFT_TITLE_MAX = 100
/** A title as one safe line, whole: no control characters, no leading markdown marks, no link syntax. Never shortened. */
export const titleClean = (value: string): string => plain(value, Number.MAX_SAFE_INTEGER).replace(/^[#>\-*\s]+/, '').replace(/[[\]()`|]/g, '').replace(/\s+/g, ' ').trim()
/** Whether a title a person typed fits, counted as it would be written; over the limit, the message with the count. */
export const titleFit = (title: string): Limit => checkLimit(titleClean(title), ADR_TITLE_MAX, 'the title', 'it is the record’s heading and file name; put the rest in the record itself')
/**
* The title of a record ALREADY in the folder, as one safe line for a link written into another record (supersede). A backstop for text
* this console did not take from a person; a title a person types goes through `titleFit` and is never cut.
*/
export const recordTitle = (value: string): string => Array.from(titleClean(value)).slice(0, ADR_TITLE_MAX).join('')
export const padNumber = (number: number, width: number): string => String(number).padStart(width, '0')
export const fileNameFor = (style: Style, number: number, title: string): string => style.pattern.replace('{n}', padNumber(number, style.width)).replace('{slug}', slugOf(title))
/** The next free number: one above the highest in the folder (duplicates and variants included), never below 1. */
export function nextNumber(docs: readonly AdrDoc[]): number {
return docs.reduce((high, doc) => Math.max(high, doc.number ?? 0), 0) + 1
}
const WORD: Record<AdrStatus, string> = { proposed: 'Proposed', accepted: 'Accepted', superseded: 'Superseded', deprecated: 'Deprecated', rejected: 'Rejected', unknown: 'Unknown' }
export const statusWord = (status: AdrStatus): string => WORD[status]
const label = (style: Style, number: number): string => (style.pattern.startsWith('ADR-') ? `ADR-${padNumber(number, style.width)}` : `ADR ${padNumber(number, style.width)}`)
export type NewAdr = { number: number; title: string; date: string; status?: AdrStatus; scope?: string[]; context?: string; decision?: string; titleShortenedFrom?: number }
/** A new record in the style: the same headings the project's other records use. The decision is left for the person unless one is given. */
export function renderNew(style: Style, adr: NewAdr): string {
const status = statusWord(adr.status ?? 'proposed')
const title = titleClean(adr.title)
const context = adr.context ?? 'What is the issue that is motivating this decision or change?'
const decision = adr.decision ?? 'What is the change that we are proposing or have agreed to implement?'
const scope = (adr.scope ?? []).filter(entry => /^[\w@./*-]{1,160}$/.test(entry)).slice(0, 12)
if (style.name === 'madr') {
return `---\nstatus: ${status.toLowerCase()}\ndate: ${adr.date}\n---\n\n# ${title}\n\n## Context and Problem Statement\n\n${context}\n\n## Considered Options\n\n* Option 1\n* Option 2\n\n## Decision Outcome\n\n${decision}\n\n### Consequences\n\n* Good, because ...\n* Bad, because ...\n`
}
if (style.name === 'ruflo') {
return `# ${label(style, adr.number).replace(' ', '-')}: ${title}\n\n**Status**: ${status}\n**Date**: ${adr.date}\n${scope.length > 0 ? `**Scope**: ${scope.map(entry => `\`${entry}\``).join(', ')}\n` : ''}\n## Context\n\n${context}\n\n## Decision\n\n${decision}\n\n## Consequences\n\nWhat becomes easier or more difficult because of this change?\n`
}
return `# ${adr.number}. ${title}\n\nDate: ${adr.date}\n\n## Status\n\n${status}\n\n## Context\n\n${context}\n\n## Decision\n\n${decision}\n\n## Consequences\n\nWhat becomes easier or more difficult to do because of this change?\n`
}
/** The first record of a project that has none: Nygard's own, accepted. */
export function initialRecord(style: Style, date: string): { file: string; text: string; title: string } {
const title = 'Record architecture decisions'
return {
file: fileNameFor(style, 1, title),
title,
text: renderNew(style, { number: 1, title, date, status: 'accepted', context: 'We need to record the architectural decisions made on this project, so that a person joining it later can find what was decided, and why.', decision: 'We will keep Architecture Decision Records, as described by Michael Nygard: one short file for each decision, in this folder, numbered in order and never rewritten; a decision that changes is superseded by a new record.' }),
}
}
export type Edit = { ok: true; text: string } | { ok: false; why: string }
/**
* A record with CRLF line endings (git's autocrlf on Windows) is edited as LF text and written back with CRLF: the front-matter and
* line checks below compare whole lines, so a trailing carriage return made a MADR record "not closed" and left mixed endings elsewhere.
*/
function keepLineEnds(text: string, edit: (lf: string) => Edit): Edit {
if (!text.includes('\r\n')) return edit(text)
const done = edit(text.replace(/\r\n/g, '\n'))
return done.ok ? { ok: true, text: done.text.replace(/\n/g, '\r\n') } : done
}
/** The record with its status changed to `to`: one line replaced where the record has a status, one inserted where it has none. */
export const withStatus = (text: string, doc: AdrDoc, style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null = null): Edit => keepLineEnds(text, lf => statusIn(lf, doc, style, to, by))
/** The newer record names what it replaces: a `Supersedes` line after its status (or title), unless it already says so. */
export const withSupersedes = (text: string, doc: AdrDoc, style: Style, old: { number: number; title: string; file: string }): Edit => keepLineEnds(text, lf => supersedesIn(lf, doc, style, old))
const lineIndexOf = (lines: readonly string[], test: (line: string) => boolean): number => lines.findIndex(test)
const INLINE_STATUS = /^(\s*(?:[-*]\s*)?\**\s*status\s*\**\s*:\s*\**\s*)(.*?)(\**\s*)$/i
const TABLE_STATUS = /^(\s*\|\s*\**status\**\s*\|\s*)(.*?)(\s*\|?\s*)$/i
/** What the status line says after a change: `Accepted`, or `Superseded by ADR-0005` / `Superseded by [5. Title](0005-x.md)`. */
export function statusText(style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null, format: AdrFormat): string {
if (to !== 'superseded' || by === null) return statusWord(to)
if (format === 'nygard') return `Superseded by [${by.number}. ${recordTitle(by.title)}](${by.file})`
if (format === 'madr') return `superseded by ADR-${padNumber(by.number, style.width)}`
return `Superseded by ${label(style, by.number).replace(' ', '-')}`
}
/** The record with its status changed to `to`: one line replaced where the record has a status, one inserted where it has none. */
function statusIn(text: string, doc: AdrDoc, style: Style, to: AdrStatus, by: { number: number; title: string; file: string } | null): Edit {
if (to === 'unknown') return { ok: false, why: 'unknown is not a status to set' }
if (to === 'superseded' && by === null) return { ok: false, why: 'superseded needs the record that supersedes it' }
const value = statusText(style, to, by, doc.format)
const lines = text.split('\n')
if (doc.format === 'madr') {
const close = lines.findIndex((line, index) => index > 0 && line === '---')
if (!text.startsWith('---\n') || close < 0) return { ok: false, why: 'the front matter is not closed' }
const at = lineIndexOf(lines.slice(0, close), line => /^status\s*:/i.test(line))
if (at >= 0) lines[at] = `status: ${value}`
else lines.splice(close, 0, `status: ${value}`)
return { ok: true, text: lines.join('\n') }
}
if (doc.format === 'nygard') {
const head = lineIndexOf(lines, line => /^#{1,4}\s*status\s*$/i.test(line.trim()))
if (head < 0) return { ok: false, why: 'no Status section' }
const first = lines.findIndex((line, index) => index > head && line.trim() !== '' && !/^#{1,4}\s/.test(line))
if (first >= 0 && lines.slice(head + 1, first).every(line => line.trim() === '')) lines[first] = value
else lines.splice(head + 1, 0, '', value)
return { ok: true, text: lines.join('\n') }
}
if (doc.format === 'inline') {
const at = lineIndexOf(lines.slice(0, 60), line => INLINE_STATUS.test(line) || TABLE_STATUS.test(line))
if (at >= 0) {
const line = lines[at] as string
const table = TABLE_STATUS.exec(line)
lines[at] = table !== null ? `${table[1]}${value}${table[3]}` : line.replace(INLINE_STATUS, (_all, lead: string, _old: string, tail: string) => `${lead}${value}${tail}`)
return { ok: true, text: lines.join('\n') }
}
}
// No status yet: after the title (and after the date line, if one sits right there) a `Status:` line the project's parser will read.
const title = lineIndexOf(lines, line => /^#\s/.test(line))
const at = title < 0 ? 0 : title + 1
lines.splice(at, 0, '', `Status: ${value}`)
return { ok: true, text: lines.join('\n') }
}
/** The newer record names what it replaces: a `Supersedes` line after its status (or title), unless it already says so. */
function supersedesIn(text: string, doc: AdrDoc, style: Style, old: { number: number; title: string; file: string }): Edit {
if (doc.supersedes.includes(old.number)) return { ok: true, text }
const lines = text.split('\n')
const link = doc.format === 'nygard' ? `Supersedes [${old.number}. ${recordTitle(old.title)}](${old.file})` : `${doc.format === 'inline' ? '**Supersedes**' : 'Supersedes'}: ${label(style, old.number).replace(' ', '-')}`
if (doc.format === 'madr') {
const close = lines.findIndex((line, index) => index > 0 && line === '---')
if (!text.startsWith('---\n') || close < 0) return { ok: false, why: 'the front matter is not closed' }
lines.splice(close, 0, `supersedes: ${label(style, old.number).replace(' ', '-')}`)
return { ok: true, text: lines.join('\n') }
}
const status = lineIndexOf(lines.slice(0, 80), line => (doc.format === 'nygard' ? /^#{1,4}\s*status\s*$/i.test(line.trim()) : INLINE_STATUS.test(line) || TABLE_STATUS.test(line)))
const at = status >= 0 ? (doc.format === 'nygard' ? lines.findIndex((line, index) => index > status && line.trim() !== '' && !/^#/.test(line)) + 1 : status + 1) : lineIndexOf(lines, line => /^#\s/.test(line)) + 1
lines.splice(Math.max(at, 1), 0, ...(doc.format === 'nygard' ? ['', link] : [link]))
return { ok: true, text: lines.join('\n') }
}
/**
* The change from `before` to `after` as one hunk of unified-diff lines with a line of context each side. The two texts differ in a
* run of adjacent lines (every edit above is one), so the common start and end are the context. Capped.
*/
export function lineDiff(before: string, after: string, file = 'file'): string[] {
if (before === after) return [`${file}: no change`]
const a = before.split('\n')
const b = after.split('\n')
let head = 0
while (head < a.length && head < b.length && a[head] === b[head]) head += 1
let tail = 0
while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1
const from = Math.max(0, head - 1)
const endA = Math.min(a.length, a.length - tail + 1)
const out = [`--- ${file}`, `+++ ${file}`, `@@ line ${from + 1} @@`]
for (let i = from; i < head; i += 1) out.push(` ${a[i]}`)
for (let i = head; i < a.length - tail; i += 1) out.push(`-${a[i]}`)
for (let i = head; i < b.length - tail; i += 1) out.push(`+${b[i]}`)
for (let i = a.length - tail; i < endA; i += 1) out.push(` ${a[i]}`)
return out.slice(0, 40)
}
/** A draft record for a finished mission: only what the mission itself said (its goal, its tasks and their results); the decision is left to the person. */
export function draftFromMission(mission: { objective: string; tasks: readonly { title: string; result?: string }[] }, scope: readonly string[], date: string): NewAdr {
// Counted and cut in code points, as titleFit counts: a cut never leaves half of a surrogate pair.
const whole = titleClean(mission.objective)
const points = Array.from(whole)
const title = points.length > DRAFT_TITLE_MAX ? points.slice(0, DRAFT_TITLE_MAX).join('').trim() : whole
const done = mission.tasks.slice(0, 12).map(task => `- ${titleClean(task.title)}${task.result === undefined || task.result === '' ? '' : `: ${plain(task.result, 140)}`}`)
return {
number: 0,
date,
title,
...(title !== whole && { titleShortenedFrom: points.length }),
status: 'proposed',
scope: [...scope],
context: `A mission set out to: ${plain(mission.objective, 2_000)}`,
decision: `Draft, written from the mission's record and to be rewritten by a person: the mission did the following.\n\n${done.join('\n')}\n\nWhat was decided, and why, is not in the record: say it here.`,
}
}