@buffcore/cli 0.8.46 → 0.8.47

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 (187) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/commands/change-merge-remove.d.ts +9 -2
  3. package/dist/commands/change-merge-remove.js +27 -15
  4. package/dist/commands/design/check.d.ts +1 -1
  5. package/dist/commands/design/check.js +2 -1
  6. package/dist/commands/design/contract-size.d.ts +7 -0
  7. package/dist/commands/design/contract-size.js +47 -0
  8. package/dist/commands/design/tells.en.d.ts +2 -0
  9. package/dist/commands/design/tells.en.js +2 -0
  10. package/dist/commands/design/tells.es.js +2 -0
  11. package/dist/commands/extension/places-approval.d.ts +4 -0
  12. package/dist/commands/process-paths.d.ts +14 -0
  13. package/dist/commands/process-paths.js +90 -0
  14. package/dist/commands/prototype/ai-approval.d.ts +27 -0
  15. package/dist/commands/prototype/ai-approval.js +60 -0
  16. package/dist/commands/prototype/approver.d.ts +71 -0
  17. package/dist/commands/prototype/approver.js +168 -0
  18. package/dist/commands/prototype/critique-gate.d.ts +14 -0
  19. package/dist/commands/prototype/critique-gate.js +48 -0
  20. package/dist/commands/prototype/fence.d.ts +1 -0
  21. package/dist/commands/prototype/fence.js +12 -0
  22. package/dist/commands/prototype/final-approval-grant.js +18 -0
  23. package/dist/commands/prototype/final-approval.js +4 -1
  24. package/dist/commands/prototype/index.js +3 -0
  25. package/dist/commands/prototype/layout-hints.d.ts +34 -0
  26. package/dist/commands/prototype/layout-hints.js +194 -0
  27. package/dist/commands/prototype/layout-measure.d.ts +39 -0
  28. package/dist/commands/prototype/layout-measure.js +97 -0
  29. package/dist/commands/prototype/layout-words.d.ts +2 -0
  30. package/dist/commands/prototype/layout-words.js +11 -0
  31. package/dist/commands/prototype/layout.en.d.ts +6 -0
  32. package/dist/commands/prototype/layout.en.js +7 -0
  33. package/dist/commands/prototype/load-location.js +2 -3
  34. package/dist/commands/prototype/messages.en.d.ts +14 -0
  35. package/dist/commands/prototype/messages.en.js +15 -1
  36. package/dist/commands/prototype/messages.js +15 -1
  37. package/dist/commands/prototype/milestone-versions.d.ts +4 -0
  38. package/dist/commands/prototype/prune-command.d.ts +5 -0
  39. package/dist/commands/prototype/prune-command.js +25 -0
  40. package/dist/commands/prototype/prune-words.d.ts +1 -0
  41. package/dist/commands/prototype/prune-words.js +7 -0
  42. package/dist/commands/prototype/prune.d.ts +16 -0
  43. package/dist/commands/prototype/prune.en.d.ts +9 -0
  44. package/dist/commands/prototype/prune.en.js +9 -0
  45. package/dist/commands/prototype/prune.es.d.ts +2 -0
  46. package/dist/commands/prototype/prune.es.js +9 -0
  47. package/dist/commands/prototype/prune.js +140 -0
  48. package/dist/commands/prototype/reopen-messages.d.ts +9 -0
  49. package/dist/commands/prototype/reopen-messages.js +19 -0
  50. package/dist/commands/prototype/report.d.ts +14 -0
  51. package/dist/commands/prototype/report.js +5 -1
  52. package/dist/commands/prototype/scene-layout.d.ts +17 -0
  53. package/dist/commands/prototype/scene-layout.js +57 -0
  54. package/dist/commands/prototype/scene-ready.js +8 -2
  55. package/dist/commands/prototype/scene.d.ts +15 -2
  56. package/dist/commands/prototype/scene.js +54 -42
  57. package/dist/commands/prototype/selector-answer.d.ts +43 -0
  58. package/dist/commands/prototype/selector-answer.js +73 -0
  59. package/dist/commands/prototype/selector-misses.d.ts +19 -0
  60. package/dist/commands/prototype/selector-misses.js +78 -0
  61. package/dist/commands/prototype/selector-prompt.d.ts +23 -0
  62. package/dist/commands/prototype/selector-prompt.js +32 -0
  63. package/dist/commands/prototype/selector-run.d.ts +13 -0
  64. package/dist/commands/prototype/selector-run.js +113 -0
  65. package/dist/commands/prototype/selector.d.ts +54 -0
  66. package/dist/commands/prototype/selector.js +96 -0
  67. package/dist/commands/prototype/snapshot-ancestor.js +2 -0
  68. package/dist/commands/prototype/snapshot-bundle.d.ts +17 -3
  69. package/dist/commands/prototype/snapshot-bundle.js +69 -7
  70. package/dist/commands/prototype/snapshot-check-files.d.ts +2 -0
  71. package/dist/commands/prototype/snapshot-check-files.js +41 -0
  72. package/dist/commands/prototype/snapshot-command.d.ts +2 -0
  73. package/dist/commands/prototype/snapshot-command.js +3 -0
  74. package/dist/commands/prototype/snapshot-completion.d.ts +4 -0
  75. package/dist/commands/prototype/snapshot-completion.js +30 -2
  76. package/dist/commands/prototype/snapshot-dependencies.d.ts +23 -2
  77. package/dist/commands/prototype/snapshot-dependencies.js +120 -14
  78. package/dist/commands/prototype/snapshot-hashes.d.ts +7 -0
  79. package/dist/commands/prototype/snapshot-hashes.js +28 -0
  80. package/dist/commands/prototype/snapshot-inputs.d.ts +15 -6
  81. package/dist/commands/prototype/snapshot-inputs.js +140 -197
  82. package/dist/commands/prototype/snapshot-matrix.d.ts +58 -0
  83. package/dist/commands/prototype/snapshot-matrix.js +95 -0
  84. package/dist/commands/prototype/snapshot-metro-inputs.d.ts +8 -0
  85. package/dist/commands/prototype/snapshot-metro-inputs.js +81 -0
  86. package/dist/commands/prototype/snapshot-owners.d.ts +6 -2
  87. package/dist/commands/prototype/snapshot-owners.js +12 -3
  88. package/dist/commands/prototype/snapshot-progress-entry.d.ts +14 -0
  89. package/dist/commands/prototype/snapshot-progress-entry.js +85 -0
  90. package/dist/commands/prototype/snapshot-progress.d.ts +19 -2
  91. package/dist/commands/prototype/snapshot-progress.js +54 -102
  92. package/dist/commands/prototype/snapshot-registry.d.ts +14 -0
  93. package/dist/commands/prototype/snapshot-registry.js +121 -0
  94. package/dist/commands/prototype/snapshot-report.d.ts +4 -0
  95. package/dist/commands/prototype/snapshot-report.js +77 -12
  96. package/dist/commands/prototype/snapshot-requests.d.ts +13 -3
  97. package/dist/commands/prototype/snapshot-requests.js +68 -30
  98. package/dist/commands/prototype/snapshot-reuse.d.ts +6 -1
  99. package/dist/commands/prototype/snapshot-reuse.js +17 -7
  100. package/dist/commands/prototype/snapshot-scene-inputs.d.ts +30 -0
  101. package/dist/commands/prototype/snapshot-scene-inputs.js +210 -0
  102. package/dist/commands/prototype/snapshot-served-inputs.d.ts +3 -0
  103. package/dist/commands/prototype/snapshot-served-inputs.js +12 -0
  104. package/dist/commands/prototype/snapshot-server-record.d.ts +26 -0
  105. package/dist/commands/prototype/snapshot-server-record.js +135 -0
  106. package/dist/commands/prototype/snapshot-servers.d.ts +3 -1
  107. package/dist/commands/prototype/snapshot-servers.js +50 -2
  108. package/dist/commands/prototype/snapshot-setup.d.ts +3 -1
  109. package/dist/commands/prototype/snapshot-setup.js +2 -1
  110. package/dist/commands/prototype/snapshot-surface-inputs.d.ts +23 -0
  111. package/dist/commands/prototype/snapshot-surface-inputs.js +161 -0
  112. package/dist/commands/prototype/snapshot-vite-inputs.d.ts +22 -0
  113. package/dist/commands/prototype/snapshot-vite-inputs.js +209 -0
  114. package/dist/commands/prototype/snapshot.d.ts +5 -0
  115. package/dist/commands/prototype/snapshot.js +72 -10
  116. package/dist/commands/prototype/version-commands.d.ts +4 -0
  117. package/dist/commands/prototype/version-commands.js +36 -8
  118. package/dist/commands/prototype/versions.d.ts +28 -2
  119. package/dist/commands/prototype/versions.js +25 -1
  120. package/dist/commands/prototype/vite-fs-path.d.ts +4 -0
  121. package/dist/commands/prototype/vite-fs-path.js +15 -0
  122. package/dist/commands/remove-links.d.ts +6 -0
  123. package/dist/commands/remove-links.js +17 -0
  124. package/dist/commands/size-docs.d.ts +9 -0
  125. package/dist/commands/size-docs.en.d.ts +6 -0
  126. package/dist/commands/size-docs.en.js +6 -0
  127. package/dist/commands/size-docs.es.d.ts +2 -0
  128. package/dist/commands/size-docs.es.js +6 -0
  129. package/dist/commands/size-docs.js +28 -0
  130. package/dist/commands/size.d.ts +5 -2
  131. package/dist/commands/size.js +27 -9
  132. package/dist/commands/ui/approval-authority.d.ts +10 -2
  133. package/dist/commands/ui/approval-authority.js +1 -0
  134. package/dist/commands/ui/autopilot-ai-approve.d.ts +18 -0
  135. package/dist/commands/ui/autopilot-ai-approve.js +68 -0
  136. package/dist/commands/ui/autopilot-loop.js +5 -6
  137. package/dist/commands/ui/autopilot-merge.js +3 -0
  138. package/dist/commands/ui/autopilot.en.d.ts +23 -0
  139. package/dist/commands/ui/autopilot.en.js +23 -0
  140. package/dist/commands/ui/autopilot.es.d.ts +23 -0
  141. package/dist/commands/ui/autopilot.es.js +23 -0
  142. package/dist/commands/ui/chat/find.d.ts +2 -0
  143. package/dist/commands/ui/chat/find.js +13 -0
  144. package/dist/commands/ui/chat/fresh-codex.d.ts +39 -0
  145. package/dist/commands/ui/chat/fresh-codex.js +175 -0
  146. package/dist/commands/ui/chat/fresh-critique.js +13 -5
  147. package/dist/commands/ui/chat/fresh-launch.d.ts +19 -0
  148. package/dist/commands/ui/chat/fresh-launch.js +67 -11
  149. package/dist/commands/ui/chat/fresh-prompts.d.ts +2 -0
  150. package/dist/commands/ui/chat/fresh-prompts.js +2 -0
  151. package/dist/commands/ui/chat/fresh-secrets.d.ts +6 -0
  152. package/dist/commands/ui/chat/fresh-secrets.js +172 -0
  153. package/dist/commands/ui/chat/fresh.en.d.ts +1 -0
  154. package/dist/commands/ui/chat/fresh.en.js +2 -1
  155. package/dist/commands/ui/chat/fresh.es.d.ts +1 -0
  156. package/dist/commands/ui/chat/fresh.es.js +2 -1
  157. package/dist/commands/ui/chat/worktree.js +25 -5
  158. package/dist/commands/ui/index.js +3 -0
  159. package/dist/commands/ui/loop-approve.d.ts +30 -1
  160. package/dist/commands/ui/loop-approve.js +2 -2
  161. package/dist/commands/ui/merge-route.js +3 -0
  162. package/dist/commands/ui/places-change.d.ts +4 -0
  163. package/dist/commands/ui/prototype-main.d.ts +4 -0
  164. package/dist/commands/ui/reopen-route.d.ts +117 -0
  165. package/dist/commands/ui/reopen-route.js +97 -0
  166. package/dist/commands/ui/save-route.d.ts +2 -0
  167. package/dist/commands/ui/save-route.js +4 -0
  168. package/dist/commands/ui/studio-routes.js +2 -0
  169. package/dist/commands/ui/studio-state.d.ts +33 -0
  170. package/dist/commands/ui/studio-versions.d.ts +24 -0
  171. package/dist/commands/ui/worktrees.d.ts +1 -1
  172. package/dist/commands/ui/worktrees.js +19 -3
  173. package/dist/commands/worktree-sweep.d.ts +45 -0
  174. package/dist/commands/worktree-sweep.js +188 -0
  175. package/dist/commands/worktrees-command.d.ts +32 -0
  176. package/dist/commands/worktrees-command.en.d.ts +25 -0
  177. package/dist/commands/worktrees-command.en.js +55 -0
  178. package/dist/commands/worktrees-command.js +96 -0
  179. package/dist/main.js +2 -0
  180. package/dist/ui/page.js +82 -82
  181. package/docs/PROTOTYPE.md +6 -3
  182. package/docs/WORKBENCH.md +11 -6
  183. package/package.json +11 -11
  184. package/skills/ape-critique/SKILL.md +41 -6
  185. package/skills/ape-design-system/SKILL.md +3 -0
  186. package/skills/ape-plan-change/SKILL.md +6 -0
  187. package/skills/ape-prototype/SKILL.md +8 -4
@@ -0,0 +1,113 @@
1
+ // The selector in a snapshot run (S3c): after the floor is known and before drawing, the selector's
2
+ // picks are added to the run (scenes drawn again, looks beyond the floor); the report keeps them. A
3
+ // full run (`--full` or a shared change) skips it, and records the selector's misses for later turns.
4
+ import { readFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { parseAgentsFile } from '../agents-file.js';
7
+ import { hostGitBytes } from '../safe-git.js';
8
+ import { freshEnvironment } from '../ui/chat/fresh-codex.js';
9
+ import { agentStart } from '../ui/chat/process.js';
10
+ import { t } from './messages.js';
11
+ import { runSelector, SELECTOR_SECONDS, skippedRun } from './selector.js';
12
+ import { extrasOf } from './selector-answer.js';
13
+ import { findMisses, readMisses, recordMisses } from './selector-misses.js';
14
+ import { findAncestor } from './snapshot-ancestor.js';
15
+ import { drawnLooks, lookName } from './snapshot-matrix.js';
16
+ /** The diff a turn reads at most, in characters. */
17
+ const DIFF_CHARS = 40_000;
18
+ /** The CLI's selector: plan/agents.md's validation agent and model, through the studio's launch. */
19
+ export function cliSelector(root, env = process.env) {
20
+ return async (folder, input) => {
21
+ let settings;
22
+ try {
23
+ settings = parseAgentsFile(readFileSync(join(root, 'plan', 'agents.md'), 'utf8'));
24
+ }
25
+ catch {
26
+ settings = undefined;
27
+ }
28
+ // The environment of the agent turn that runs this snapshot never reaches the selector's.
29
+ const source = freshEnvironment(env);
30
+ let start;
31
+ try {
32
+ start = agentStart(root, source);
33
+ }
34
+ catch {
35
+ return skippedRun('launch', input.floor);
36
+ }
37
+ const home = process.platform === 'win32' ? env.USERPROFILE : env.HOME;
38
+ return runSelector(folder, input, { start, settings, env, ...(home ? { home } : {}) });
39
+ };
40
+ }
41
+ function diffSince(root, base) {
42
+ if (!base)
43
+ return '';
44
+ const read = (args) => {
45
+ try {
46
+ return hostGitBytes(root, [
47
+ 'diff',
48
+ '--no-color',
49
+ '--no-ext-diff',
50
+ '--no-textconv',
51
+ ...args,
52
+ base,
53
+ ]).toString();
54
+ }
55
+ catch {
56
+ return '';
57
+ }
58
+ };
59
+ const stat = read(['--stat']);
60
+ const patch = stat.length < DIFF_CHARS ? read([]) : '';
61
+ const text = `${stat}\n${patch}`;
62
+ return text.length > DIFF_CHARS ? `${text.slice(0, DIFF_CHARS)}\n[diff cut]` : text;
63
+ }
64
+ /** Ask the selector (whole floor runs only) and add its picks to the run; never throws. */
65
+ export async function selectForRun(options, run) {
66
+ if (!options.selector)
67
+ return;
68
+ const floor = drawnLooks({ ...run, matrix: 'floor' }).map(lookName);
69
+ const why = run.matrix !== 'floor' ? 'full' : options.scene !== undefined ? 'scene' : undefined;
70
+ let record;
71
+ if (why)
72
+ record = skippedRun(why, floor);
73
+ else {
74
+ const base = options.root ? findAncestor(options.root, run.commit)?.report.commit : undefined;
75
+ const input = {
76
+ ...(base ? { base } : {}),
77
+ diff: options.root ? diffSince(options.root, base) : '',
78
+ scenes: options.scenes.scenes.map(({ key, surface, view }) => ({ key, surface, view })),
79
+ floor,
80
+ looks: drawnLooks({ ...run, matrix: 'full' }).map(lookName),
81
+ misses: readMisses(options.dir),
82
+ };
83
+ record = await options
84
+ .selector(options.root ?? process.cwd(), input)
85
+ .catch(() => skippedRun('failed', floor));
86
+ }
87
+ run.selector = record;
88
+ const extras = extrasOf(record.picks);
89
+ run.redraw = extras.scenes;
90
+ run.extraLooks = extras.looks;
91
+ if (record.skipped && record.skipped !== 'full' && record.skipped !== 'scene')
92
+ console.log(t('prototype.selectorSkipped', {
93
+ why: t(`prototype.selector.${record.skipped}`, {
94
+ seconds: SELECTOR_SECONDS,
95
+ agent: record.agent,
96
+ file: record.file,
97
+ }),
98
+ }));
99
+ else if (record.picks.length)
100
+ console.log(t('prototype.selectorAdded', { count: record.picks.length }));
101
+ }
102
+ /** After a whole full run: note the problems in looks the last selector run didn't draw. */
103
+ export function afterFullRun(options, report) {
104
+ if (!options.selector || !options.root || report.matrix !== 'full')
105
+ return;
106
+ try {
107
+ const last = findAncestor(options.root, report.commit)?.report;
108
+ recordMisses(options.dir, findMisses(report, last));
109
+ }
110
+ catch {
111
+ /* Learning never fails a run. */
112
+ }
113
+ }
@@ -0,0 +1,54 @@
1
+ import type { AgentsFile } from '@buffcore/contracts/workbench';
2
+ import { type FreshAgent } from '../ui/chat/fresh-codex.ts';
3
+ import { type Start, stopTree } from '../ui/runner.ts';
4
+ import { type SelectorDrop, type SelectorPick } from './selector-answer.ts';
5
+ import { type SelectorInput } from './selector-prompt.ts';
6
+ /** How long one selector turn may take. */
7
+ export declare const SELECTOR_SECONDS = 120;
8
+ /** Why the floor was drawn alone, or why a turn gave nothing. */
9
+ export type SelectorWhy = 'full' | 'scene' | 'agent-unsupported' | 'codex-sandbox' | 'ci' | 'host' | 'launch' | 'failed' | 'timeout' | 'shape' | 'secret';
10
+ export interface SelectorTurn {
11
+ agent: FreshAgent;
12
+ model?: string;
13
+ effort?: string;
14
+ /** `done`, or why the turn gave nothing. */
15
+ state: 'done' | Extract<SelectorWhy, 'launch' | 'failed' | 'timeout' | 'shape' | 'secret'>;
16
+ seconds: number;
17
+ /** With 'secret': the secret file whose value the answer quoted (never the value). */
18
+ file?: string;
19
+ }
20
+ /** What `report.json` keeps of the run's selector, in `selector`. */
21
+ export interface SelectorRecord {
22
+ /** Absent when at least one turn answered; else why the floor was drawn alone. */
23
+ skipped?: SelectorWhy;
24
+ /** With 'agent-unsupported': the agent plan/agents.md sets, which has no fresh read-only turn. */
25
+ agent?: string;
26
+ /** With 'secret': the secret file whose value a turn's answer quoted (never the value). */
27
+ file?: string;
28
+ turns: SelectorTurn[];
29
+ picks: SelectorPick[];
30
+ dropped: SelectorDrop[];
31
+ /** The floor's looks, to tell a later full run which looks this run drew. */
32
+ floor: string[];
33
+ }
34
+ export interface SelectorDeps {
35
+ start: Start;
36
+ settings: AgentsFile | undefined;
37
+ env: NodeJS.ProcessEnv;
38
+ stop?: typeof stopTree;
39
+ seconds?: number;
40
+ /** The bounded wait after a timeout (tests shorten it). */
41
+ stopWaitMs?: number;
42
+ /** The person's home, whose Claude settings give the turn their denies and sign-in. */
43
+ home?: string;
44
+ }
45
+ /** The floor alone, and why. */
46
+ export declare const skippedRun: (why: SelectorWhy, floor: readonly string[], turns?: SelectorTurn[]) => {
47
+ skipped: SelectorWhy;
48
+ turns: SelectorTurn[];
49
+ picks: never[];
50
+ dropped: never[];
51
+ floor: string[];
52
+ };
53
+ /** Run both turns and keep their union; never throws. */
54
+ export declare function runSelector(folder: string, input: SelectorInput, deps: SelectorDeps): Promise<SelectorRecord>;
@@ -0,0 +1,96 @@
1
+ import { freshAgent, freshUnready } from '../ui/chat/fresh-codex.js';
2
+ import { runFresh, stopFresh } from '../ui/chat/fresh-launch.js';
3
+ import { hostLaunchedEnv } from '../ui/chat/host-launched.js';
4
+ import { stopTree } from '../ui/runner.js';
5
+ import { parseAnswer, unionPicks, } from './selector-answer.js';
6
+ import { selectorPrompt } from './selector-prompt.js';
7
+ /** How long one selector turn may take. */
8
+ export const SELECTOR_SECONDS = 120;
9
+ /** How long a stopped turn may take to close before its settings file is removed anyway. */
10
+ const STOP_WAIT_MS = 5000;
11
+ const wait = (ms) => new Promise((done) => setTimeout(done, ms).unref?.());
12
+ /** The floor alone, and why. */
13
+ export const skippedRun = (why, floor, turns = []) => ({
14
+ skipped: why,
15
+ turns,
16
+ picks: [],
17
+ dropped: [],
18
+ floor: [...floor],
19
+ });
20
+ /** Run both turns and keep their union; never throws. */
21
+ export async function runSelector(folder, input, deps) {
22
+ const { settings, env } = deps;
23
+ // As the critique: without plan/agents.md, Claude Code.
24
+ const agent = settings?.work.validation ?? settings?.default ?? 'claude';
25
+ // Only an agent with a fresh read-only turn (fresh-launch.ts) takes it, as for the critique.
26
+ const unready = freshUnready(agent, folder);
27
+ if (unready || !freshAgent(agent)) {
28
+ const why = unready !== 'codex-sandbox' ? 'agent-unsupported' : unready;
29
+ return { ...skippedRun(why, input.floor), agent };
30
+ }
31
+ // A test run counts as CI: a child the tests start must never reach a live agent.
32
+ if (env.CI || env.VITEST)
33
+ return skippedRun('ci', input.floor);
34
+ // The host's own launcher starts every turn; a terminal run can't.
35
+ if (hostLaunchedEnv(env))
36
+ return skippedRun('host', input.floor);
37
+ const choice = {
38
+ ...(settings?.model?.validation ? { model: settings.model.validation } : {}),
39
+ ...(settings?.effort?.validation ? { effort: settings.effort.validation } : {}),
40
+ };
41
+ const bounds = {
42
+ scenes: new Set(input.scenes.map((scene) => scene.key)),
43
+ looks: new Set(input.looks),
44
+ floor: new Set(input.floor),
45
+ };
46
+ const launch = { agent, folder, ...choice, ...(deps.home ? { home: deps.home } : {}) };
47
+ const one = await selectorTurn(deps, { ...launch, prompt: selectorPrompt(input) });
48
+ if (!one.answer) {
49
+ const skipped = skippedRun(one.turn.state, input.floor, [one.turn]);
50
+ return one.turn.file ? { ...skipped, file: one.turn.file } : skipped;
51
+ }
52
+ const first = unionPicks([one.answer], bounds).picks.map(({ scene, look }) => ({
53
+ scene,
54
+ ...(look ? { look } : {}),
55
+ }));
56
+ const two = await selectorTurn(deps, { ...launch, prompt: selectorPrompt(input, first) });
57
+ return {
58
+ turns: [one.turn, two.turn],
59
+ ...unionPicks([one.answer, two.answer], bounds),
60
+ floor: [...input.floor],
61
+ };
62
+ }
63
+ async function selectorTurn(deps, launch) {
64
+ const started = Date.now();
65
+ const record = (state) => ({
66
+ agent: launch.agent ?? 'claude',
67
+ ...(launch.model ? { model: launch.model } : {}),
68
+ ...(launch.effort ? { effort: launch.effort } : {}),
69
+ state,
70
+ seconds: Math.max(0, Math.floor((Date.now() - started) / 1000)),
71
+ });
72
+ const run = runFresh(deps.start, launch);
73
+ if (!run.child)
74
+ return { turn: record('launch') };
75
+ let timer;
76
+ const late = new Promise((done) => {
77
+ timer = setTimeout(() => done('timeout'), (deps.seconds ?? SELECTOR_SECONDS) * 1000);
78
+ timer.unref?.();
79
+ });
80
+ const result = await Promise.race([run.result, late]);
81
+ clearTimeout(timer);
82
+ if (result === 'timeout') {
83
+ stopFresh(run, deps.stop ?? stopTree);
84
+ // The stopped tree closes the child, which removes the turn's settings file; if it never does,
85
+ // the file goes after a bounded wait.
86
+ await Promise.race([run.result, wait(deps.stopWaitMs ?? STOP_WAIT_MS)]);
87
+ run.release?.();
88
+ return { turn: record('timeout') };
89
+ }
90
+ if (result.secret)
91
+ return { turn: { ...record('secret'), file: result.secret } };
92
+ if (result.text === undefined)
93
+ return { turn: record('failed') };
94
+ const answer = parseAnswer(result.text);
95
+ return answer ? { turn: record('done'), answer } : { turn: record('shape') };
96
+ }
@@ -57,6 +57,8 @@ export function findAncestor(root, current, reader = bounded) {
57
57
  '--format=%H',
58
58
  '--name-only',
59
59
  '--no-renames',
60
+ // A commit that only removes old reports (`ape prototype prune`) holds no report to reuse.
61
+ '--diff-filter=d',
60
62
  '--diff-merges=first-parent',
61
63
  '--relative',
62
64
  '--no-notes',
@@ -1,11 +1,12 @@
1
1
  import type { Surface } from '@buffcore/config';
2
- import { type Loader, type PluginBuild } from 'esbuild';
2
+ import { type Loader, type Metafile, type PluginBuild } from 'esbuild';
3
3
  export declare const loaders: Record<string, Loader>;
4
4
  export interface SurfaceEntry {
5
5
  surface: Surface;
6
6
  dir: string;
7
7
  registry: string;
8
8
  roots: string[];
9
+ routes: string[];
9
10
  }
10
11
  export declare const catalogInput = "snapshot-inputs:snapshot-catalog-effects";
11
12
  export declare const virtualInput: (name: string) => boolean;
@@ -19,12 +20,13 @@ export declare function bundleSurface(root: string, catalog: string, entry: Surf
19
20
  format: "esm";
20
21
  platform: "browser";
21
22
  conditions: string[];
22
- mainFields: string[] | undefined;
23
+ mainFields: string[];
23
24
  define: {
24
25
  'import.meta.env.DEV': string;
25
26
  __DEV__: string;
26
27
  };
27
28
  jsx: "automatic";
29
+ jsxDev: boolean;
28
30
  ignoreAnnotations: true;
29
31
  loader: Record<string, Loader>;
30
32
  logLevel: "silent";
@@ -39,6 +41,18 @@ export declare function bundleSurface(root: string, catalog: string, entry: Surf
39
41
  name: string;
40
42
  setup(builder: PluginBuild): void;
41
43
  }[];
42
- resolveExtensions: string[] | undefined;
44
+ resolveExtensions: string[];
43
45
  write: false;
44
46
  }>>;
47
+ export type Imports = Metafile['inputs'][string]['imports'];
48
+ export type SourceFiles = {
49
+ read(file: string): Promise<Buffer>;
50
+ };
51
+ export declare function code(file: string, deps: SourceFiles, format?: 'esm'): Promise<string>;
52
+ export declare function reexports(source: string): RegExpExecArray[] | undefined;
53
+ /** Isolate initialization and re-export wiring without running the module. */
54
+ export declare function moduleEffects(file: string, deps: SourceFiles): Promise<{
55
+ initializes: boolean;
56
+ exports: string[];
57
+ defaultOnly: boolean;
58
+ } | undefined>;
@@ -1,6 +1,7 @@
1
1
  import { isBuiltin } from 'node:module';
2
2
  import { dirname, extname, join } from 'node:path';
3
- import { build } from 'esbuild';
3
+ import { build, transform } from 'esbuild';
4
+ import { inProse, tokenize } from './milestone-tokens.js';
4
5
  import { catalogForWalk } from './snapshot-catalog.js';
5
6
  export const loaders = {
6
7
  '.ts': 'ts',
@@ -47,7 +48,18 @@ function projectCatalog(builder, route, catalog, project) {
47
48
  });
48
49
  }
49
50
  function metroWeb(builder, dir) {
50
- builder.onResolve({ filter: /^react-native$/ }, ({ kind }) => builder.resolve('react-native-web', { kind, resolveDir: dir }));
51
+ // The stock Metro resolver gives the app one copy of each of its React singletons.
52
+ builder.onResolve({
53
+ filter: /^(?:react|react-dom|react-native|react-native-web|react-native-unistyles|react-native-svg)(?:\/|$)/,
54
+ }, ({ path, kind, pluginData }) => {
55
+ if (pluginData === metroEmpty)
56
+ return;
57
+ return builder.resolve(path === 'react-native' ? 'react-native-web' : path, {
58
+ kind,
59
+ resolveDir: dir,
60
+ pluginData: metroEmpty,
61
+ });
62
+ });
51
63
  // Stock Metro stubs Node builtins on the web when there is no browser implementation.
52
64
  builder.onResolve({ filter: /^node:/ }, ({ path }) => {
53
65
  if (isBuiltin(path))
@@ -76,12 +88,12 @@ function surfacePlugin(catalog, entry, read, unproven) {
76
88
  };
77
89
  }
78
90
  export function bundleSurface(root, catalog, entry, read, unproven) {
79
- const { surface, registry, roots } = entry;
91
+ const { surface, registry, roots, routes } = entry;
80
92
  const app = surface === 'app';
81
93
  return build({
82
94
  absWorkingDir: root,
83
95
  stdin: {
84
- contents: [registry, ...roots]
96
+ contents: [...new Set([registry, ...roots, ...routes])]
85
97
  .map((file, index) => `export * as __snapshotRoot${index} from ${JSON.stringify(file)};`)
86
98
  .join('\n'),
87
99
  resolveDir: root,
@@ -89,10 +101,13 @@ export function bundleSurface(root, catalog, entry, read, unproven) {
89
101
  bundle: true,
90
102
  format: 'esm',
91
103
  platform: 'browser',
92
- conditions: app ? ['react-native'] : ['development', 'module'],
93
- mainFields: app ? ['react-native', 'browser', 'main'] : undefined,
104
+ conditions: app ? [] : ['development', 'module'],
105
+ mainFields: app
106
+ ? ['browser', 'module', 'main']
107
+ : ['browser', 'module', 'jsnext:main', 'jsnext', 'main'],
94
108
  define: { 'import.meta.env.DEV': 'true', __DEV__: 'true' },
95
109
  jsx: 'automatic',
110
+ jsxDev: !app,
96
111
  ignoreAnnotations: true,
97
112
  loader: loaders,
98
113
  logLevel: 'silent',
@@ -106,7 +121,54 @@ export function bundleSurface(root, catalog, entry, read, unproven) {
106
121
  plugins: [surfacePlugin(catalog, entry, read, unproven)],
107
122
  resolveExtensions: app
108
123
  ? ['.web.tsx', '.web.ts', '.web.jsx', '.web.js', '.tsx', '.ts', '.jsx', '.js', '.json']
109
- : undefined,
124
+ : ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'],
110
125
  write: false,
111
126
  });
112
127
  }
128
+ export async function code(file, deps, format) {
129
+ return (await transform((await deps.read(file)).toString('utf8'), {
130
+ loader: loaders[extname(file).toLowerCase()],
131
+ jsx: 'preserve',
132
+ ...(format ? { format } : {}),
133
+ })).code;
134
+ }
135
+ // esbuild prints top-level import and export declarations at column zero. Check token ranges
136
+ // too: identical lines inside a template literal are not declarations.
137
+ export function reexports(source) {
138
+ const tokens = tokenize(source, true);
139
+ if (!tokens)
140
+ return;
141
+ const pattern = /^export (\*|\{[\w$\s,]+}) from ("[^"\\\n]+");$/gm;
142
+ return [...source.matchAll(pattern)].filter(({ index }) => !inProse(tokens.prose, index));
143
+ }
144
+ /** Isolate initialization and re-export wiring without running the module. */
145
+ export async function moduleEffects(file, deps) {
146
+ const source = await code(file, deps, 'esm');
147
+ const original = (await deps.read(file)).toString('utf8');
148
+ const named = /\bexport\s*[{*]/.test(original) ? reexports(await code(file, deps)) : [];
149
+ const stars = reexports(source);
150
+ if (!named || !stars)
151
+ return;
152
+ const tokens = tokenize(source, true);
153
+ if (!tokens)
154
+ return;
155
+ const list = [...source.matchAll(/^export \{[\w$\s,]+};$/gm)].filter(({ index }) => !inProse(tokens.prose, index));
156
+ const body = source.split('');
157
+ for (const { index, 0: statement } of [...stars, ...list])
158
+ body.fill(' ', index, index + statement.length);
159
+ const { code: effects } = await transform(body.join(''), {
160
+ loader: 'jsx',
161
+ jsx: 'transform',
162
+ treeShaking: true,
163
+ ignoreAnnotations: true,
164
+ minifySyntax: true,
165
+ });
166
+ // A retained directive, declaration, or instruction is a shared effect.
167
+ return {
168
+ initializes: effects.split('\n').some((line) => !!line && !line.startsWith('import ')),
169
+ exports: [...named, ...list].map(([statement]) => statement),
170
+ defaultOnly: !named.length &&
171
+ list.length === 1 &&
172
+ /^export \{\s+[\w$]+ as default\s+};$/.test(list[0]?.[0] ?? ''),
173
+ };
174
+ }
@@ -0,0 +1,2 @@
1
+ /** The files of `checks`, beside this one. */
2
+ export declare function sceneCheckFiles(): string[];
@@ -0,0 +1,41 @@
1
+ import { join } from 'node:path';
2
+ /**
3
+ * The code that draws and checks a scene, that proves its requests and decides its file set, and
4
+ * the words its findings use: in every fingerprint, so a change to any of them redraws every scene.
5
+ */
6
+ const checks = [
7
+ 'browser',
8
+ 'checks',
9
+ 'fonts',
10
+ 'font-samples',
11
+ 'full-shot',
12
+ 'measure',
13
+ 'media-ready',
14
+ 'messages',
15
+ 'messages.en',
16
+ 'module-errors',
17
+ 'readable',
18
+ 'scene',
19
+ 'scene-check',
20
+ 'scene-load',
21
+ 'scene-look',
22
+ 'scene-ready',
23
+ 'scene-render',
24
+ 'snapshot-bundle',
25
+ 'snapshot-dependencies',
26
+ 'snapshot-inputs',
27
+ 'snapshot-metro-inputs',
28
+ 'snapshot-recovery',
29
+ 'snapshot-registry',
30
+ 'snapshot-requests',
31
+ 'snapshot-scene-inputs',
32
+ 'snapshot-served-inputs',
33
+ 'snapshot-surface-inputs',
34
+ 'snapshot-themes',
35
+ 'snapshot-vite-inputs',
36
+ ];
37
+ /** The files of `checks`, beside this one. */
38
+ export function sceneCheckFiles() {
39
+ const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
40
+ return [...checks.map((name) => name + extension), 'drawn-text.js'].map((file) => join(import.meta.dirname, file));
41
+ }
@@ -11,6 +11,8 @@ export interface SnapshotFlags extends Pick<SetupFlags, 'ownFirst'> {
11
11
  remake?: boolean;
12
12
  /** Scene pages open at once, 1 to 4 (`--pages`); unset, the cores and the free memory say. */
13
13
  pages?: number;
14
+ /** `--full`: every theme, mode and pseudo-locale, not only the floor (S3b). */
15
+ full?: boolean;
14
16
  json?: boolean;
15
17
  }
16
18
  /** `ape prototype snapshot`: needs `ape dev` running. Fails (exit 1) when a check fails. */
@@ -10,6 +10,7 @@ import { readModel } from './data.js';
10
10
  import { MAX_SHOT_HEIGHT } from './full-shot.js';
11
11
  import { number, t } from './messages.js';
12
12
  import { newestReport, renderRetries, requireCommitted, shortCommit, unsavedWork, } from './report.js';
13
+ import { cliSelector } from './selector-run.js';
13
14
  import { remakeScreenshots, takeSnapshot } from './snapshot.js';
14
15
  import { SnapshotAccessRefused } from './snapshot-refused.js';
15
16
  import { requireServers, setup, } from './snapshot-setup.js';
@@ -91,6 +92,8 @@ async function taken(run, commit, onFallback) {
91
92
  // Asked again after the scenes are drawn: an edit made while they were drawn counts too.
92
93
  dirty: () => unsaved || unsavedWork(root),
93
94
  runId: runId && /^[a-f0-9-]{36}$/.test(runId) ? runId : undefined,
95
+ // Fresh, read-only agent turns pick looks beyond the floor (S3c); never the turn running this.
96
+ selector: cliSelector(root),
94
97
  artifacts: { 'data.json': model, ...(design ? { 'design.json': design } : {}) },
95
98
  });
96
99
  }
@@ -10,6 +10,8 @@ export declare function previousSnapshot(folder: string): Promise<{
10
10
  }>;
11
11
  export type PreviousSnapshot = Awaited<ReturnType<typeof previousSnapshot>>;
12
12
  export declare function inputsFingerprint(inputs: SnapshotInputs | undefined, scenes: readonly Scene[], api: SnapshotReport['api'], data: unknown): string | undefined;
13
+ export declare function runtimeHash(inputs: SnapshotInputs | undefined, run: Run): string | undefined;
14
+ export declare function reuseFingerprint(inputs: SnapshotInputs | undefined, { key, surface }: Pick<Scene, 'key' | 'surface'>): string | undefined;
13
15
  export declare function keptScenes(report: SnapshotReport | undefined, selected: ReadonlySet<string>): {
14
16
  scenes: {
15
17
  key: string;
@@ -26,6 +28,8 @@ export declare function keptScenes(report: SnapshotReport | undefined, selected:
26
28
  loadFailure?: import("./scene-errors.ts").LoadFailure;
27
29
  scriptError?: import("./scene-errors.ts").LoadFailure;
28
30
  reusedFrom?: string;
31
+ matrix?: import("./snapshot-matrix.ts").Matrix;
32
+ extraLooks?: string[];
29
33
  }[];
30
34
  problems: {
31
35
  check: "clipped" | "contrast" | "identical" | "overflow" | "render" | "target" | "text" | "theme";
@@ -2,8 +2,10 @@ import { readFileSync } from 'node:fs';
2
2
  import { copyFile, readdir, readFile } from 'node:fs/promises';
3
3
  import { basename, join } from 'node:path';
4
4
  import { t } from './messages.js';
5
+ import { SnapshotCheckoutChanged } from './snapshot-checkout.js';
5
6
  import { SnapshotRefused } from './snapshot-env.js';
6
7
  import { sha256 } from './snapshot-hashes.js';
8
+ import { requireReusedScenes } from './snapshot-reuse.js';
7
9
  import { boundShots, hashShots } from './snapshot-shots.js';
8
10
  import { lookKey, photographed } from './snapshot-themes.js';
9
11
  export async function previousSnapshot(folder) {
@@ -30,7 +32,21 @@ export async function previousSnapshot(folder) {
30
32
  export function inputsFingerprint(inputs, scenes, api, data) {
31
33
  if (!scenes.length || !inputs || scenes.some((scene) => !inputs.fingerprints.has(scene.key)))
32
34
  return;
33
- return sha256(JSON.stringify([api, data, [...inputs.fingerprints]]));
35
+ const runtime = inputs.runtime();
36
+ return sha256(JSON.stringify([api, data, [...inputs.fingerprints], ...(runtime ? [runtime] : [])]));
37
+ }
38
+ export function runtimeHash(inputs, run) {
39
+ try {
40
+ return inputs?.runtime(true);
41
+ }
42
+ catch {
43
+ throw new SnapshotCheckoutChanged(run.commit, run.commit);
44
+ }
45
+ }
46
+ export function reuseFingerprint(inputs, { key, surface }) {
47
+ const hash = inputs?.reuse.get(key);
48
+ const runtime = inputs?.runtime(false, surface);
49
+ return hash && runtime ? sha256(JSON.stringify([hash, runtime])) : hash;
34
50
  }
35
51
  export function keptScenes(report, selected) {
36
52
  if (!report)
@@ -82,6 +98,16 @@ export async function partialReason(old, run, picked, all, report, inputs) {
82
98
  const looks = run.looks.flatMap((theme) => Object.keys(theme.color)
83
99
  .filter((mode) => photographed(theme.key, mode, run.product))
84
100
  .map((mode) => lookKey(theme.key, mode)));
101
+ if (old.reuseReport !== undefined || old.scenes.some((scene) => scene.reusedFrom)) {
102
+ try {
103
+ if (!run.root)
104
+ return 'prototype.partialEvidence';
105
+ requireReusedScenes(run.root, old, false);
106
+ }
107
+ catch {
108
+ return 'prototype.partialEvidence';
109
+ }
110
+ }
85
111
  for (const scene of old.scenes) {
86
112
  if (picked.has(scene.key))
87
113
  continue;
@@ -89,7 +115,9 @@ export async function partialReason(old, run, picked, all, report, inputs) {
89
115
  if (!shots ||
90
116
  shots.length !== looks.length ||
91
117
  scene.apiCalls !== false ||
92
- scene.fingerprint !== inputs?.fingerprints.get(scene.key))
118
+ !scene.fingerprint ||
119
+ (scene.fingerprint !== inputs?.fingerprints.get(scene.key) &&
120
+ scene.fingerprint !== reuseFingerprint(inputs, scene)))
93
121
  return 'prototype.partialEvidence';
94
122
  const hashes = await hashShots(run.out, run.commit, scene);
95
123
  if (!hashes ||
@@ -1,9 +1,30 @@
1
+ import { type Metafile } from 'esbuild';
1
2
  import { type SurfaceEntry } from './snapshot-bundle.ts';
2
3
  export declare const dependencyVersion: string;
3
- /** Hash the same bytes esbuild reads, sharing file reads across surfaces. */
4
+ export declare const slash: (path: string) => string;
5
+ export declare function pathIn(root: string, file: string): boolean;
6
+ declare function cachedFiles(): {
7
+ read: (file: string) => Promise<Buffer<ArrayBufferLike>>;
8
+ digest: (file: string) => Promise<string>;
9
+ same: () => Promise<boolean>;
10
+ has: (file: string) => boolean;
11
+ };
12
+ /** The resolver reads manifests and config even though they need not be bundle inputs. */
13
+ export declare function resolutionSettings(root: string, files: readonly string[], deps: ReturnType<typeof snapshotDependencies>): Promise<string[][]>;
14
+ /** Include competing paths if the stock bundlers may prioritize them differently. */
15
+ export declare function resolutionAlternatives(importer: string, spec: string | undefined, target: string): string[];
16
+ /** esbuild's input graph can list external TS type imports even though no JS loads them. */
17
+ export declare function runtimeExternal(path: string, specifiers: readonly string[], read: ReturnType<typeof cachedFiles>['read']): Promise<boolean>;
4
18
  export declare function snapshotDependencies(root: string, catalog: string): {
5
19
  read: (file: string) => Promise<Buffer<ArrayBufferLike>>;
6
20
  digest: (file: string) => Promise<string>;
7
21
  same: () => Promise<boolean>;
8
- walk: (entry: SurfaceEntry) => Promise<(readonly [string, string])[] | undefined>;
22
+ walk: (entry: SurfaceEntry) => Promise<{
23
+ files: (readonly [string, string])[];
24
+ meta: Metafile;
25
+ selected: Set<string>;
26
+ unproven: Set<string>;
27
+ } | undefined>;
28
+ assets: (path: string) => never[] | Promise<string[] | undefined>;
9
29
  };
30
+ export {};