rvlib-shipkit 2.13.0 → 2.14.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 (268) hide show
  1. package/CHANGELOG.md +32 -13
  2. package/package.json +1 -1
  3. package/src/assets/run-assets.ts +2 -2
  4. package/src/assets/server/studio-server.ts +27 -23
  5. package/src/check.ts +3 -3
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -4
  7. package/src/checks/SK002-contracts-fulfillness.check.ts +2 -2
  8. package/src/checks/SK003-claude-md-shape.check.ts +19 -12
  9. package/src/checks/SK004-gitignore-policy.check.ts +18 -4
  10. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  11. package/src/checks/SK006-npm-publish-safety.check.ts +3 -3
  12. package/src/checks/SK007-github-visibility.check.ts +2 -2
  13. package/src/checks/SK008-reviewer-agent.check.ts +1 -1
  14. package/src/checks/SK010-undeclared-unit.check.ts +2 -2
  15. package/src/checks/SK011-sibling-unit-ranges.check.ts +2 -2
  16. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  17. package/src/checks/SK013-one-way-in-policy.check.ts +2 -2
  18. package/src/checks/SK015-nested-repo.check.ts +2 -2
  19. package/src/checks/SK016-legacy-check-shapes.check.ts +2 -2
  20. package/src/checks/SK017-vscode-hub-task.check.ts +2 -2
  21. package/src/checks/SK018-test-files-run.check.ts +2 -2
  22. package/src/checks/SK019-tests-run-in-units.check.ts +2 -2
  23. package/src/checks/SK020-self-spawning-check.check.ts +2 -2
  24. package/src/checks/SK022-machine-runs-the-pin.check.ts +2 -2
  25. package/src/checks/SK024-identity-colors.check.ts +1 -1
  26. package/src/checks/SK025-release-drift.check.ts +2 -2
  27. package/src/checks/SK026-asks-autoclose.check.ts +2 -2
  28. package/src/checks/SK027-agent-wiki-links.check.ts +8 -2
  29. package/src/checks/SK028-readme.check.ts +2 -2
  30. package/src/checks/SK029-explicit-check-files.check.ts +3 -3
  31. package/src/checks/SK030-cache-audit.check.ts +7 -5
  32. package/src/checks/SK031-trace-audit.check.ts +7 -7
  33. package/src/checks/SK032-ignored-inputs.check.ts +3 -3
  34. package/src/checks/SK033-global-contribution.check.ts +11 -4
  35. package/src/checks/SK034-commit-gates-armed.check.ts +2 -2
  36. package/src/checks/SK035-public-clean.check.ts +4 -4
  37. package/src/checks/SK036-draft-media-size.check.ts +2 -2
  38. package/src/checks/SK037-keyword-additions.check.ts +43 -0
  39. package/src/cli/cmd_Backup.ts +2 -2
  40. package/src/cli/cmd_Commands.ts +4 -4
  41. package/src/cli/cmd_ConfigKeys.ts +2 -2
  42. package/src/cli/cmd_Drill.ts +1 -1
  43. package/src/cli/cmd_Home.ts +1 -1
  44. package/src/cli/cmd_Init.ts +1 -1
  45. package/src/cli/cmd_Media.ts +4 -4
  46. package/src/cli/cmd_Mv.ts +14 -7
  47. package/src/cli/cmd_Review.ts +2 -2
  48. package/src/cli/cmd_Smoke.ts +1 -1
  49. package/src/cli/cmd_Social.ts +3 -3
  50. package/src/cli/cmd_Sound.ts +1 -1
  51. package/src/cli/cmd_TraceAudit.ts +6 -6
  52. package/src/cli/cmd_Trailer.ts +2 -2
  53. package/src/cli/cmd_Veille.ts +2 -2
  54. package/src/cli/cmd_When.ts +2 -2
  55. package/src/cli/family-pages.ts +19 -19
  56. package/src/collections/collection-types.ts +2 -2
  57. package/src/collections/review.ts +1 -1
  58. package/src/comfy/comfy-panel.ts +2 -2
  59. package/src/contracts/manifests/discord.contract.ts +1 -1
  60. package/src/contracts/manifests/identity.contract.ts +1 -1
  61. package/src/contracts/manifests/itch.contract.ts +1 -1
  62. package/src/contracts/manifests/steam.contract.ts +1 -1
  63. package/src/core/agent-dir-at.ts +12 -0
  64. package/src/core/agent-dir.ts +16 -0
  65. package/src/core/budget.ts +1 -1
  66. package/src/core/canonical-scripts.ts +2 -2
  67. package/src/core/discover-checks.ts +1 -1
  68. package/src/core/global-contribution.ts +4 -1
  69. package/src/core/ignored-block.ts +1 -1
  70. package/src/core/ignored-inputs.ts +3 -2
  71. package/src/core/layout.ts +3 -3
  72. package/src/core/loop-watch.ts +1 -1
  73. package/src/core/motherhome.ts +2 -2
  74. package/src/core/one-way-in-policy.ts +8 -8
  75. package/src/core/run-ci.ts +3 -3
  76. package/src/core/runs-matrix.ts +1 -1
  77. package/src/core/slots.ts +14 -5
  78. package/src/core/trace-audit.ts +50 -9
  79. package/src/core/tree-rev.ts +1 -1
  80. package/src/drill/run.ts +1 -1
  81. package/src/home/daemon-jobs.ts +1 -1
  82. package/src/home/global-context.ts +11 -8
  83. package/src/home/gui-app/ShipkitGui.swift +91 -2
  84. package/src/home/inbox-shape.ts +1 -1
  85. package/src/home/inbox.ts +1 -1
  86. package/src/home/pm-config.ts +4 -1
  87. package/src/home/pm-inputs.ts +2 -0
  88. package/src/home/resources.ts +7 -2
  89. package/src/home/run-pm.ts +1 -1
  90. package/src/home/serve-web.ts +2 -2
  91. package/src/hooks/commit-message.ts +1 -1
  92. package/src/hooks/hook-gates.ts +1 -1
  93. package/src/hooks/leak-guard.ts +61 -8
  94. package/src/hooks/run-hooks.ts +18 -18
  95. package/src/identities/identities.ts +1 -1
  96. package/src/identities/machine-route.ts +1 -1
  97. package/src/identities/machine.ts +1 -1
  98. package/src/init-repo.ts +2 -2
  99. package/src/ledger/gate-checks.ts +1 -1
  100. package/src/ledger/record-kept.ts +1 -1
  101. package/src/media-kinds.ts +1 -1
  102. package/src/media-store/backup/daemon.ts +1 -1
  103. package/src/media-store/backup/keys.ts +1 -1
  104. package/src/media-store/backup/manifest.ts +1 -1
  105. package/src/media-store/backup/restore.ts +1 -1
  106. package/src/media-store/backup/run.ts +1 -1
  107. package/src/media-store/backup/secret.ts +1 -1
  108. package/src/media-store/backup/snapshot.ts +1 -1
  109. package/src/media-store/backup/sources.ts +1 -1
  110. package/src/media-store/content.ts +1 -1
  111. package/src/media-store/daemon.ts +1 -1
  112. package/src/media-store/db.ts +1 -1
  113. package/src/media-store/fact.ts +1 -1
  114. package/src/media-store/hand.ts +1 -1
  115. package/src/media-store/kind.ts +1 -1
  116. package/src/media-store/purge.ts +1 -1
  117. package/src/media-store/put.ts +1 -1
  118. package/src/media-store/remote.ts +1 -1
  119. package/src/media-store/space.ts +1 -1
  120. package/src/mv/mv-md.ts +63 -22
  121. package/src/pages/forward.ts +1 -1
  122. package/src/pages/frame-client.ts +1 -1
  123. package/src/pages/routes.ts +1 -1
  124. package/src/pages/unit.ts +1 -1
  125. package/src/plan/planner.ts +1 -1
  126. package/src/plan/repo-source.ts +1 -1
  127. package/src/release/public-clean.ts +25 -7
  128. package/src/release/run-bump.ts +1 -1
  129. package/src/release/run-release.ts +3 -3
  130. package/src/repo-config.ts +23 -16
  131. package/src/review/anim.ts +1 -1
  132. package/src/review/auto.ts +1 -1
  133. package/src/review/cells.ts +15 -1
  134. package/src/review/format.ts +2 -2
  135. package/src/review/marks.ts +1 -1
  136. package/src/review/media-kind.ts +1 -1
  137. package/src/review/media-read.ts +1 -1
  138. package/src/review/model.ts +14 -4
  139. package/src/review/notes.ts +52 -4
  140. package/src/review/previews.ts +1 -1
  141. package/src/review/project.ts +1 -1
  142. package/src/review/role.ts +1 -1
  143. package/src/review/routes.ts +14 -2
  144. package/src/review/store.ts +2 -2
  145. package/src/review/threads.ts +1 -1
  146. package/src/review/trailer-desk.ts +3 -3
  147. package/src/review/trailer-media.ts +1 -1
  148. package/src/review/trailer-model.ts +1 -1
  149. package/src/review/trailer-routes.ts +1 -1
  150. package/src/review/trailer-shots.ts +1 -1
  151. package/src/review/unit.ts +1 -1
  152. package/src/scaffold/files/tsconfig.json +1 -1
  153. package/src/scaffold/project-scaffold.ts +1 -1
  154. package/src/serve/embed.ts +1 -1
  155. package/src/serve/hub-app/check-words.ts +1 -1
  156. package/src/serve/hub-app/frames-st.ts +1 -1
  157. package/src/serve/hub-app/hash-route.ts +1 -1
  158. package/src/serve/hub-app/home-st.ts +1 -1
  159. package/src/serve/hub-app/home-strip.css +1 -1
  160. package/src/serve/hub-app/hub-app.tsx +2 -2
  161. package/src/serve/hub-app/identities-st.ts +1 -1
  162. package/src/serve/hub-app/identities-view.tsx +5 -4
  163. package/src/serve/hub-app/identity-address.ts +1 -1
  164. package/src/serve/hub-app/inbox-st.ts +1 -1
  165. package/src/serve/hub-app/inbox-view.tsx +1 -1
  166. package/src/serve/hub-app/kept-cols.tsx +30 -0
  167. package/src/serve/hub-app/keys.ts +1 -1
  168. package/src/serve/hub-app/media-svc.ts +1 -1
  169. package/src/serve/hub-app/pages-frames.tsx +1 -1
  170. package/src/serve/hub-app/pages-svc.ts +1 -1
  171. package/src/serve/hub-app/projects-svc.ts +1 -1
  172. package/src/serve/hub-app/repo-st.ts +1 -1
  173. package/src/serve/hub-app/review/review-board.tsx +1 -1
  174. package/src/serve/hub-app/review/review-cells.tsx +3 -2
  175. package/src/serve/hub-app/review/review-page.tsx +5 -4
  176. package/src/serve/hub-app/review/review-st.ts +15 -7
  177. package/src/serve/hub-app/review/review-thread.tsx +52 -5
  178. package/src/serve/hub-app/review/review-views.tsx +50 -33
  179. package/src/serve/hub-app/review/thread-st.ts +79 -27
  180. package/src/serve/hub-app/review/trailer-page.tsx +5 -4
  181. package/src/serve/hub-app/review/trailer-st.ts +1 -1
  182. package/src/serve/hub-app/review.css +9 -1
  183. package/src/serve/hub-app/site/site-part.tsx +1 -1
  184. package/src/serve/hub-app/site/site-st.ts +1 -1
  185. package/src/serve/hub-app/social/calendar.tsx +1 -1
  186. package/src/serve/hub-app/social/comms-page.tsx +29 -5
  187. package/src/serve/hub-app/social/kit.tsx +1 -1
  188. package/src/serve/hub-app/social/post-card.tsx +1 -1
  189. package/src/serve/hub-app/social/social-model.ts +1 -1
  190. package/src/serve/hub-app/social/social-page.tsx +12 -5
  191. package/src/serve/hub-app/social/social-st.ts +31 -3
  192. package/src/serve/hub-app/social.css +1 -1
  193. package/src/serve/hub-app/stores/stores-page.tsx +5 -4
  194. package/src/serve/hub-app/stores/stores-st.ts +1 -1
  195. package/src/serve/hub-app/stores.css +1 -1
  196. package/src/serve/hub-app/tree-row.tsx +1 -1
  197. package/src/serve/hub-app/veille/veille-page.tsx +5 -4
  198. package/src/serve/hub-app/veille/veille-st.ts +1 -1
  199. package/src/serve/hub-app/veille.css +1 -1
  200. package/src/serve/hub-runtime.ts +6 -2
  201. package/src/serve/project-gutter-route.ts +1 -1
  202. package/src/shot/box.ts +5 -7
  203. package/src/shot/browser-slot.ts +18 -6
  204. package/src/shot/client.ts +1 -2
  205. package/src/shot/clip-encoder.ts +16 -13
  206. package/src/shot/film-box.ts +132 -28
  207. package/src/shot/shooter.ts +21 -2
  208. package/src/shot/stepped-clip.ts +1 -1
  209. package/src/site/desk.ts +2 -2
  210. package/src/site/routes.ts +1 -1
  211. package/src/site/unit.ts +1 -1
  212. package/src/social/card-drafts.ts +24 -0
  213. package/src/social/compose.ts +2 -2
  214. package/src/social/desk-index.ts +1 -1
  215. package/src/social/desk-wire.ts +1 -1
  216. package/src/social/drafts.ts +3 -3
  217. package/src/social/load.ts +14 -1
  218. package/src/social/media-facts.ts +1 -1
  219. package/src/social/media-kind.ts +1 -1
  220. package/src/social/media-limit.ts +1 -1
  221. package/src/social/media-of.ts +1 -1
  222. package/src/social/migrate.ts +1 -1
  223. package/src/social/post-url.ts +1 -1
  224. package/src/social/presence.ts +2 -2
  225. package/src/social/public-read.ts +1 -1
  226. package/src/social/publish/bluesky.ts +1 -1
  227. package/src/social/publish/discord.ts +1 -1
  228. package/src/social/push.ts +10 -4
  229. package/src/social/richtext.ts +1 -1
  230. package/src/social/routes.ts +10 -4
  231. package/src/social/stats.ts +1 -1
  232. package/src/social/text.ts +1 -1
  233. package/src/social/tracker-route.ts +1 -1
  234. package/src/social/tracker.ts +1 -1
  235. package/src/social/unit.ts +1 -1
  236. package/src/social/writes.ts +1 -1
  237. package/src/stores/collection.ts +1 -1
  238. package/src/stores/desk.ts +1 -1
  239. package/src/stores/model.ts +1 -1
  240. package/src/stores/routes.ts +1 -1
  241. package/src/stores/unit.ts +1 -1
  242. package/src/suite/judge-suites.ts +1 -1
  243. package/src/trace/tracer.ts +12 -5
  244. package/src/trailer/adapter.ts +1 -1
  245. package/src/trailer/build.ts +6 -4
  246. package/src/trailer/holes.ts +1 -1
  247. package/src/trailer/passage.ts +1 -1
  248. package/src/trailer/prune.ts +1 -1
  249. package/src/trailer/states.ts +1 -1
  250. package/src/trailer/versions.ts +1 -1
  251. package/src/trailer/words.ts +1 -1
  252. package/src/tui/run-tui.ts +1 -1
  253. package/src/tui/tui-store.ts +1 -1
  254. package/src/veille/asks.ts +1 -1
  255. package/src/veille/auto.ts +1 -1
  256. package/src/veille/batch.ts +1 -1
  257. package/src/veille/chrome.ts +1 -1
  258. package/src/veille/collection.ts +1 -1
  259. package/src/veille/desk.ts +1 -1
  260. package/src/veille/identity.ts +1 -1
  261. package/src/veille/import.ts +1 -1
  262. package/src/veille/log.ts +1 -1
  263. package/src/veille/platforms.ts +1 -1
  264. package/src/veille/reads.ts +1 -1
  265. package/src/veille/replied.ts +1 -1
  266. package/src/veille/routes.ts +2 -2
  267. package/src/veille/watch.ts +1 -1
  268. package/src/veille/worth.ts +2 -2
package/src/core/slots.ts CHANGED
@@ -51,17 +51,26 @@ export const browserPool = (repo: string, size: number): SlotPool => ({ dir: joi
51
51
  /** a repo's browser cap when its config names none */
52
52
  export const DEFAULT_BROWSERS = 2
53
53
 
54
+ /** the box's browsers at once when its config names none */
55
+ export const DEFAULT_BOX_BROWSERS = 2
56
+
54
57
  /** why a `browsers` config is refused, or null when it holds */
55
58
  export function browsersProblem(v: unknown): string | null {
56
59
  if (v === undefined) return null
57
- if (v === null || typeof v !== 'object' || Array.isArray(v)) return `browsers is an object, { max: <browsers at once>, box?: <ssh host> }, got ${JSON.stringify(v)}`
60
+ const whole = (x: unknown) => typeof x === 'number' && Number.isInteger(x) && x >= 1
61
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) return `browsers is an object, { max: <browsers at once>, box?: { host: <ssh host>, max?: <browsers at once there> } }, got ${JSON.stringify(v)}`
58
62
  const extra = Object.keys(v).filter((k) => k !== 'max' && k !== 'box')
59
63
  if (extra.length > 0) return `browsers has unknown key(s) ${extra.join(', ')}: it takes only max and box`
60
- const box = (v as { box?: unknown }).box
61
- if (box !== undefined && !(typeof box === 'string' && /^[\w.-]+$/.test(box))) return `browsers.box is the ssh host whose browser films for this repo, like 'wm', got ${JSON.stringify(box)}`
62
64
  const max = (v as { max?: unknown }).max
63
- if (max !== undefined && !(typeof max === 'number' && Number.isInteger(max) && max >= 1))
64
- return `browsers.max is a whole number of browsers, 1 or more (default ${DEFAULT_BROWSERS}), got ${JSON.stringify(max)}`
65
+ if (max !== undefined && !whole(max)) return `browsers.max is a whole number of browsers, 1 or more (default ${DEFAULT_BROWSERS}), got ${JSON.stringify(max)}`
66
+ const box = (v as { box?: unknown }).box
67
+ if (box === undefined) return null
68
+ if (box === null || typeof box !== 'object' || Array.isArray(box)) return `browsers.box is { host: <ssh host>, max?: <browsers at once there> }, like { host: 'wm', max: 5 }, got ${JSON.stringify(box)}`
69
+ const boxExtra = Object.keys(box).filter((k) => k !== 'host' && k !== 'max')
70
+ if (boxExtra.length > 0) return `browsers.box has unknown key(s) ${boxExtra.join(', ')}: it takes only host and max`
71
+ const { host, max: boxMax } = box as { host?: unknown; max?: unknown }
72
+ if (!(typeof host === 'string' && /^[\w.-]+$/.test(host))) return `browsers.box.host is the ssh host whose browser films for this repo, like 'wm', got ${JSON.stringify(host)}`
73
+ if (boxMax !== undefined && !whole(boxMax)) return `browsers.box.max is a whole number of browsers on the box, 1 or more (default ${DEFAULT_BOX_BROWSERS}), got ${JSON.stringify(boxMax)}`
65
74
  return null
66
75
  }
67
76
 
@@ -1,9 +1,10 @@
1
- // THE TRACED AUDIT: which gitignored paths a task reads that its key cannot
2
- // see. A task's key covers the tracked tree and the paths `ignoredInputs`
3
- // names; a generated type or a local fixture it reads outside those is a
4
- // stale green waiting for its first edit. Each gate task runs once under the
5
- // tracer (trace/tracer.ts), and the ignored paths it touched that no key
6
- // covers become that task's proposals: the keys read them at once
1
+ // THE TRACED AUDIT: which paths a task reads that its key cannot see. An
2
+ // undeclared task's key covers the tracked tree, a declared one its list
3
+ // (a unit's `test:<unit>` is its dir and siblings), and each adds the paths
4
+ // `ignoredInputs` names; a generated type, a local fixture, or a doc a unit
5
+ // test reads outside its dir is a stale green waiting for its first edit.
6
+ // Each gate task runs once under the tracer (trace/tracer.ts), and the paths
7
+ // it touched that no key covers become that task's proposals: the keys read them at once
7
8
  // (core/audit-report.ts), and `sk trace-audit --fix` writes them into their
8
9
  // own managed block of repo.config.ts (core/ignored-block.ts).
9
10
  //
@@ -14,7 +15,7 @@
14
15
  // git common dir and reused while it is young: rule SK031 in
15
16
  // the health pass pays for it, and the fix pass that applies it reads it.
16
17
  import { mkdirSync, writeFileSync } from 'fs'
17
- import { dirname, posix } from 'path'
18
+ import { dirname, isAbsolute, posix, relative, resolve, sep } from 'path'
18
19
  import type { RepoConfig } from '../repo-config.ts'
19
20
  import { composeChecks } from '../ledger/gate-checks.ts'
20
21
  import { isNamesInput } from '../ledger/git-key.ts'
@@ -22,7 +23,7 @@ import { readTrace } from '../trace/read-trace.ts'
22
23
  import { dropTrace, learnBlind, traceUnavailable, tracedCommand } from '../trace/tracer.ts'
23
24
  import { spawnWithTimeout } from './spawn-timeout.ts'
24
25
  import { gitBin } from './git-bin.ts'
25
- import { auditReportPath, ignoredFor, pendingByTask, readAuditReport, type AuditReport, type AuditTask, type IgnoredInputs } from './audit-report.ts'
26
+ import { auditReportPath, auditedExtras, ignoredFor, pendingByTask, readAuditReport, type AuditReport, type AuditTask, type IgnoredInputs } from './audit-report.ts'
26
27
  import { addIgnoredInputs } from './ignored-block.ts'
27
28
  import { loadRepoConfig } from '../repo-config.ts'
28
29
 
@@ -39,6 +40,25 @@ function gitIgnored(root: string, paths: string[]): Set<string> {
39
40
  return new Set(p.stdout.toString().split('\n').filter((l) => l !== ''))
40
41
  }
41
42
 
43
+ /** the paths of `paths` in the work tree's key, by their exact name: tracked,
44
+ * or untracked and not ignored. A case insensitive disk answers a probe of
45
+ * `TSCONFIG.JSON` with `tsconfig.json`, and only git says which name exists */
46
+ function inWorkTree(root: string, paths: string[]): Set<string> {
47
+ if (paths.length === 0) return new Set()
48
+ const p = Bun.spawnSync([gitBin(), 'ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...paths.map((x) => `:(literal)${x}`)], { cwd: root, stdout: 'pipe', stderr: 'pipe' })
49
+ const listed = new Set(p.stdout.toString().split('\0').filter((l) => l !== ''))
50
+ return new Set(paths.filter((x) => listed.has(x)))
51
+ }
52
+
53
+ /** the toolkit running this audit, repo-relative when the repo hosts it. Its
54
+ * files are keyed by the code that produces each answer (the runner, a
55
+ * toolkit module's closure, `libused`), never by path, so a read under it
56
+ * is no finding */
57
+ function toolkitDir(root: string): string | null {
58
+ const rel = relative(root, resolve(import.meta.dir, '../..'))
59
+ return rel === '' || rel.startsWith('..') || isAbsolute(rel) ? null : rel.split(sep).join('/')
60
+ }
61
+
42
62
  const under = (p: string, dir: string): boolean => p === dir || p.startsWith(`${dir}/`)
43
63
 
44
64
  /** is this ignored path already in a key: bytes under a content entry, or a
@@ -47,6 +67,24 @@ function covered(p: string, listing: boolean, extras: string[]): boolean {
47
67
  return extras.some((e) => (isNamesInput(e) ? listing && under(p, e.slice(0, -3)) : under(p, e)))
48
68
  }
49
69
 
70
+ /** the list a task DECLARED, without what the kept audit added to its key:
71
+ * a finding the last audit keyed is still a finding until the config carries
72
+ * it, or the next audit would drop it and the key with it. null for a task
73
+ * keyed on the whole work tree, which covers every tracked file */
74
+ function declaredList(inputs: string[], keptExtras: string[], configExtras: string[]): string[] | null {
75
+ if (inputs.includes('.')) return null
76
+ return inputs.filter((p) => !keptExtras.includes(p) || configExtras.includes(p))
77
+ }
78
+
79
+ /** is this tracked (or untracked, not ignored) file in the key: under a
80
+ * declared path by content. A tracked dir a task only LISTS is not asked:
81
+ * a resolver lists every dir it walks (bun lists `packages/` on the way
82
+ * to a unit), and keying those names would re-run the task for any new file
83
+ * in the repo. A file it reads under that dir is a finding by itself */
84
+ function inTree(p: string, declared: string[], extras: string[]): boolean {
85
+ return [...declared, ...extras].some((e) => !isNamesInput(e) && under(p, e))
86
+ }
87
+
50
88
  /** the fewest entries that cover what was read: each file by itself, or a
51
89
  * dir by content once more than three files under it were read (its own
52
90
  * dir, or the outermost dir the task also listed); each listed dir as
@@ -91,6 +129,7 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
91
129
  const off = traceUnavailable(env)
92
130
  if (off != null) return { at: now, skipped: off, tasks: [] }
93
131
  const tasks: AuditTask[] = []
132
+ const toolkit = toolkitDir(root)
94
133
  for (const g of await composeChecks(root, config)) {
95
134
  const u = g.runnable
96
135
  if (u.body.cmd == null || g.row.runs.off != null || !g.row.runs.onCi || g.row.decl.inputs == null) continue
@@ -113,7 +152,9 @@ export async function traceAudit(root: string, config: RepoConfig, o: { fresh?:
113
152
  const dirs = dirsRead(Object.keys(r.reads.dirs ?? {}).filter(rel), Object.entries(r.reads.exists).filter(([, k]) => k === 'dir').map(([p]) => p).filter(rel), files)
114
153
  const ignored = gitIgnored(root, [...files, ...dirs])
115
154
  const extras = ignoredFor(config.ignoredInputs, u.id)
116
- const missF = files.filter((p) => ignored.has(p) && !covered(p, false, extras))
155
+ const declared = declaredList(g.row.decl.inputs, auditedExtras(kept, u.id), extras)
156
+ const outside = declared == null ? new Set<string>() : inWorkTree(root, files.filter((p) => !ignored.has(p) && !(toolkit != null && under(p, toolkit)) && !inTree(p, declared, extras)))
157
+ const missF = files.filter((p) => (ignored.has(p) ? !covered(p, false, extras) : outside.has(p)))
117
158
  const missD = dirs.filter((p) => ignored.has(p) && !covered(p, true, extras))
118
159
  tasks.push({ id: u.id, status: 'audited', uncovered: [...missF, ...missD].sort(), propose: proposeInputs(missF, missD) })
119
160
  } finally {
@@ -1,6 +1,6 @@
1
1
  // a work tree's revision in this process: a count the save watch (serve/tracked-watch.ts) moves whenever a file the
2
2
  // owner edits moves (tracked, or untracked and not ignored). A reader keyed on it reads the tree again only after a
3
- // move, where a listing costs a git spawn and a stat per file (wiki build/shipkit/home.md, Nothing heavy on the
3
+ // move, where a listing costs a git spawn and a stat per file (wiki tools/shipkit/home.md, Nothing heavy on the
4
4
  // daemon's loop).
5
5
  //
6
6
  // the one constraint a reader breaks first: no watch, no revision. `treeRev` is null for a root no live watch follows
package/src/drill/run.ts CHANGED
@@ -1,4 +1,4 @@
1
- // one drill run, read from its Claude Code transcript (wiki build/speed-up-agents.md): what it did, in
1
+ // one drill run, read from its Claude Code transcript (wiki meta/speed-up-agents/index.md): what it did, in
2
2
  // which order, at what cost, through the same transcript reader and timeline as `sk time`. Pure: lines in,
3
3
  // a record out, so a test feeds it a fixture. The record is json first; the md is a view of it, regenerated,
4
4
  // never edited by hand, so a number copied into a card cannot drift from its source.
@@ -1,4 +1,4 @@
1
- // THE DAEMON'S BACKGROUND JOBS, OFF ITS LOOP (wiki build/shipkit/home.md, Nothing heavy on the daemon's loop): the
1
+ // THE DAEMON'S BACKGROUND JOBS, OFF ITS LOOP (wiki tools/shipkit/home.md, Nothing heavy on the daemon's loop): the
2
2
  // backup, the retention sweep, the media store and the house's global context each run as a child process (`sk daemon job <id>`, niced), started
3
3
  // detached with its pid in a file, its lines appended to the daemon's log. The daemon only starts it and reads the
4
4
  // pid: an in place restart adopts a child still running and never starts a second one. What a job remembers between
@@ -10,18 +10,20 @@ import { createHash } from 'crypto'
10
10
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs'
11
11
  import { homedir } from 'os'
12
12
  import { dirname, join } from 'path'
13
+ import { contributionFileAt } from '../core/agent-dir-at.ts'
13
14
  import { CONTRIBUTION_FILE, CONTRIBUTION_MAX_BYTES, CONTRIBUTION_MAX_LINES, contributionBody, contributionOver, loadsContext } from '../core/global-contribution.ts'
14
15
  import { KEYWORD_FILE } from '../core/layout.ts'
15
16
  import { yieldLoop } from '../core/loop-watch.ts'
16
17
  import { repoUnitFiles } from '../core/discover-checks.ts'
17
- import { evaluateLeak, globalKeywordFile, maskPattern, parsePatterns } from '../hooks/leak-guard.ts'
18
+ import { evaluateLeak, globalKeywordFile, maskPattern, parsePatterns, withBuiltinRows } from '../hooks/leak-guard.ts'
18
19
  import { homeRepo, houseRepos } from '../serve/project-gutter.ts'
19
20
  import { scanGlobalUnits, type GlobalProcessDecl } from './global-units.ts'
20
21
 
21
22
  /** how often the daemon looks whether a source moved */
22
23
  export const GLOBAL_CONTEXT_EVERY_MS = 60_000
23
24
 
24
- export type ContextRepo = { name: string; path: string; description: string | null; contribution: string }
25
+ /** `file`: the contribution file, repo relative, in the agent folder its CLAUDE.md names */
26
+ export type ContextRepo = { name: string; path: string; description: string | null; contribution: string; file: string }
25
27
  export type ContextProcess = Pick<GlobalProcessDecl, 'id' | 'label' | 'repo' | 'url' | 'description'>
26
28
 
27
29
  /** the banned keyword a text matches, masked, or null: every item is
@@ -41,7 +43,7 @@ function capped(r: ContextRepo, body: string): string {
41
43
  // a heading above #### would outrank the `### <repo>` it sits under
42
44
  let cut = body.replace(/^#{1,3}(?=\s)/gm, '####').split('\n').slice(0, CONTRIBUTION_MAX_LINES).join('\n')
43
45
  while (Buffer.byteLength(cut) > CONTRIBUTION_MAX_BYTES) cut = cut.slice(0, cut.lastIndexOf('\n'))
44
- return `${cut}\n\n(cut: ${r.name}/${CONTRIBUTION_FILE} is ${over}, and SK033 fails there until it fits)`
46
+ return `${cut}\n\n(cut: ${r.name}/${r.file} is ${over}, and SK033 fails there until it fits)`
45
47
  }
46
48
 
47
49
  /** a description's first line, at most DESCRIPTION_MAX characters */
@@ -94,7 +96,7 @@ export function globalContextText(o: { repos: ContextRepo[]; processes: ContextP
94
96
  }
95
97
  const given = o.repos
96
98
  .map((r) => ({ r, body: contributionBody(r.contribution) }))
97
- .filter((x) => x.body !== '' && clean(`${x.r.name}/${CONTRIBUTION_FILE}`, x.body) != null)
99
+ .filter((x) => x.body !== '' && clean(`${x.r.name}/${x.r.file}`, x.body) != null)
98
100
  out.push('', '## What each repo offers', '')
99
101
  if (given.length === 0) out.push(`No repo contributes yet: each writes its own \`${CONTRIBUTION_FILE}\`.`)
100
102
  for (const { r, body } of given) out.push(`### ${r.name}`, '', capped(r, body), '')
@@ -110,8 +112,9 @@ export function contextRepo(r: { name: string; path: string }, home: string = ho
110
112
  const d = (JSON.parse(readFileSync(join(r.path, 'package.json'), 'utf8')) as { description?: unknown }).description
111
113
  if (typeof d === 'string' && d.trim() !== '') description = d.trim()
112
114
  } catch { /* no package.json, or one that does not parse: no line */ }
113
- const f = join(r.path, CONTRIBUTION_FILE)
114
- return { name: r.name, path: r.path.startsWith(`${home}/`) ? `~${r.path.slice(home.length)}` : r.path, description, contribution: existsSync(f) ? readFileSync(f, 'utf8') : '' }
115
+ const file = contributionFileAt(r.path)
116
+ const f = join(r.path, file)
117
+ return { name: r.name, path: r.path.startsWith(`${home}/`) ? `~${r.path.slice(home.length)}` : r.path, description, contribution: existsSync(f) ? readFileSync(f, 'utf8') : '', file }
115
118
  }
116
119
 
117
120
  /** writes the text when it differs from what the file holds; true when it wrote */
@@ -127,7 +130,7 @@ export function writeIfChanged(path: string, text: string): boolean {
127
130
  export function houseLeak(houseRoot: string): Leak | null {
128
131
  const files = [globalKeywordFile(), join(houseRoot, KEYWORD_FILE)].filter((f): f is string => f != null && existsSync(f))
129
132
  if (files.length === 0) return null
130
- const patterns = parsePatterns(files.map((f) => readFileSync(f, 'utf8')).join('\n'))
133
+ const patterns = parsePatterns(withBuiltinRows(files.map((f) => readFileSync(f, 'utf8'))))
131
134
  return (text) => {
132
135
  const hit = evaluateLeak([{ where: 'global context', content: text }], patterns, []).hits[0]
133
136
  return hit == null ? null : maskPattern(hit.pattern)
@@ -153,7 +156,7 @@ export async function contextSourcesStamp(root: string, home: string = homedir()
153
156
  const parts = [h.index, stampOf(h.index), stampOf(globalContextPath(h.index)), ...[globalKeywordFile(), join(h.home, KEYWORD_FILE)].map((f) => (f == null ? '-' : stampOf(f)))]
154
157
  for (const r of h.repos) {
155
158
  await yieldLoop()
156
- parts.push(r.path, stampOf(join(r.path, 'package.json')), stampOf(join(r.path, CONTRIBUTION_FILE)))
159
+ parts.push(r.path, stampOf(join(r.path, 'package.json')), stampOf(join(r.path, contributionFileAt(r.path))), stampOf(join(r.path, 'CLAUDE.md')))
157
160
  for (const f of repoUnitFiles(r.path)) parts.push(f, stampOf(f))
158
161
  }
159
162
  return createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 16)
@@ -4,7 +4,7 @@
4
4
  // project): the bundle's Info.plist names the app (CFBundleName) and the url
5
5
  // a bare launch opens (ShipkitStartURL). One WKWebView per window; every
6
6
  // `open -a <app> <url>` opens one more window, cmd-n too. A link to another
7
- // site opens in the default browser.
7
+ // site opens in the default browser, and a download lands in ~/Downloads.
8
8
  import AppKit
9
9
  import WebKit
10
10
 
@@ -124,13 +124,14 @@ final class Pane: NSView, NSSearchFieldDelegate {
124
124
  }
125
125
  }
126
126
 
127
- final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, NSWindowDelegate, NSMenuItemValidation {
127
+ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation {
128
128
  var windows: [NSWindow] = []
129
129
  var opened = false
130
130
 
131
131
  func applicationDidFinishLaunching(_ note: Notification) {
132
132
  if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
133
133
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
134
+ if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
134
135
  buildMenu()
135
136
  // esc closes the find bar of the key window, and reaches the page otherwise
136
137
  NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in
@@ -335,12 +336,100 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
335
336
 
336
337
  // the app's own host: stay in the window; anything else: the default browser
337
338
  func webView(_ web: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
339
+ // a link marked download saves the file, as a browser does, instead of showing it in the window
340
+ if action.shouldPerformDownload { return decisionHandler(.download) }
338
341
  guard let url = action.request.url, action.navigationType == .linkActivated else { return decisionHandler(.allow) }
339
342
  if stays(url) { return decisionHandler(.allow) }
340
343
  NSWorkspace.shared.open(url)
341
344
  decisionHandler(.cancel)
342
345
  }
343
346
 
347
+ // a response the window cannot show (an archive, an attachment) is saved too
348
+ func webView(_ web: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
349
+ let attachment = ((response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment")
350
+ decisionHandler(attachment || !response.canShowMIMEType ? .download : .allow)
351
+ }
352
+
353
+ func webView(_ web: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self }
354
+ func webView(_ web: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self }
355
+
356
+ /** where a download lands: the user's Downloads folder (SHIPKIT_GUI_DOWNLOADS for the self test) */
357
+ func downloadsDir() -> URL {
358
+ if let dir = ProcessInfo.processInfo.environment["SHIPKIT_GUI_DOWNLOADS"], !dir.isEmpty { return URL(fileURLWithPath: dir) }
359
+ return FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Downloads")
360
+ }
361
+
362
+ /** `name.ext`, else `name (2).ext`, `name (3).ext`: a download never overwrites a file */
363
+ func freeName(_ dir: URL, _ suggested: String) -> URL {
364
+ let name = suggested.isEmpty ? "download" : suggested
365
+ let base = (name as NSString).deletingPathExtension, ext = (name as NSString).pathExtension
366
+ var url = dir.appendingPathComponent(name)
367
+ var n = 2
368
+ while FileManager.default.fileExists(atPath: url.path) {
369
+ url = dir.appendingPathComponent(ext.isEmpty ? "\(base) (\(n))" : "\(base) (\(n)).\(ext)")
370
+ n += 1
371
+ }
372
+ return url
373
+ }
374
+
375
+ var downloads: [ObjectIdentifier: URL] = [:]
376
+ /** hears every finished download: the self test reads it */
377
+ var onDownloaded: ((URL?) -> Void)?
378
+
379
+ func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
380
+ let dest = freeName(downloadsDir(), suggestedFilename)
381
+ downloads[ObjectIdentifier(download)] = dest
382
+ completionHandler(dest)
383
+ }
384
+
385
+ // the Downloads stack in the dock bounces on the file, as it does for a browser's download
386
+ func downloadDidFinish(_ download: WKDownload) {
387
+ let dest = downloads.removeValue(forKey: ObjectIdentifier(download))
388
+ if let dest { DistributedNotificationCenter.default().post(name: Notification.Name("com.apple.DownloadFileFinished"), object: dest.path) }
389
+ onDownloaded?(dest)
390
+ }
391
+
392
+ // a failed download says so in a panel: never silent
393
+ func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
394
+ let dest = downloads.removeValue(forKey: ObjectIdentifier(download))
395
+ if let onDownloaded { return onDownloaded(nil) }
396
+ let alert = NSAlert()
397
+ alert.messageText = "Download failed"
398
+ alert.informativeText = "\(dest?.lastPathComponent ?? "the file"): \(error.localizedDescription)"
399
+ alert.runModal()
400
+ }
401
+
402
+ // `--self-test-download`: an offscreen page clicks a link marked download, twice, into SHIPKIT_GUI_DOWNLOADS; what
403
+ // landed printed, exit 0 only when both files hold the bytes under a free name and the page stayed on itself
404
+ func selfTestDownload() {
405
+ let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
406
+ web.navigationDelegate = self
407
+ let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
408
+ win.contentView = Pane(web: web)
409
+ win.orderFrontRegardless()
410
+ windows.append(win)
411
+ var saved: [String] = []
412
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
413
+ let click = "document.getElementById('a').click(); 'clicked'"
414
+ onDownloaded = { url in
415
+ let text = url.flatMap { try? String(contentsOf: $0, encoding: .utf8) } ?? "none"
416
+ saved.append("\(url?.lastPathComponent ?? "failed"):\(text)")
417
+ if saved.count == 1 { return web.evaluateJavaScript(click) { _, _ in } }
418
+ web.evaluateJavaScript("document.body.dataset.page") { page, _ in
419
+ print("saved=\(saved.joined(separator: ","))")
420
+ print("page=\((page as? String) ?? "gone")")
421
+ exit(saved == ["hello.txt:hello", "hello (2).txt:hello"] && (page as? String) == "here" ? 0 : 1)
422
+ }
423
+ }
424
+ var started = false
425
+ onLoad = { _ in
426
+ if started { return }
427
+ started = true
428
+ web.evaluateJavaScript(click) { _, _ in }
429
+ }
430
+ web.loadHTMLString("<body data-page=here><a id=a href='data:text/plain,hello' download='hello.txt'>save</a></body>", baseURL: nil)
431
+ }
432
+
344
433
  // window.open and target=_blank: one more window of this app for its own pages
345
434
  func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
346
435
  if let url = action.request.url {
@@ -1,4 +1,4 @@
1
- // the inbox as data (wiki build/shipkit/home.md, The inbox): everything that waits on the owner in every house repo,
1
+ // the inbox as data (wiki tools/shipkit/home.md, The inbox): everything that waits on the owner in every house repo,
2
2
  // one list. Pure and browser safe: the daemon (inbox.ts), the page and the tests share it. Each repo gives what it
3
3
  // already holds, never a store of its own: its review store's thread index and its hub's rows that need someone.
4
4
  //
package/src/home/inbox.ts CHANGED
@@ -1,4 +1,4 @@
1
- // the daemon's inbox route (wiki build/shipkit/home.md, The inbox): every loaded hub's review index and needing rows,
1
+ // the daemon's inbox route (wiki tools/shipkit/home.md, The inbox): every loaded hub's review index and needing rows,
2
2
  // shaped by inbox-shape.ts. It reads memory only (each store's thread index, each hub's warm rows) and a stat per
3
3
  // dated file, so a poll answers in milliseconds; the whole answer's hash is its ETag
4
4
  import { statSync } from 'fs'
@@ -7,6 +7,7 @@
7
7
  //
8
8
  // bun pm-config.ts <root> prints a PmConfig as json on stdout
9
9
  import { homedir } from 'os'
10
+ import { join } from 'path'
10
11
  import { houseInputs, stampOf, type PmConfig } from './pm-inputs.ts'
11
12
 
12
13
  export type { PmConfig }
@@ -27,7 +28,9 @@ if (import.meta.main) {
27
28
  files.set(r, f)
28
29
  return f
29
30
  })
30
- const out: PmConfig = { index: house.index, processes: [], errors: [], inputs, stamp: stampOf(inputs) }
31
+ // an archived repo's config too: its unarchive must bring its processes back at once
32
+ if (house.index != null) for (const r of house.archived) inputs.push(join(r.path, 'repo.config.ts'))
33
+ const out: PmConfig = { index: house.index, processes: [], errors: [], archived: house.archived.map((r) => r.name), inputs, stamp: stampOf(inputs) }
31
34
  if (house.index != null) {
32
35
  // a unit file imports the lib by name: this copy, like the daemon's
33
36
  const { installOneLib } = await import('../core/one-lib.ts')
@@ -13,6 +13,8 @@ export type PmConfig = {
13
13
  processes: GlobalProcessDecl[]
14
14
  /** the unit files that would not load */
15
15
  errors: string[]
16
+ /** the archived house repos, by name: a process one of them declared is stopped when it leaves (Resources.sync) */
17
+ archived: string[]
16
18
  /** every path whose stat can change this answer (houseInputs) */
17
19
  inputs: string[]
18
20
  /** stampOf(inputs), taken before the unit files were imported */
@@ -398,12 +398,17 @@ export class Resources {
398
398
 
399
399
  /** the declarations as they are now: an unchanged one keeps its state, a
400
400
  * changed or new one starts from its pid record, a dropped one leaves
401
- * its process running for whoever declares it next */
402
- sync(decls: GlobalProcessDecl[], errors: string[] = []): void {
401
+ * its process running for whoever declares it next (a unit file that
402
+ * fails to load mid edit must not kill it). A dropped one whose repo is
403
+ * now `archived` is stopped first: nothing runs in an archived repo */
404
+ async sync(decls: GlobalProcessDecl[], errors: string[] = [], archived: readonly string[] = []): Promise<void> {
403
405
  const key = (d: GlobalProcessDecl): string => JSON.stringify(d)
404
406
  const had = new Map(this.list.map((r) => [key(r.decl), r]))
407
+ const kept = new Set(decls.map(key))
408
+ const gone = this.list.filter((r) => !kept.has(key(r.decl)) && archived.includes(r.decl.repo) && !decls.some((d) => d.id === r.decl.id))
405
409
  this.list = decls.map((d) => had.get(key(d)) ?? new Resource(d, this.dir, this.o))
406
410
  this.errors = errors
411
+ await Promise.all(gone.map((r) => r.set('down')))
407
412
  }
408
413
 
409
414
  get(id: string): Resource | null {
@@ -130,7 +130,7 @@ export async function runPm(root: string, io: HomeIo, o: { port?: number } = {})
130
130
  if (reading) return
131
131
  reading = true
132
132
  void watch.poll()
133
- .then((n) => { if (n != null) pm.resources.sync(n.processes, n.errors) })
133
+ .then((n) => (n == null ? undefined : pm.resources.sync(n.processes, n.errors, n.archived)))
134
134
  .catch((e) => io.printErr(`WARN pm could not read the global processes again: ${(e as Error).message}`))
135
135
  .finally(() => { reading = false })
136
136
  }, PM_RESCAN_MS)
@@ -126,7 +126,7 @@ export type StaleWhy = 'restarting' | 'slow'
126
126
 
127
127
  /** the last good answer of each GET the page reads from the daemon: a JSON answer of status 200, by path, query and
128
128
  * encoding, its body as the daemon sent it. A restart of the daemon or a held loop then answers the page from here
129
- * (wiki build/shipkit/home.md, How it stays up: a restart never blanks the page) */
129
+ * (wiki tools/shipkit/home.md, How it stays up: a restart never blanks the page) */
130
130
  export class LastGood {
131
131
  private held = new Map<string, { body: Uint8Array<ArrayBuffer>; headers: [string, string][]; at: number }>()
132
132
 
@@ -264,7 +264,7 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
264
264
  /** each repo's pages, by id: where its process serves it, asked of the daemon and kept a while */
265
265
  const pageUrls = new Map<string, { at: number; pages: Map<string, { url: string; process?: string }> }>()
266
266
  /** a repo page's request straight to the repo's process, the daemon left out of the path: a busy daemon held a page's
267
- * html 2.5 s (wiki build/shipkit/project-pages.md, The proxy). null: the daemon answers it (a redirect, an unknown page) */
267
+ * html 2.5 s (wiki tools/shipkit/project-pages.md, The proxy). null: the daemon answers it (a redirect, an unknown page) */
268
268
  async function toPageProcess(req: Request, repo: string, rest: string, srv: Bun.Server<Pipe>): Promise<Response | null> {
269
269
  const at = pagePath(rest)
270
270
  if (at == null || at.rest === null) return null
@@ -63,7 +63,7 @@ export function commitMessageOffenses(message: string, opts?: { languageAllow?:
63
63
  else if (i === 0 && prose.includes(' - '))
64
64
  offenses.push({ line: i + 1, text: raw, kind: 'dash', why: 'inline " - " separator in the subject: use a comma or a colon' })
65
65
  if (frenchHits(raw, opts?.languageAllow))
66
- offenses.push({ line: i + 1, text: raw, kind: 'language', why: 'French: git surfaces are English, always (identity/writing-voice.md); quote product copy in "…" or `…` to exempt it' })
66
+ offenses.push({ line: i + 1, text: raw, kind: 'language', why: 'French: git surfaces are English, always (preferences/writing-voice/index.md); quote product copy in "…" or `…` to exempt it' })
67
67
  })
68
68
  return offenses
69
69
  }
@@ -23,7 +23,7 @@ export const HOOK_GATES = [
23
23
  export type HookGateId = (typeof HOOK_GATES)[number]['id']
24
24
 
25
25
  /** the page that owns every commit gate */
26
- export const HOOK_GATES_OWNER = 'build/shipkit/commit-gates.md'
26
+ export const HOOK_GATES_OWNER = 'tools/shipkit/commit-gates.md'
27
27
 
28
28
  /** the whole pre-commit hook, boot included, past which it warns */
29
29
  export const HOOK_BUDGET_MS = 1_000
@@ -21,7 +21,9 @@ import { basename, join } from 'path'
21
21
  import { gitBin } from '../core/git-bin.ts'
22
22
  import { KEYWORD_FILE, MACHINE_PRIVATE } from '../core/layout.ts'
23
23
 
24
- export type LeakHit = { where: string; pattern: string; file?: string }
24
+ /** `over`: an entry with a `count` named this pattern in this file, and the
25
+ * file now holds more, so every match blocks again until a person reviews it */
26
+ export type LeakHit = { where: string; pattern: string; file?: string; over?: { count: number; found: number; source: string } }
25
27
  export type LeakWaiver = LeakHit & { reason: string; source: string }
26
28
 
27
29
  /** what a hit REPORTS. The matched string is private by construction, and a
@@ -65,6 +67,12 @@ export type LeakAllowEntry = {
65
67
  * are arithmetic, not prose, so a keyword inside one is noise. The same
66
68
  * keyword on a normal line of the same file still blocks. */
67
69
  inHashes?: boolean
70
+ /** the most matches of the pattern the file may hold: one more and every
71
+ * match blocks again. Takes exactly one exact file in `paths` and one
72
+ * pattern, so the entry reads as « this word, this file, this many ».
73
+ * No readable label rides with it: a short keyword's label is the
74
+ * keyword, and the hit and waiver lines print it outside git. */
75
+ count?: number
68
76
  }
69
77
 
70
78
  export type LeakGuardResult =
@@ -84,8 +92,9 @@ const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$
84
92
  * or `desk-lamp-...` is a word that ends in `sk`, never a key */
85
93
  export const SK_KEY_ROW = 're:(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{20,}'
86
94
 
87
- /** the generic secret shapes: a private key, an AWS key id, an sk- key, a GitHub token, a Slack token. The starter of
88
- * every keyword file, and the rows the backup refuses a file on (media-store/backup/secret.ts) */
95
+ /** the generic secret shapes: a private key, an AWS key id, an sk- key, a GitHub token, a Slack token. Built into
96
+ * every scan (`withBuiltinRows`), never copied into a keyword file, and the rows the backup refuses a file on
97
+ * (media-store/backup/secret.ts) */
89
98
  export const SECRET_ROWS: readonly string[] = ['re:-----BEGIN [A-Z ]*PRIVATE KEY-----', 're:AKIA[0-9A-Z]{16}', SK_KEY_ROW, 're:ghp_[A-Za-z0-9]{36}', 're:xox[baprs]-[A-Za-z0-9-]{10,}']
90
99
 
91
100
  /** rows the hooks seeded before their shape was fixed, read as the fixed
@@ -108,7 +117,10 @@ export function parsePatterns(text: string): ParsedPatterns {
108
117
  const row = raw.trim()
109
118
  if (row === '' || row.startsWith('#')) continue
110
119
  if (row.startsWith('re:')) {
111
- try { regexes.push({ row, re: new RegExp((SEEDED_ROW_FIXES[row] ?? row).slice(3), 'i') }) }
120
+ // a secret shape is exact, like the token it matches (a key is `sk-`, never `SK-`, which a public plugin
121
+ // name carries); every other regex row is case-insensitive
122
+ const source = SEEDED_ROW_FIXES[row] ?? row
123
+ try { regexes.push({ row, re: new RegExp(source.slice(3), SECRET_ROWS.includes(source) ? '' : 'i') }) }
112
124
  catch { /* a malformed row must not disable the whole guard */ }
113
125
  } else if (row.startsWith('w:')) {
114
126
  const word = row.slice(2).trim().toLowerCase()
@@ -120,6 +132,36 @@ export function parsePatterns(text: string): ParsedPatterns {
120
132
  return { substrings, words, regexes }
121
133
  }
122
134
 
135
+ /** the keyword text a scan reads: the built-in secret shapes, then the files' rows */
136
+ export const withBuiltinRows = (fileTexts: string[]): string => [...SECRET_ROWS, ...fileTexts].join('\n')
137
+
138
+ /** what makes two rows one row: a `w:` row and a substring row of the same word, in any case, or two `re:` rows of
139
+ * one regex (a seeded row and its fix included). null for a blank line or a comment */
140
+ function rowKey(raw: string): string | null {
141
+ const row = raw.trim()
142
+ if (row === '' || row.startsWith('#')) return null
143
+ if (row.startsWith('re:')) return SEEDED_ROW_FIXES[row] ?? row
144
+ return (row.startsWith('w:') ? row.slice(2).trim() : row).toLowerCase()
145
+ }
146
+
147
+ /** a repo's keyword file holds its ADDITIONS only: the official list is the machine's
148
+ * (~/.shipkit/private/banned-keywords.txt) and the secret shapes are built in. `copies` are the rows either already
149
+ * holds; `text` is the file without them, its comments and its own rows kept. The official row's shape wins: a
150
+ * repo's `foo` beside an official `w:foo` is a copy that stays stricter than the list decided */
151
+ export function repoAdditions(repoText: string, officialText: string): { text: string; copies: string[]; own: number } {
152
+ const held = new Set([...SECRET_ROWS, ...officialText.split('\n')].map(rowKey).filter((k): k is string => k != null))
153
+ const copies: string[] = []
154
+ let own = 0
155
+ const kept = repoText.split('\n').filter((line) => {
156
+ const k = rowKey(line)
157
+ if (k == null) return true
158
+ if (held.has(k)) { copies.push(line.trim()); return false }
159
+ own++
160
+ return true
161
+ })
162
+ return { text: kept.join('\n'), copies, own }
163
+ }
164
+
123
165
  type Span = [start: number, end: number]
124
166
 
125
167
  // a substring row is matched by a case-insensitive REGEX rather than by
@@ -194,23 +236,28 @@ export function evaluateLeak(targets: ScanTarget[], p: ParsedPatterns, allow: Lo
194
236
  if (seen.has(key)) continue
195
237
  seen.add(key)
196
238
  const fp = patternFingerprint(id)
239
+ let over: LeakHit['over']
197
240
  const entry = allow.find((a) => {
198
241
  if (a.paths != null && !pathCovered(t.file, a.paths)) return false
199
242
  if (a.patterns != null && !a.patterns.some((x) => x === fp || x.toLowerCase() === id)) return false
243
+ if (a.count != null && (a.paths?.[0] !== t.file || spans.length > a.count)) {
244
+ if (a.paths?.[0] === t.file) over = { count: a.count, found: spans.length, source: a.source }
245
+ return false
246
+ }
200
247
  if (a.inHashes === true) {
201
248
  hashes ??= hashSpans(t.content)
202
249
  if (!spans.every((s) => inside(s, hashes!))) return false
203
250
  }
204
251
  return true
205
252
  })
206
- if (entry == null) hits.push({ where: t.where, pattern: id, file: t.file })
253
+ if (entry == null) hits.push({ where: t.where, pattern: id, file: t.file, ...(over == null ? {} : { over }) })
207
254
  else waived.push({ where: t.where, pattern: id, file: t.file, reason: entry.reason, source: entry.source })
208
255
  }
209
256
  }
210
257
  return { hits, waived }
211
258
  }
212
259
 
213
- const ALLOW_KEYS = ['reason', 'paths', 'patterns', 'inHashes']
260
+ const ALLOW_KEYS = ['reason', 'paths', 'patterns', 'inHashes', 'count']
214
261
  const FINGERPRINT = /^fp:[0-9a-f]{12}$/
215
262
 
216
263
  /** why an entry cannot be used, or null. `tracked` = the source is committed
@@ -230,6 +277,13 @@ export function leakAllowProblem(entry: unknown, where: string, tracked: boolean
230
277
  return `${where}: '${k}' is a non-empty array of non-empty strings`
231
278
  }
232
279
  if (e['inHashes'] != null && typeof e['inHashes'] !== 'boolean') return `${where}: 'inHashes' is a boolean`
280
+ if (e['count'] != null) {
281
+ const n = e['count']
282
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1) return `${where}: 'count' is a whole number of at least 1`
283
+ const paths = e['paths'] as string[] | undefined
284
+ if (paths?.length !== 1 || paths[0]!.endsWith('/')) return `${where}: 'count' takes exactly one file in 'paths', never a folder`
285
+ if ((e['patterns'] as string[] | undefined)?.length !== 1) return `${where}: 'count' takes exactly one entry in 'patterns'`
286
+ }
233
287
  if (tracked)
234
288
  for (const x of (e['patterns'] as string[] | undefined) ?? [])
235
289
  if (!FINGERPRINT.test(x))
@@ -358,9 +412,8 @@ export function runLeakGuard(root: string, o: LeakGuardOpts = {}): LeakGuardResu
358
412
  const file = join(root, rel)
359
413
  const sources = [existsSync(file) ? file : null, globalKeywordFile()].filter((f): f is string => f != null)
360
414
  if (sources.length === 0) return { status: 'skipped', reason: `${rel} not found and no machine-global banned-keywords.txt — no keyword list, no leak guard` }
361
- const patterns = parsePatterns(sources.map((f) => readFileSync(f, 'utf8')).join('\n'))
415
+ const patterns = parsePatterns(withBuiltinRows(sources.map((f) => readFileSync(f, 'utf8'))))
362
416
  const count = patterns.substrings.length + patterns.words.length + patterns.regexes.length
363
- if (count === 0) return { status: 'skipped', reason: `keyword file(s) have no patterns (${sources.join(', ')})` }
364
417
 
365
418
  const notes: string[] = []
366
419
  const allow: LoadedAllow[] = []