rvlib-shipkit 2.24.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/live.ts +153 -0
  4. package/src/annex/offload.ts +16 -7
  5. package/src/check.ts +3 -1
  6. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  7. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  8. package/src/checks/SK033-global-contribution.check.ts +1 -1
  9. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  10. package/src/checks/SK040-release-words.check.ts +1 -1
  11. package/src/checks/SK042-post-kinds.check.ts +1 -1
  12. package/src/cli/cmd_Annex.ts +12 -7
  13. package/src/cli/cmd_Assets.ts +5 -5
  14. package/src/cli/cmd_Backup.ts +11 -5
  15. package/src/cli/cmd_Capacity.ts +10 -6
  16. package/src/cli/cmd_Checks.ts +12 -1
  17. package/src/cli/cmd_Ci.ts +2 -2
  18. package/src/cli/cmd_Commands.ts +11 -2
  19. package/src/cli/cmd_ConfigKeys.ts +17 -0
  20. package/src/cli/cmd_Home.ts +1 -1
  21. package/src/cli/cmd_Keys.ts +4 -1
  22. package/src/cli/cmd_Lanes.ts +35 -0
  23. package/src/cli/cmd_Mv.ts +6 -7
  24. package/src/cli/cmd_Rec.ts +22 -7
  25. package/src/cli/cmd_Review.ts +107 -39
  26. package/src/cli/cmd_Shot.ts +15 -4
  27. package/src/cli/cmd_Status.ts +6 -5
  28. package/src/cli/cmd_Time.ts +10 -4
  29. package/src/cli/cmd_Veille.ts +10 -6
  30. package/src/cli/family-help.ts +136 -0
  31. package/src/cli/family-pages.ts +0 -19
  32. package/src/cli/kit/calls.ts +35 -0
  33. package/src/cli/kit/project-cli.ts +2 -12
  34. package/src/cli/registry.ts +39 -6
  35. package/src/cli.ts +8 -4
  36. package/src/core/capacity.ts +89 -33
  37. package/src/core/check-runner.ts +5 -1
  38. package/src/core/floor-resolve.ts +6 -2
  39. package/src/core/floor.ts +6 -2
  40. package/src/core/history-files.ts +18 -0
  41. package/src/core/jobs.ts +35 -16
  42. package/src/core/layout.ts +2 -2
  43. package/src/core/nearest.ts +16 -0
  44. package/src/core/remove-tree.ts +19 -0
  45. package/src/core/runs.ts +12 -3
  46. package/src/core/throwaway-worktree.ts +22 -4
  47. package/src/core/trace-audit.ts +17 -4
  48. package/src/home/daemon-jobs.ts +41 -4
  49. package/src/home/machine-temp.ts +2 -10
  50. package/src/ledger/gate-checks.ts +3 -2
  51. package/src/ledger/git-key.ts +25 -4
  52. package/src/ledger/git-scan.ts +10 -0
  53. package/src/media-store/backup/daemon.ts +92 -20
  54. package/src/media-store/backup/run.ts +21 -15
  55. package/src/media-store/backup/sources.ts +166 -21
  56. package/src/media-store/backup/watch.ts +106 -0
  57. package/src/media-store/daemon.ts +36 -8
  58. package/src/media-store/hand.ts +3 -1
  59. package/src/mv/mv-md.ts +50 -18
  60. package/src/pb/run-pb.ts +2 -10
  61. package/src/plan/repo-source.ts +25 -14
  62. package/src/recordings/model.ts +1 -1
  63. package/src/release/run-bump.ts +3 -2
  64. package/src/release/run-release.ts +12 -4
  65. package/src/review/cells.ts +2 -1
  66. package/src/review/format.ts +1 -1
  67. package/src/review/model.ts +14 -1
  68. package/src/review/store.ts +15 -7
  69. package/src/review/trailer-model.ts +2 -2
  70. package/src/shot/client.ts +4 -2
  71. package/src/shot/serve-shot.ts +71 -2
  72. package/src/shot/shooter.ts +65 -11
  73. package/src/shot/shot-ask.ts +32 -9
  74. package/src/suite/select.ts +13 -2
  75. package/src/suite/test-units.ts +31 -12
  76. package/src/trailer/graph.ts +2 -1
  77. package/src/ts/config.ts +12 -35
  78. package/src/ts/rename.ts +31 -17
  79. package/src/ts/workspaces.ts +45 -0
  80. package/src/wiki/run-wiki.ts +7 -2
  81. package/src/wiki/scan-md.ts +2 -1
@@ -15,10 +15,10 @@ interface Here {
15
15
  }
16
16
 
17
17
  /** the identity named, else the one the current repo's Veille is */
18
- async function run(context: Ctx, as: string | undefined, body: (h: Here) => Promise<number>): Promise<number> {
18
+ async function run(context: Ctx, as: string | undefined, cmd: string, body: (h: Here) => Promise<number>): Promise<number> {
19
19
  const out = (l: string): void => void context.stdout.write(`${l}\n`)
20
20
  try {
21
- const { identityOf, hasVeille } = await import('../veille/identity.ts')
21
+ const { identities, identityOf, hasVeille } = await import('../veille/identity.ts')
22
22
  const { veilleAt } = await import('../veille/routes.ts')
23
23
  const { storeDir } = await import('../review/store.ts')
24
24
  const { findRepoRoot } = await import('../ts/config.ts')
@@ -30,7 +30,11 @@ async function run(context: Ctx, as: string | undefined, body: (h: Here) => Prom
30
30
  }
31
31
  const here = root == null ? null : veilleAt(root)
32
32
  const identity = as === undefined ? here?.identity : identityOf(as)
33
- if (identity == null) throw new Error(as === undefined ? 'this repo shows no Veille: name the identity with --as <id>' : `no identity ${as}`)
33
+ if (identity == null) {
34
+ const watched = identities().filter(hasVeille).map((x) => x.id)
35
+ const pick = watched.length === 0 ? 'no identity has a watch list yet' : `name one: ${watched.map((id) => `${cmd} --as ${id}`).join(', ')}`
36
+ throw new Error(`${as === undefined ? 'this repo shows no Veille' : `no identity ${as}`}: ${pick}`)
37
+ }
34
38
  if (!hasVeille(identity)) throw new Error(`${identity.id} has no watch list (${identity.watchFile})`)
35
39
  const asksDir = here != null && here.identity.id === identity.id ? storeDir(here.asks.root) : null
36
40
  return await body({ out, identity, root, asksDir })
@@ -60,7 +64,7 @@ export class VeilleFeedCommand extends Command {
60
64
  since = Option.String('--since', '24h', { description: 'the window: 90m, 24h, 3d, 7d' })
61
65
  all = Option.Boolean('--all', false, { description: 'the expired and handled posts too' })
62
66
  async execute(): Promise<number> {
63
- return run(this.context, this.as, async (h) => {
67
+ return run(this.context, this.as, `sk ${this.path.join(' ')}`, async (h) => {
64
68
  const { feedLine } = await import('../veille/desk.ts')
65
69
  const { isPlatform } = await import('../veille/platforms.ts')
66
70
  const { interactions } = await import('../veille/asks.ts')
@@ -97,7 +101,7 @@ export class VeilleReplyCommand extends Command {
97
101
  text = Option.String('--text', { description: 'the reply' })
98
102
  media = Option.String('--media', { description: 'a media file of the drafts it lends, repo relative' })
99
103
  async execute(): Promise<number> {
100
- return run(this.context, this.as, async (h) => {
104
+ return run(this.context, this.as, `sk ${this.path.join(' ')}`, async (h) => {
101
105
  const { brief, mediaFor } = await import('../veille/desk.ts')
102
106
  const { draftMedia } = await import('../social/media-of.ts')
103
107
  const { oursOf, veilleOf } = await import('../veille/service.ts')
@@ -127,7 +131,7 @@ export class VeillePassCommand extends Command {
127
131
  as = asOpt()
128
132
  why = Option.String('--why', { required: true, description: 'the real reason, one line' })
129
133
  async execute(): Promise<number> {
130
- return run(this.context, this.as, async (h) => {
134
+ return run(this.context, this.as, `sk ${this.path.join(' ')}`, async (h) => {
131
135
  const { oursOf, veilleOf } = await import('../veille/service.ts')
132
136
  const { desk } = veilleOf(h.identity)
133
137
  if (desk.feed({ all: true, ours: oursOf(h.identity) }).every((r) => r.key !== this.key)) throw new Error(`no post ${this.key} in the log: sk veille feed gives the keys`)
@@ -0,0 +1,136 @@
1
+ // what the cli answers itself where the parser's own text costs a screen: the list of
2
+ // `<bin> <family> --help`, a family name typed as a command, and words no command has.
3
+ // the one constraint a reader breaks first: each answer is a few lines, never the whole registry
4
+ import { nearest } from '../core/nearest.ts'
5
+ import { type CommandRow, compactLine } from './cmd_Commands.ts'
6
+ import { FAMILY_PAGES, pageAt } from './family-pages.ts'
7
+
8
+ export type Said = { lines: string[]; code: number }
9
+ /** a command the parser held the line against, and why it did not fit when it says */
10
+ export type Candidate = { usage: string; reason: string | null }
11
+ /** the command words of a usage line: what stands between the binary and the first flag or argument */
12
+ const commandOf = (usage: string): string => {
13
+ const w = usage.split(' ').slice(1)
14
+ const n = w.findIndex((x) => !/^[a-z][\w-]*$/.test(x))
15
+ return (n < 0 ? w : w.slice(0, n)).join(' ')
16
+ }
17
+
18
+ const firstWord = (path: string): string => path.split(' ')[0]!
19
+
20
+ /** edits between two words, two swapped neighbours counting as one (`dnoe` for `done`) */
21
+ function editDistance(a: string, b: string): number {
22
+ let before: number[] = []
23
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
24
+ for (let i = 1; i <= a.length; i++) {
25
+ const next = [i]
26
+ for (let j = 1; j <= b.length; j++) {
27
+ next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
28
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) next[j] = Math.min(next[j]!, before[j - 2]! + 1)
29
+ }
30
+ before = row
31
+ row = next
32
+ }
33
+ return row[b.length]!
34
+ }
35
+
36
+ /** the names one slip of the keyboard away from `want`: one edit, two for a word of five letters or more */
37
+ export function typoOf(want: string, have: readonly string[], max = 3): string[] {
38
+ const w = want.toLowerCase()
39
+ const reach = w.length >= 5 ? 2 : 1
40
+ return have
41
+ .map((n) => [n, editDistance(w, n.toLowerCase())] as const)
42
+ .filter(([, d]) => d <= reach)
43
+ .sort((a, b) => a[1] - b[1])
44
+ .slice(0, max)
45
+ .map(([n]) => n)
46
+ }
47
+
48
+ const count = (n: number): string => `${n} command${n === 1 ? '' : 's'}`
49
+ const flagsLine = (bin: string): string => `flags and examples of one: ${bin} <command> --help`
50
+
51
+ /** the list `<bin> <words> --help` prints when several commands start with those words: one line each, then
52
+ * the family's page. `self` is where the command that IS those words sits in the parser's list, when one does */
53
+ export function familyList(rows: readonly CommandRow[], bin: string, pages: Readonly<Record<string, string>> | null = FAMILY_PAGES): Said {
54
+ const words = rows.map((r) => r.path.split(' '))
55
+ let n = 0
56
+ while (words.every((w) => w[n] != null && w[n] === words[0]![n])) n++
57
+ const prefix = words[0]!.slice(0, n).join(' ')
58
+ const self = rows.findIndex((r) => r.path === prefix)
59
+ const families = new Set(rows.map((r) => r.category))
60
+ const page = families.size === 1 ? pages?.[[...families][0]!] : undefined
61
+ return {
62
+ code: 0,
63
+ lines: [
64
+ // no word in common (`asks` and `ask`): the first words stand in for it
65
+ `${bin} ${prefix === '' ? [...new Set(rows.map((r) => firstWord(r.path)))].join(', ') : prefix}: ${count(rows.length)}`,
66
+ ...rows.map((r) => compactLine(r, bin)),
67
+ `${flagsLine(bin)}${self < 0 ? '' : `; the help of ${bin} ${prefix} alone: ${bin} ${prefix} -h=${self}`}`,
68
+ ...(page == null ? [] : [`Read first: ${pageAt(page)}`]),
69
+ ],
70
+ }
71
+ }
72
+
73
+ /** words no command has. A family's name lists the family (exit 0 when help was asked). Anything else names
74
+ * the closest commands, or the one command that lists them all. Null: no word was typed */
75
+ export function unknownCommand(input: readonly string[], rows: readonly CommandRow[], bin: string, pages: Readonly<Record<string, string>> | null = FAMILY_PAGES, candidates: readonly Candidate[] = []): Said | null {
76
+ const flag = input.findIndex((a) => a.startsWith('-'))
77
+ const words = flag < 0 ? [...input] : input.slice(0, flag)
78
+ if (words.length === 0) return null
79
+ const typed = `${bin} ${words.join(' ')}`
80
+ // the parser found the command and the line does not fit it: its usage, never « no command »
81
+ // one command, and the typed words begin with its words: a few candidates alone prove nothing, since a word
82
+ // only a few commands start with (`wiki`, `hooks`) gives a short list too
83
+ const fits = [...new Set(candidates.map((c) => c.usage.replace(/ #\d+\b/g, ' <value>')))]
84
+ const held = [...new Set(candidates.map((c) => commandOf(c.usage)))]
85
+ if (held.length === 1 && held[0] !== '' && `${words.join(' ')} `.startsWith(`${held[0]} `)) {
86
+ const reason = candidates.find((c) => c.reason != null)?.reason?.replace(/\.$/, '') ?? 'a required flag or argument is missing'
87
+ return { code: 1, lines: [`FAIL: ${bin} ${input.join(' ')}: ${reason}`, ...fits.map((u) => ` usage: ${u}`), ` fix: ${bin} ${held[0]} --help`] }
88
+ }
89
+ const family = words.length === 1 ? [...new Set(rows.map((r) => r.category))].find((c) => c.toLowerCase() === words[0]!.toLowerCase()) : undefined
90
+ if (family != null) {
91
+ const mine = rows.filter((r) => r.category === family)
92
+ const help = input.includes('--help') || input.includes('-h')
93
+ const page = pages?.[family]
94
+ return {
95
+ code: help ? 0 : 1,
96
+ lines: [
97
+ help ? `${family}: a family of ${count(mine.length)}` : `FAIL: ${typed} is no command: ${family} is a family of ${count(mine.length)}`,
98
+ ...mine.map((r) => compactLine(r, bin)),
99
+ flagsLine(bin),
100
+ ...(page == null ? [] : [`Read first: ${pageAt(page)}`]),
101
+ ],
102
+ }
103
+ }
104
+ const paths = rows.map((r) => r.path)
105
+ const firsts = [...new Set(paths.map(firstWord))]
106
+ const rest = words.slice(1)
107
+ const close: string[] = []
108
+ const add = (s: string): void => { if (!close.includes(s)) close.push(s) }
109
+ if (words.length === 1 && firsts.includes(words[0]!)) {
110
+ // a word several commands start with and no command is: its list, as a refusal
111
+ const list = familyList(rows.filter((r) => firstWord(r.path) === words[0]), bin, pages)
112
+ return { code: 1, lines: [`FAIL: ${typed} is no command: ${list.lines[0]}`, ...list.lines.slice(1)] }
113
+ }
114
+ if (firsts.includes(words[0]!)) {
115
+ // the first word is a real one: the slip is in the words after it
116
+ // each command of that word against as many typed words as it has, so what follows the slip is kept
117
+ const near = paths
118
+ .filter((p) => firstWord(p) === words[0] && p.includes(' '))
119
+ .map((p) => ({ p, n: p.split(' ').length }))
120
+ .filter(({ p, n }) => typoOf(words.slice(0, n).join(' '), [p]).length > 0)
121
+ for (const { p, n } of near.slice(0, 2)) add([bin, p, ...words.slice(n)].join(' '))
122
+ add(`${bin} ${words[0]} --help`)
123
+ } else {
124
+ for (const f of [...typoOf(words[0]!, firsts), ...nearest(words[0]!, firsts, 3)]) {
125
+ const whole = [f, ...rest].join(' ')
126
+ add(paths.includes(whole) ? `${bin} ${whole}` : rest.length === 0 && paths.includes(f) && !paths.some((p) => p.startsWith(`${f} `)) ? `${bin} ${f}` : `${bin} ${f} --help`)
127
+ }
128
+ }
129
+ return {
130
+ code: 1,
131
+ lines: [
132
+ `FAIL: no command « ${typed} »`,
133
+ close.length > 0 ? ` fix: did you mean ${close.slice(0, 3).join(', ')} ?` : ` fix: ${bin} commands --compact lists every command, one line each`,
134
+ ],
135
+ }
136
+ }
@@ -36,22 +36,3 @@ export function pageAt(rel: string): string {
36
36
  const home = homedir()
37
37
  return abs.startsWith(`${home}/`) ? `~${abs.slice(home.length)}` : abs
38
38
  }
39
-
40
- type Listed = { contexts?: { commandClass: { usage?: { category?: string | null } } }[]; commands?: number[]; execute(): Promise<number | void>; context: { stdout: { write(s: string): unknown } } }
41
-
42
- /** `sk <family> --help` lists the family's commands (clipanion's help for several matches): the family's page
43
- * follows the list. Any other command passes through */
44
- export function withFamilyPage<C extends object>(command: C, pages: Readonly<Record<string, string>> = FAMILY_PAGES): C {
45
- const h = command as C & Listed
46
- if (!Array.isArray(h.contexts) || !Array.isArray(h.commands) || h.commands.length < 2) return command
47
- const families = new Set(h.commands.map((i) => h.contexts?.[i]?.commandClass.usage?.category ?? ''))
48
- const page = families.size === 1 ? pages[[...families][0]!] : undefined
49
- if (page == null) return command
50
- const list = h.execute.bind(h)
51
- h.execute = async () => {
52
- const code = await list()
53
- h.context.stdout.write(`Read first: ${pageAt(page)}\n`)
54
- return code
55
- }
56
- return command
57
- }
@@ -36,6 +36,41 @@ export type CallEnd = {
36
36
  /** where a CLI's calls go: `<root>/.shipkit/logs/<bin>-calls.jsonl` */
37
37
  export const callsFile = (root: string, bin: string): string => join(root, LAYOUT.logs, `${bin}-calls.jsonl`)
38
38
 
39
+ /** the path of the command `parse` resolves (a clipanion `cli.process`), what
40
+ * `matched` logs: `help` for a help request, null when no command matches */
41
+ export function commandPath(parse: () => object): string | null {
42
+ try {
43
+ const c = parse().constructor as { name: string; paths?: string[][] }
44
+ // a command's own help is clipanion's HelpCommand, which carries no path
45
+ const path = c.name === 'HelpCommand' ? 'help' : (c.paths?.[0]?.join(' ') ?? null)
46
+ return path?.startsWith('-') === true ? 'help' : path
47
+ } catch {
48
+ return null
49
+ }
50
+ }
51
+
52
+ /** the argv to run when `--help` comes after a command's own args (`review seen <id> --help`): clipanion reads help
53
+ * only right after a command's path, so the line is cut back to the longest prefix that parses as help. Any other
54
+ * argv, and one no prefix of which is help, runs as typed */
55
+ export function helpArgv(argv: readonly string[], parse: (argv: string[]) => object): string[] {
56
+ const isHelp = (a: string): boolean => a === '--help' || a === '-h'
57
+ // a command's help parses to clipanion's HelpCommand, which carries no path
58
+ const parsed = (a: string[]): string | null => {
59
+ try {
60
+ return parse(a).constructor.name
61
+ } catch {
62
+ return null
63
+ }
64
+ }
65
+ if (!argv.some(isHelp) || parsed([...argv]) !== null) return [...argv]
66
+ const words = argv.filter((a) => !isHelp(a))
67
+ for (let n = words.length; n >= 1; n--) {
68
+ const cut = [...words.slice(0, n), '--help']
69
+ if (parsed(cut) === 'HelpCommand') return cut
70
+ }
71
+ return [...argv]
72
+ }
73
+
39
74
  /** the env prefix of a CLI: `my-tool` → `MY_TOOL` */
40
75
  export const envPrefix = (bin: string): string => bin.toUpperCase().replace(/[^A-Z0-9]/g, '_')
41
76
 
@@ -4,7 +4,7 @@
4
4
  // pages, generated) and `calls` (the log, read back). The bar: the bare
5
5
  // listing answers in well under a second.
6
6
  import { type BaseContext, Builtins, Cli } from 'clipanion'
7
- import { callsFile, logCall } from './calls.ts'
7
+ import { callsFile, commandPath, logCall } from './calls.ts'
8
8
  import { type Family, familiesFor, listing, listingOf, rootClashes } from './families.ts'
9
9
  import type { AskTool, CommandClass, KitContext } from './verb.ts'
10
10
 
@@ -47,16 +47,6 @@ export async function projectCli(spec: ProjectCliSpec, argv: readonly string[],
47
47
  return { cli, context: { root: spec.root, cwd, classes, askTool: spec.askTool } }
48
48
  }
49
49
 
50
- /** the path of the command a call runs, null when none matches */
51
- function commandOf(cli: Cli<KitContext>, argv: string[], context: KitExtra): string | null {
52
- try {
53
- const path = (cli.process(argv, context).constructor as { paths?: string[][] }).paths?.[0]?.join(' ') ?? null
54
- return path?.startsWith('-') === true ? 'help' : path
55
- } catch {
56
- return null
57
- }
58
- }
59
-
60
50
  const closedPipe = (e: unknown): boolean => e instanceof Error && 'code' in e && e.code === 'EPIPE'
61
51
 
62
52
  /** the whole entry of a project CLI: log, load, then list or run */
@@ -66,7 +56,7 @@ export async function runProjectCli(spec: ProjectCliSpec, argv: string[] = proce
66
56
  const call = logCall(callsFile(spec.root, spec.name), spec.name, argv)
67
57
  const t0 = performance.now()
68
58
  const { cli, context } = await projectCli(spec, argv)
69
- call.matched(commandOf(cli, argv, context), performance.now() - t0)
59
+ call.matched(commandPath(() => cli.process(argv, context)), performance.now() - t0)
70
60
  const word = listingOf(spec.name, argv, cli.definitions())
71
61
  if (word !== null) { process.stdout.write(listing(spec.name, cli.definitions(), word, spec.label)); return }
72
62
  await cli.runExit(argv, context)
@@ -3,7 +3,7 @@
3
3
  // (../cli.ts) loads it with an await import, so a file that fails to load is
4
4
  // caught there. A new command registers here.
5
5
  import { LIB_VERSION } from '../core/lib-version.ts'
6
- import { Builtins, Cli, type Command } from 'clipanion'
6
+ import { Builtins, Cli, Command } from 'clipanion'
7
7
  import { AskNewCommand, AsksCheckCommand, AsksCommand } from './cmd_Asks.ts'
8
8
  import { AssetsAddCommand, AssetsCheckCommand, AssetsFillCommand, AssetsGenCommand, AssetsIdentityCommand } from './cmd_Assets.ts'
9
9
  import { BumpCommand } from './cmd_Bump.ts'
@@ -12,8 +12,9 @@ import { TimeCommand } from './cmd_Time.ts'
12
12
  import { DrillCalibrateCommand, DrillCleanCommand, DrillCloneCommand, DrillCompareCommand, DrillFinishCommand, DrillReportCommand, DrillVerdictCommand } from './cmd_Drill.ts'
13
13
  import { CheckCommand } from './cmd_Check.ts'
14
14
  import { CapacityCommand } from './cmd_Capacity.ts'
15
- import { CommandsCommand } from './cmd_Commands.ts'
16
- import { withFamilyPage } from './family-pages.ts'
15
+ import { LanesCommand } from './cmd_Lanes.ts'
16
+ import { type CommandRow, commandRows, CommandsCommand, type Definition } from './cmd_Commands.ts'
17
+ import { type Candidate, familyList, type Said, unknownCommand } from './family-help.ts'
17
18
  import { CrossRepoActivityCommand } from './cmd_CrossRepoActivity.ts'
18
19
  import { ConfigKeysCommand } from './cmd_ConfigKeys.ts'
19
20
  import { GlobalProcessesCommand, GlobalProcessOpenCommand, GlobalProcessRestartCommand, GlobalProcessStartCommand, GlobalProcessStopCommand } from './cmd_GlobalProcesses.ts'
@@ -61,7 +62,20 @@ import { SecretListCommand, SecretReadCommand, SecretSetCommand, SecretCopyComma
61
62
  import { WikiLintCommand, WikiServeCommand } from './cmd_Wiki.ts'
62
63
 
63
64
 
64
- /** `sk <family> --help` names the family's page under its list */
65
+ /** an answer the cli gives itself: a few lines and an exit code */
66
+ class SaidCommand extends Command {
67
+ said: Said = { lines: [], code: 0 }
68
+ async execute(): Promise<number> {
69
+ this.context.stdout.write(`${this.said.lines.join('\n')}\n`)
70
+ return this.said.code
71
+ }
72
+ }
73
+ const say = (said: Said): Command => Object.assign(new SaidCommand(), { said })
74
+
75
+ type Listed = { contexts?: { commandClass: { paths?: string[][] } }[]; commands?: number[]; index?: number }
76
+
77
+ /** the parser's two screens become a few lines (cli/family-help.ts): the list of `sk <family> --help`, and
78
+ * words no command has */
65
79
  class FamilyHelpCli extends Cli {
66
80
  /** every class registered, so `sk commands` reads each command's marks (essential, film) */
67
81
  readonly classes: Parameters<Cli['register']>[0][] = []
@@ -69,8 +83,25 @@ class FamilyHelpCli extends Cli {
69
83
  this.classes.push(c)
70
84
  super.register(c)
71
85
  }
86
+ private rows(): CommandRow[] {
87
+ return commandRows(this.definitions() as Definition[], [], this.binaryName, this.classes)
88
+ }
72
89
  override process(...args: unknown[]): Command {
73
- return withFamilyPage((super.process as (...a: unknown[]) => Command).apply(this, args))
90
+ let command: Command
91
+ try {
92
+ command = (super.process as (...a: unknown[]) => Command).apply(this, args)
93
+ } catch (e) {
94
+ const input = Array.isArray(args[0]) ? (args[0] as string[]) : (args[0] as { input?: string[] } | undefined)?.input
95
+ const said = input != null && e instanceof Error && e.message.startsWith('Command not found') ? unknownCommand(input, this.rows(), this.binaryName, undefined, (e as { candidates?: Candidate[] }).candidates ?? []) : null
96
+ if (said == null) throw e
97
+ return say(said)
98
+ }
99
+ const h = command as Command & Listed
100
+ // the parser's help for several matches, with no index asked: its list
101
+ if (!Array.isArray(h.contexts) || !Array.isArray(h.commands) || h.commands.length < 2 || (h.index != null && h.index >= 0 && h.index < h.commands.length)) return command
102
+ const byPath = new Map(this.rows().map((r) => [r.path, r]))
103
+ const listed = h.commands.map((i) => byPath.get(h.contexts?.[i]?.commandClass.paths?.[0]?.join(' ') ?? ''))
104
+ return listed.every((r) => r != null) ? say(familyList(listed as CommandRow[], this.binaryName)) : command
74
105
  }
75
106
  }
76
107
 
@@ -83,7 +114,8 @@ export function buildCli(): Cli {
83
114
  binaryName: 'sk',
84
115
  binaryVersion: LIB_VERSION,
85
116
  enableCapture: true, // console output pipes into the command streams (testable)
86
- enableColors: true,
117
+ // off a terminal (every agent harness) colour codes are bytes nobody reads
118
+ enableColors: process.stdout.isTTY === true && (process.env.NO_COLOR ?? '') === '',
87
119
  })
88
120
 
89
121
  cli.register(Builtins.HelpCommand)
@@ -165,6 +197,7 @@ export function buildCli(): Cli {
165
197
  cli.register(UnitsAliasCommand)
166
198
  cli.register(CommandsCommand)
167
199
  cli.register(CapacityCommand)
200
+ cli.register(LanesCommand)
168
201
  cli.register(CallsCommand)
169
202
  cli.register(TimeCommand)
170
203
  cli.register(DrillReportCommand)
package/src/cli.ts CHANGED
@@ -42,6 +42,7 @@ export const loadBoot = (cmd?: string) =>
42
42
  // started when it is down (autostart.ts), before the command runs
43
43
  if (import.meta.main) {
44
44
  const raw = process.argv.slice(2)
45
+ const t0 = performance.now()
45
46
  let m
46
47
  try {
47
48
  m = await loadBoot(raw[0])
@@ -50,12 +51,15 @@ if (import.meta.main) {
50
51
  throw e
51
52
  }
52
53
  bootLoaded()
53
- const [{ buildCli }, { aliasArgs }, { handoff }, { installOneLib }, { callsFile, logCall }, { autostart }, { linkMachineCopy }] = m
54
+ const [{ buildCli }, { aliasArgs }, { handoff }, { installOneLib }, { callsFile, commandPath, helpArgv, logCall }, { autostart }, { linkMachineCopy }] = m
54
55
  const argv = aliasArgs(raw)
55
56
  handoff(argv)
56
57
  installOneLib()
57
58
  await linkMachineCopy()
58
- logCall(callsFile((await import('os')).homedir(), 'sk'), 'sk', argv)
59
- await autostart(argv)
60
- void buildCli().runExit(argv)
59
+ const call = logCall(callsFile((await import('os')).homedir(), 'sk'), 'sk', argv)
60
+ const cli = buildCli()
61
+ const run = helpArgv(argv, (a) => cli.process(a))
62
+ call.matched(commandPath(() => cli.process(run)), performance.now() - t0)
63
+ await autostart(run)
64
+ void cli.runExit(run)
61
65
  }
@@ -1,17 +1,26 @@
1
- // HOW MANY MORE LANES THE MACHINE CAN TAKE NOW, read from the machine: its
2
- // cores, its load, and the agents writing right now (every account, every
3
- // repo). No fixed cap: the answer moves with what the machine runs.
1
+ // HOW MANY LANES A REPO RUNS NOW, read from the machine: its cores, its
2
+ // 1 minute load and the agents writing right now (every account, every repo).
3
+ // No fixed cap: each repo adjusts its own count, and the answer moves with
4
+ // what the machine runs.
4
5
  //
5
- // The one constraint a reader breaks first: an agent counts for at least one
6
- // core. Most of a lane's time is its model's turns, which load nothing here,
7
- // so a quiet moment reads far under what its next test run will cost.
6
+ // The one constraint a reader breaks first: the answer is never zero. One
7
+ // lane always runs, a maximum the owner gave replaces the number, and only a
8
+ // dying machine (a load of twice its cores) holds a lane back. A tool that
9
+ // said WAIT at a load of 9 on 8 cores stopped five lanes the owner had
10
+ // allowed, for 25 minutes.
8
11
  import { availableParallelism, loadavg } from 'os'
12
+ import { dirname } from 'path'
13
+ import { liveRow, oneRowAnAgent } from '../agent-time/live.ts'
9
14
  import { listTranscripts, type TranscriptFile } from '../agent-time/store.ts'
15
+ import { gitBin } from './git-bin.ts'
16
+ import { gitRoot } from './git-root.ts'
10
17
 
11
18
  /** an agent is live when its transcript was written this recently */
12
19
  export const LIVE_WINDOW_MS = 3 * 60 * 1000
20
+ /** the machine is dying at this many times its cores of load: no lane starts, a maximum included */
21
+ export const DYING_LOAD = 2
13
22
 
14
- export type LiveAgents = { sessions: number; lanes: number; byProject: [project: string, agents: number][] }
23
+ export type LiveAgents = { sessions: number; lanes: number; byProject: [project: string, agents: number][]; /** agents live in the window whose turn ended: they hold no core */ idle?: number }
15
24
 
16
25
  /** the sessions and sub-agents whose transcript moved inside the window */
17
26
  export function liveAgents(files: readonly TranscriptFile[], now: number, windowMs = LIVE_WINDOW_MS): LiveAgents {
@@ -25,47 +34,94 @@ export function liveAgents(files: readonly TranscriptFile[], now: number, window
25
34
  }
26
35
  }
27
36
 
37
+ /** the transcript folder name of a work tree: its path with every character that is no letter or digit as a dash */
38
+ export const projectSlug = (top: string): string => top.replace(/[^a-zA-Z0-9]/g, '-')
39
+
40
+ /** the live lanes of one repo: the transcript folders of its work trees, by their exact names. A name that only
41
+ * starts the same is another repo */
42
+ export function lanesOf(files: readonly TranscriptFile[], slugs: ReadonlySet<string>, now: number, windowMs = LIVE_WINDOW_MS): number {
43
+ return files.filter((f) => f.agent !== '' && now - f.mtime <= windowMs && slugs.has(f.project)).length
44
+ }
45
+
46
+ /** every work tree of the repo `top` is in, as git lists them: the main one and each linked one */
47
+ export function workTrees(top: string): string[] {
48
+ try {
49
+ const p = Bun.spawnSync([gitBin(), 'worktree', 'list', '--porcelain'], { cwd: top, stdout: 'pipe', stderr: 'ignore' })
50
+ const paths = p.stdout.toString().split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice('worktree '.length))
51
+ return paths.length > 0 ? paths : [top]
52
+ } catch {
53
+ return [top]
54
+ }
55
+ }
56
+
57
+ /** the kernel says memory is critical (darwin, level 4): a machine can die of memory with idle cores */
58
+ export function memoryCritical(): boolean {
59
+ if (process.platform !== 'darwin') return false
60
+ try {
61
+ return Number(Bun.spawnSync(['sysctl', '-n', 'kern.memorystatus_vm_pressure_level'], { stdout: 'pipe', stderr: 'ignore' }).stdout.toString().trim()) >= 4
62
+ } catch {
63
+ return false
64
+ }
65
+ }
66
+
28
67
  export type Capacity = {
29
68
  cores: number
30
- /** the larger of the 1 and the 5 minute load: a burst counts at once, and a lull does not open the door */
69
+ /** the 1 minute load: it follows the machine within a minute, where the 5 minute one held a lane back long after the others had ended */
31
70
  load: number
71
+ /** the agents live on the machine, sessions and lanes: each counts for at least one core, whatever the load says */
32
72
  agents: number
33
- /** what one agent costs now, in cores: the load shared between the live agents, never under one */
34
- perAgent: number
35
- /** the lanes the machine can start now */
36
- room: number
37
- /** how far the load sits over the cores, 0 when under */
38
- over: number
73
+ /** the lanes this repo has live now */
74
+ mine: number
75
+ /** the load is at twice the cores or more, or memory is critical: nothing starts */
76
+ dying: boolean
77
+ /** the lanes this repo runs now: its live ones plus one a free core, never under one, the maximum when one is given */
78
+ lanes: number
79
+ /** how many it can start now */
80
+ more: number
81
+ /** the maximum the owner gave, when the caller passed one */
82
+ max: number | null
39
83
  }
40
84
 
41
- export function capacityOf(p: { cores: number; load1: number; load5: number; agents: number }): Capacity {
42
- const load = Math.max(p.load1, p.load5)
43
- const perAgent = Math.max(1, p.agents > 0 ? load / p.agents : 1)
44
- const free = p.cores - load
45
- return { cores: p.cores, load, agents: p.agents, perAgent, room: free <= 0 ? 0 : Math.floor(free / perAgent), over: free < 0 ? -free : 0 }
85
+ export function capacityOf(p: { cores: number; load1: number; agents: number; mine: number; max?: number | null; memoryCritical?: boolean }): Capacity {
86
+ const dying = p.load1 >= p.cores * DYING_LOAD || p.memoryCritical === true
87
+ const max = p.max ?? null
88
+ // a lane in its model turn loads nothing here, so the load alone would hand out the same free cores at every
89
+ // ask: each live agent holds a core, and the load counts only where it is the larger
90
+ const free = Math.floor(p.cores - Math.max(p.load1, p.agents))
91
+ const lanes = max ?? Math.max(1, p.mine + free)
92
+ return { cores: p.cores, load: p.load1, agents: p.agents, mine: p.mine, dying, lanes, more: dying ? 0 : Math.max(0, lanes - p.mine), max }
46
93
  }
47
94
 
48
- /** the machine read now */
49
- export function readCapacity(now = Date.now()): { capacity: Capacity; live: LiveAgents } {
50
- const live = liveAgents(listTranscripts(), now)
51
- const [load1 = 0, load5 = 0] = loadavg()
52
- return { capacity: capacityOf({ cores: availableParallelism(), load1, load5, agents: live.sessions + live.lanes }), live }
95
+ /** the machine read now, for the repo `cwd` stands in */
96
+ export function readCapacity(cwd: string, max: number | null = null, now = Date.now()): { capacity: Capacity; live: LiveAgents; repo: string } {
97
+ // an agent whose turn ended holds no core: a lane that handed back, a session that waits for its user
98
+ const recent = oneRowAnAgent(listTranscripts().filter((f) => now - f.mtime <= LIVE_WINDOW_MS))
99
+ const files = recent.filter((f) => liveRow(f, { calls: false }).state.kind !== 'ended')
100
+ const root = gitRoot(cwd)
101
+ // a linked worktree counts with its repo: the common dir's parent is the main work tree
102
+ const top = root == null ? cwd : dirname(root.commonDir)
103
+ const live: LiveAgents = { ...liveAgents(files, now), idle: recent.length - files.length }
104
+ const [load1 = 0] = loadavg()
105
+ const mine = lanesOf(files, new Set(workTrees(top).map(projectSlug)), now)
106
+ return { capacity: capacityOf({ cores: availableParallelism(), load1, agents: live.sessions + live.lanes, mine, max, memoryCritical: memoryCritical() }), live, repo: top.split('/').at(-1) ?? top }
53
107
  }
54
108
 
55
109
  const one = (n: number): string => n.toFixed(1)
56
110
  const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
57
111
 
58
- /** the answer in three lines: the measure, who is live, the room */
59
- export function capacityLines(c: Capacity, live: LiveAgents): string[] {
112
+ /** the answer in three lines: the machine, this repo, what to do */
113
+ export function capacityLines(c: Capacity, live: LiveAgents, repo: string): string[] {
60
114
  const who = live.byProject.slice(0, 5).map(([p, n]) => `${p.replace(/^.*-dev-/, '')} ${n}`).join(', ')
61
- const verdict = c.room > 0
62
- ? `ok: room for ${plural(c.room, 'more lane')} now: ${one(c.cores - c.load)} of ${c.cores} cores free, ${one(c.perAgent)} a lane`
63
- : c.over > 0
64
- ? `WAIT: no room for a lane: the load is ${one(c.over)} over the ${c.cores} cores, so every tool of every agent already waits. A lane started now slows the others`
65
- : `WAIT: no room for a lane: ${one(c.cores - c.load)} of ${c.cores} cores free, and a lane costs ${one(c.perAgent)} now`
115
+ const verdict = c.dying
116
+ ? `STOP: the machine is dying: ${c.load >= c.cores * DYING_LOAD ? `load ${one(c.load)} on ${c.cores} cores, ${DYING_LOAD} times its cores or more` : 'its memory is critical'}. Start no lane${c.max != null ? `, the maximum of ${c.max} included` : ''}: run the next step yourself, and ask again before each next step`
117
+ : c.max != null
118
+ ? `ok: run up to ${plural(c.lanes, 'lane')}, the maximum given: start ${c.more} more`
119
+ : c.more > 0
120
+ ? `ok: run up to ${plural(c.lanes, 'lane')} now: start ${c.more} more (${c.cores} cores, ${c.agents} held by live agents, load ${one(c.load)})`
121
+ : `ok: keep ${plural(c.mine, 'lane')} and start none now: ${c.load >= c.cores + 0.05 ? `the load is ${one(c.load - c.cores)} over the ${c.cores} cores` : c.agents >= c.cores ? `${c.agents} live agents hold the ${c.cores} cores` : `the load is at the ${c.cores} cores`}. Ask again when a lane ends`
66
122
  return [
67
- `machine: ${c.cores} cores, load ${one(c.load)} (the larger of 1 and 5 min)`,
68
- `agents writing in the last ${LIVE_WINDOW_MS / 60_000} min: ${c.agents} (${plural(live.sessions, 'session')}, ${plural(live.lanes, 'lane')})${who === '' ? '' : `: ${who}`}`,
123
+ `machine: ${c.cores} cores, load ${one(c.load)} (1 min), ${plural(live.sessions + live.lanes, 'agent')} at work (${plural(live.sessions, 'session')}, ${plural(live.lanes, 'lane')})${who === '' ? '' : `: ${who}`}${(live.idle ?? 0) > 0 ? `; ${live.idle} more ${live.idle === 1 ? 'waits' : 'wait'}, turn ended, and ${live.idle === 1 ? 'holds' : 'hold'} no core` : ''}`,
124
+ `${repo}: ${plural(c.mine, 'lane')} at work`,
69
125
  verdict,
70
126
  ]
71
127
  }
@@ -50,6 +50,7 @@ import { liveStateOf } from '../ledger/live-runs.ts'
50
50
  import { CHECK_ID_ENV } from '../ledger/suite-log.ts'
51
51
  import { rememberWorld, replayWorld, worldKeyOf, type WorldCache } from '../ledger/world-cache.ts'
52
52
  import { extractProblems } from '../problems/extract.ts'
53
+ import { nearest } from './nearest.ts'
53
54
 
54
55
  /** the first line of a check that ran in this run, stamped with its cost. A
55
56
  * world answer carries its keep in a stamp already, so the cost joins it */
@@ -311,7 +312,10 @@ export function selectChecks(o: Pick<RunChecksOpts, 'checks' | 'audience' | 'ful
311
312
  const onlyIds: string[] = []
312
313
  for (const [raw, groups] of [...(o.onlyIds ?? []).map((r) => [r, true] as const), ...(o.withIds ?? []).map((r) => [r, false] as const)]) {
313
314
  const ids = resolve(raw, groups)
314
- if (ids == null) errors.push(`unknown check id${groups ? ' or group' : ''} '${raw}'`)
315
+ if (ids == null) {
316
+ const close = nearest(raw, o.checks.map((u) => u.id))
317
+ errors.push(`unknown check id${groups ? ' or group' : ''} '${raw}': ${close.length > 0 ? `did you mean ${close.join(', ')} ?` : '`shipkit checks` lists every id'}`)
318
+ }
315
319
  else for (const id of ids) { named.add(id); if (groups) onlyIds.push(id) }
316
320
  }
317
321
  // a dep cycle must die loud at select time, not hang the loop
@@ -19,6 +19,7 @@ import { rawName, slotBody } from './canonical-scripts.ts'
19
19
  import type { CheckCtx } from './check-ctx.ts'
20
20
  import { checkUnitReader, type UnitReader } from '../release/unit-resolve.ts'
21
21
  import { parseJsonc } from '../ts/jsonc.ts'
22
+ import { workspacePackagesOf } from '../ts/workspaces.ts'
22
23
  import { gateCheckCmd, tscFallbackNote } from '../ts/gate-typecheck.ts'
23
24
  import { parseBunTestScript, suiteFlags } from '../suite/judge-suites.ts'
24
25
  import { declaredTestUnits, siblingUnits, testCheckId, unitIgnores, unitTestBody, unitTsconfig, type TestUnitDecl } from '../suite/test-units.ts'
@@ -31,7 +32,9 @@ import { normalizeVendored } from './vendored.ts'
31
32
  /** how the floor reads the repo, by repo-relative path, plus the lookups
32
33
  * outside it: a binary on PATH, and the bun version (default: the bun
33
34
  * running shipkit) */
34
- export type FloorReader = UnitReader & { which: (bin: string) => string | null; bunVersion?: string }
35
+ /** `subdirs`: the dir names directly inside a repo-relative dir ('' is the root),
36
+ * to expand the workspace globs */
37
+ export type FloorReader = UnitReader & { which: (bin: string) => string | null; subdirs: (rel: string) => string[]; bunVersion?: string }
35
38
 
36
39
  /** the check context as a floor reader. A PATH lookup is not a repo read, so
37
40
  * it marks the answer untracked, and only the tsc fallback of a bun with no
@@ -39,6 +42,7 @@ export type FloorReader = UnitReader & { which: (bin: string) => string | null;
39
42
  export function checkFloorReader(c: CheckCtx): FloorReader {
40
43
  return {
41
44
  ...checkUnitReader(c),
45
+ subdirs: (rel) => c.entries(rel).filter((e) => e.kind === 'dir').map((e) => e.name),
42
46
  which: (bin) => {
43
47
  c.untrack(`looked ${bin} up on PATH, outside the repo`)
44
48
  return Bun.which(bin)
@@ -285,7 +289,7 @@ export function resolveFloor(c: RepoConfig, root: string, io: FloorReader): Floo
285
289
  if (typeof b === 'string') unfilled.push({ id, reason: slot.kind === 'routed-empty' ? `script '${id}' routes to shipkit and there is no '${rawName(id)}' body to run` : b })
286
290
  else { tasks.push(decorate(b.task)); sources[id] = b.source }
287
291
  }
288
- const siblings = siblingUnits(subs, io.text)
292
+ const siblings = siblingUnits(subs, io.text, workspacePackagesOf(io.text, io.subdirs, (c.vendored ?? []).map(normalizeVendored)))
289
293
  for (const t of unitTestTasks(root, io, subs, siblings, notes, unfilled)) { tasks.push(t); sources[t.id] = 'unit' }
290
294
  for (const t of unitTypecheckTasks(root, io, subs, siblings, notes, unfilled)) { tasks.push(t); sources[t.id] = 'unit' }
291
295
  return { tasks, disabled, unfilled, sources, notes }