@buffcore/cli 0.8.41 → 0.8.43

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 (219) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/commands/agents-file.d.ts +5 -0
  3. package/dist/commands/agents-file.js +30 -7
  4. package/dist/commands/change.d.ts +4 -0
  5. package/dist/commands/change.js +12 -5
  6. package/dist/commands/create-block.d.ts +2 -1
  7. package/dist/commands/create-block.js +7 -5
  8. package/dist/commands/create.d.ts +3 -2
  9. package/dist/commands/create.en.js +1 -1
  10. package/dist/commands/create.es.js +1 -1
  11. package/dist/commands/create.js +8 -6
  12. package/dist/commands/design/check.d.ts +2 -0
  13. package/dist/commands/design/check.js +6 -0
  14. package/dist/commands/design/journey-roles.d.ts +6 -0
  15. package/dist/commands/design/journey-roles.js +60 -0
  16. package/dist/commands/design/references.d.ts +12 -0
  17. package/dist/commands/design/references.js +44 -0
  18. package/dist/commands/design/tells-text.js +2 -2
  19. package/dist/commands/design/tells.d.ts +3 -1
  20. package/dist/commands/design/tells.en.d.ts +2 -0
  21. package/dist/commands/design/tells.en.js +2 -0
  22. package/dist/commands/design/tells.es.js +2 -0
  23. package/dist/commands/design/tells.js +10 -7
  24. package/dist/commands/dev.js +3 -0
  25. package/dist/commands/extension/places-approval.d.ts +1 -1
  26. package/dist/commands/port-claims.d.ts +23 -0
  27. package/dist/commands/port-claims.js +95 -0
  28. package/dist/commands/prototype/browser.d.ts +9 -4
  29. package/dist/commands/prototype/browser.js +26 -18
  30. package/dist/commands/prototype/comp-record.d.ts +27 -0
  31. package/dist/commands/prototype/comp-record.js +85 -0
  32. package/dist/commands/prototype/comp-words.d.ts +12 -0
  33. package/dist/commands/prototype/comp-words.js +24 -0
  34. package/dist/commands/prototype/comp.d.ts +26 -0
  35. package/dist/commands/prototype/comp.js +71 -0
  36. package/dist/commands/prototype/export-base.d.ts +27 -0
  37. package/dist/commands/prototype/export-base.js +80 -0
  38. package/dist/commands/prototype/export.d.ts +3 -2
  39. package/dist/commands/prototype/export.js +13 -6
  40. package/dist/commands/prototype/index.js +1 -0
  41. package/dist/commands/prototype/media-ready.d.ts +8 -0
  42. package/dist/commands/prototype/media-ready.js +36 -0
  43. package/dist/commands/prototype/messages.en.d.ts +6 -0
  44. package/dist/commands/prototype/messages.en.js +6 -0
  45. package/dist/commands/prototype/messages.js +6 -0
  46. package/dist/commands/prototype/milestone-versions.d.ts +1 -1
  47. package/dist/commands/prototype/record-look-child.js +4 -1
  48. package/dist/commands/prototype/scene.d.ts +3 -1
  49. package/dist/commands/prototype/scene.js +22 -6
  50. package/dist/commands/prototype/snapshot-command.js +1 -1
  51. package/dist/commands/prototype/snapshot-inputs.js +35 -7
  52. package/dist/commands/prototype/snapshot-setup.d.ts +12 -1
  53. package/dist/commands/prototype/snapshot-setup.js +31 -6
  54. package/dist/commands/prototype/snapshot.d.ts +2 -0
  55. package/dist/commands/prototype/snapshot.js +2 -1
  56. package/dist/commands/prototype/versions.d.ts +3 -3
  57. package/dist/commands/ui/agents-route.d.ts +2 -0
  58. package/dist/commands/ui/agents-route.js +8 -5
  59. package/dist/commands/ui/approval-authority.d.ts +1 -1
  60. package/dist/commands/ui/approve.js +7 -1
  61. package/dist/commands/ui/chat/allow-folder.js +23 -77
  62. package/dist/commands/ui/chat/claude-permissions.d.ts +21 -0
  63. package/dist/commands/ui/chat/claude-permissions.js +69 -0
  64. package/dist/commands/ui/chat/codex-idle.d.ts +2 -0
  65. package/dist/commands/ui/chat/codex-overrides.js +2 -1
  66. package/dist/commands/ui/chat/codex-permissions.d.ts +12 -0
  67. package/dist/commands/ui/chat/codex-permissions.js +97 -0
  68. package/dist/commands/ui/chat/command-parts.d.ts +33 -0
  69. package/dist/commands/ui/chat/command-parts.js +219 -0
  70. package/dist/commands/ui/chat/command-wrappers.d.ts +21 -0
  71. package/dist/commands/ui/chat/command-wrappers.js +100 -0
  72. package/dist/commands/ui/chat/design-deletes.d.ts +1 -0
  73. package/dist/commands/ui/chat/design-deletes.js +39 -0
  74. package/dist/commands/ui/chat/fresh-critique.d.ts +28 -0
  75. package/dist/commands/ui/chat/fresh-critique.js +121 -0
  76. package/dist/commands/ui/chat/fresh-launch.d.ts +31 -0
  77. package/dist/commands/ui/chat/fresh-launch.js +122 -0
  78. package/dist/commands/ui/chat/fresh-prompts.d.ts +17 -0
  79. package/dist/commands/ui/chat/fresh-prompts.js +76 -0
  80. package/dist/commands/ui/chat/fresh-report.d.ts +8 -0
  81. package/dist/commands/ui/chat/fresh-report.js +36 -0
  82. package/dist/commands/ui/chat/fresh-routes.d.ts +3 -0
  83. package/dist/commands/ui/chat/fresh-routes.js +64 -0
  84. package/dist/commands/ui/chat/fresh-settings.d.ts +12 -0
  85. package/dist/commands/ui/chat/fresh-settings.js +66 -0
  86. package/dist/commands/ui/chat/fresh-store.d.ts +17 -0
  87. package/dist/commands/ui/chat/fresh-store.js +67 -0
  88. package/dist/commands/ui/chat/fresh.d.ts +31 -0
  89. package/dist/commands/ui/chat/fresh.en.d.ts +7 -0
  90. package/dist/commands/ui/chat/fresh.en.js +7 -0
  91. package/dist/commands/ui/chat/fresh.es.d.ts +7 -0
  92. package/dist/commands/ui/chat/fresh.es.js +7 -0
  93. package/dist/commands/ui/chat/fresh.js +112 -0
  94. package/dist/commands/ui/chat/launch-input.d.ts +4 -2
  95. package/dist/commands/ui/chat/launch-input.js +16 -3
  96. package/dist/commands/ui/chat/limit-mentions.d.ts +5 -0
  97. package/dist/commands/ui/chat/limit-mentions.js +94 -0
  98. package/dist/commands/ui/chat/limit-patterns.d.ts +15 -0
  99. package/dist/commands/ui/chat/limit-patterns.js +182 -0
  100. package/dist/commands/ui/chat/limits-hook.d.ts +1 -0
  101. package/dist/commands/ui/chat/limits-hook.js +30 -0
  102. package/dist/commands/ui/chat/limits.d.ts +44 -0
  103. package/dist/commands/ui/chat/limits.en.d.ts +20 -0
  104. package/dist/commands/ui/chat/limits.en.js +20 -0
  105. package/dist/commands/ui/chat/limits.es.d.ts +2 -0
  106. package/dist/commands/ui/chat/limits.es.js +19 -0
  107. package/dist/commands/ui/chat/limits.js +236 -0
  108. package/dist/commands/ui/chat/local-settings.d.ts +17 -0
  109. package/dist/commands/ui/chat/local-settings.js +73 -0
  110. package/dist/commands/ui/chat/opencode-config.d.ts +22 -0
  111. package/dist/commands/ui/chat/opencode-config.js +83 -0
  112. package/dist/commands/ui/chat/parse-claude.js +25 -5
  113. package/dist/commands/ui/chat/permission-ask.d.ts +44 -0
  114. package/dist/commands/ui/chat/permission-ask.js +145 -0
  115. package/dist/commands/ui/chat/permission-channel.d.ts +18 -0
  116. package/dist/commands/ui/chat/permission-channel.js +67 -0
  117. package/dist/commands/ui/chat/permission-route.d.ts +10 -0
  118. package/dist/commands/ui/chat/permission-route.js +47 -0
  119. package/dist/commands/ui/chat/permission-tool.d.ts +1 -0
  120. package/dist/commands/ui/chat/permission-tool.js +86 -0
  121. package/dist/commands/ui/chat/permissions.d.ts +11 -12
  122. package/dist/commands/ui/chat/permissions.js +20 -102
  123. package/dist/commands/ui/chat/planning-limits.d.ts +12 -0
  124. package/dist/commands/ui/chat/planning-limits.js +46 -0
  125. package/dist/commands/ui/chat/process.js +4 -1
  126. package/dist/commands/ui/chat/prompt.d.ts +8 -1
  127. package/dist/commands/ui/chat/prompt.en.d.ts +4 -0
  128. package/dist/commands/ui/chat/prompt.en.js +4 -0
  129. package/dist/commands/ui/chat/prompt.es.d.ts +4 -0
  130. package/dist/commands/ui/chat/prompt.es.js +4 -0
  131. package/dist/commands/ui/chat/prompt.js +18 -50
  132. package/dist/commands/ui/chat/publish-limits.d.ts +4 -0
  133. package/dist/commands/ui/chat/publish-limits.js +97 -0
  134. package/dist/commands/ui/chat/recorded-turn.js +6 -0
  135. package/dist/commands/ui/chat/routes.js +2 -0
  136. package/dist/commands/ui/chat/secret-folders.d.ts +16 -0
  137. package/dist/commands/ui/chat/secret-folders.js +35 -0
  138. package/dist/commands/ui/chat/stdin-shells.d.ts +8 -0
  139. package/dist/commands/ui/chat/stdin-shells.js +102 -0
  140. package/dist/commands/ui/chat/step-rules.d.ts +13 -0
  141. package/dist/commands/ui/chat/step-rules.js +47 -0
  142. package/dist/commands/ui/chat/store.js +11 -2
  143. package/dist/commands/ui/chat/stream.en.d.ts +6 -0
  144. package/dist/commands/ui/chat/stream.en.js +6 -0
  145. package/dist/commands/ui/chat/stream.es.d.ts +6 -0
  146. package/dist/commands/ui/chat/stream.es.js +6 -0
  147. package/dist/commands/ui/chat/stream.js +8 -2
  148. package/dist/commands/ui/chat/turn-guard.d.ts +27 -0
  149. package/dist/commands/ui/chat/turn-guard.js +86 -0
  150. package/dist/commands/ui/chat/turn-input.d.ts +3 -2
  151. package/dist/commands/ui/chat/turn-input.js +3 -1
  152. package/dist/commands/ui/chat/turn-scenes.d.ts +19 -0
  153. package/dist/commands/ui/chat/turn-scenes.js +44 -0
  154. package/dist/commands/ui/chat/turn-state.d.ts +11 -0
  155. package/dist/commands/ui/chat/turn.js +9 -3
  156. package/dist/commands/ui/comp-approval.d.ts +6 -0
  157. package/dist/commands/ui/comp-approval.js +42 -0
  158. package/dist/commands/ui/host.js +3 -0
  159. package/dist/commands/ui/index.js +18 -6
  160. package/dist/commands/ui/level-route.js +8 -3
  161. package/dist/commands/ui/loop-approve.d.ts +4 -4
  162. package/dist/commands/ui/page.d.ts +19 -1
  163. package/dist/commands/ui/page.js +9 -6
  164. package/dist/commands/ui/places-change.d.ts +1 -1
  165. package/dist/commands/ui/plan-structure.d.ts +12 -2
  166. package/dist/commands/ui/plan-structure.en.d.ts +4 -0
  167. package/dist/commands/ui/plan-structure.en.js +4 -0
  168. package/dist/commands/ui/plan-structure.es.d.ts +4 -0
  169. package/dist/commands/ui/plan-structure.es.js +4 -0
  170. package/dist/commands/ui/plan-structure.js +48 -14
  171. package/dist/commands/ui/prototype-comp-route.d.ts +7 -0
  172. package/dist/commands/ui/prototype-comp-route.js +109 -0
  173. package/dist/commands/ui/prototype-main.d.ts +3 -1
  174. package/dist/commands/ui/prototype-scenes-child.js +6 -1
  175. package/dist/commands/ui/prototype-scenes-read.d.ts +1 -0
  176. package/dist/commands/ui/prototype-scenes-route.js +7 -1
  177. package/dist/commands/ui/prototype-snapshot-session.d.ts +1 -1
  178. package/dist/commands/ui/prototype-snapshot-session.js +3 -0
  179. package/dist/commands/ui/prototype-snapshot.d.ts +1 -1
  180. package/dist/commands/ui/routes.d.ts +6 -3
  181. package/dist/commands/ui/routes.js +3 -3
  182. package/dist/commands/ui/save-commit.js +6 -2
  183. package/dist/commands/ui/save-publish.js +3 -0
  184. package/dist/commands/ui/server-options.js +2 -0
  185. package/dist/commands/ui/server.d.ts +12 -22
  186. package/dist/commands/ui/server.js +10 -48
  187. package/dist/commands/ui/snapshot-runners.d.ts +22 -0
  188. package/dist/commands/ui/snapshot-runners.js +45 -0
  189. package/dist/commands/ui/structure-surface.d.ts +6 -0
  190. package/dist/commands/ui/structure-surface.js +94 -0
  191. package/dist/commands/ui/studio-routes.d.ts +1 -0
  192. package/dist/commands/ui/studio-routes.js +5 -0
  193. package/dist/commands/ui/studio-state.d.ts +9 -4
  194. package/dist/commands/ui/studio-state.js +1 -0
  195. package/dist/commands/ui/studio-versions.d.ts +3 -3
  196. package/dist/commands/ui/studio.en.d.ts +13 -0
  197. package/dist/commands/ui/studio.en.js +13 -0
  198. package/dist/commands/ui/studio.es.d.ts +13 -0
  199. package/dist/commands/ui/studio.es.js +13 -0
  200. package/dist/commands/ui/theme-option.d.ts +8 -0
  201. package/dist/commands/ui/theme-option.js +40 -0
  202. package/dist/commands/ui/theme-values.d.ts +5 -0
  203. package/dist/commands/ui/theme-values.js +113 -0
  204. package/dist/ui/page.js +94 -94
  205. package/docs/PROCESS.md +5 -0
  206. package/docs/PROTOTYPE.md +24 -1
  207. package/docs/WORKBENCH.md +76 -22
  208. package/package.json +11 -11
  209. package/skills/ape-critique/SKILL.md +16 -6
  210. package/skills/ape-design-system/SKILL.md +4 -3
  211. package/skills/ape-plan-change/SKILL.md +7 -3
  212. package/skills/ape-prototype/SKILL.md +12 -1
  213. package/templates/example/apps/app/src/i18n/en.ts +2 -0
  214. package/templates/example/apps/app/src/i18n/es.json +2 -0
  215. package/templates/product/apps/admin/src/fonts.ts +2 -1
  216. package/templates/product/apps/app/src/fonts.ts +5 -1
  217. package/templates/product/apps/app/src/i18n/en.ts +2 -0
  218. package/templates/product/apps/app/src/i18n/es.json +2 -0
  219. package/templates/product/prototype/journeys.ts +3 -0
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The commands a part hands to another shell: `sh -c '…'`, `bash -lc "…"`, `cmd /c …`,
3
+ * `powershell -Command …` (or `-EncodedCommand`, or a bare command), `pwsh -c …`, `eval …` and
4
+ * `iex …` (`Invoke-Expression`),
5
+ * found anywhere in the part, so `pnpm exec sh -c "…"` and `env X=1 bash -c …` count too. The
6
+ * limits check each one with the same rules (limits.ts). Plain Node only: the hook runs it.
7
+ */
8
+ import { programName } from './command-parts.js';
9
+ export const POSIX = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash', 'fish']);
10
+ export const POWERSHELL = new Set(['powershell', 'pwsh']);
11
+ // PowerShell options that take a value, by their shortest accepted names.
12
+ const VALUED = [
13
+ 'executionpolicy',
14
+ 'ep',
15
+ 'windowstyle',
16
+ 'workingdirectory',
17
+ 'wd',
18
+ 'configurationname',
19
+ 'outputformat',
20
+ 'inputformat',
21
+ 'settingsfile',
22
+ 'custompipename',
23
+ 'psconsolefile',
24
+ 'version',
25
+ ];
26
+ /** `sh`'s script: the first word after its options, when one of them is `-c` (`-lc`, `-ec`…). */
27
+ export function posixScript(words, from) {
28
+ let command = false;
29
+ for (let index = from; index < words.length; index++) {
30
+ const word = words[index];
31
+ if (/^[-+][oO]$/.test(word))
32
+ index++;
33
+ else if (/^-[A-Za-z]*c[A-Za-z]*$/.test(word))
34
+ command = true;
35
+ else if (!/^[-+]/.test(word))
36
+ return command ? word : undefined;
37
+ }
38
+ }
39
+ const decoded = (text) => {
40
+ try {
41
+ return text ? Buffer.from(text, 'base64').toString('utf16le') : undefined;
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ };
47
+ /** PowerShell's command: after `-Command` (or any prefix), `-EncodedCommand`, or bare words. */
48
+ export function powershellScript(words, from) {
49
+ for (let index = from; index < words.length; index++) {
50
+ const word = words[index];
51
+ if (!/^[-/]/.test(word))
52
+ return words.slice(index).join(' ');
53
+ const name = word.replace(/^[-/]+/, '').toLowerCase();
54
+ if (!name)
55
+ return words.slice(index + 1).join(' ');
56
+ if ('command'.startsWith(name))
57
+ return words.slice(index + 1).join(' ');
58
+ if (name === 'e' || name === 'ec' || (name.length > 1 && 'encodedcommand'.startsWith(name)))
59
+ return decoded(words[index + 1]);
60
+ if ('file'.startsWith(name))
61
+ return undefined;
62
+ if (VALUED.some((option) => option.startsWith(name) && name.length > 1))
63
+ index++;
64
+ }
65
+ }
66
+ export const EXPRESSIONS = new Set(['iex', 'invoke-expression']);
67
+ /** Every script the part's words hand to another shell; past `cap` of them, one more and stop. */
68
+ export function wrappedScripts(words, cap = Number.POSITIVE_INFINITY) {
69
+ const found = [];
70
+ for (let index = 0; index < words.length && found.length <= cap; index++) {
71
+ const name = programName(words[index]);
72
+ let script;
73
+ let shell = 'bash';
74
+ if (POSIX.has(name))
75
+ script = posixScript(words, index + 1);
76
+ else if (name === 'eval')
77
+ script = words.slice(index + 1).join(' ');
78
+ else if (EXPRESSIONS.has(name)) {
79
+ script = words
80
+ .slice(index + 1)
81
+ .filter((value) => !/^-command$/i.test(value))
82
+ .join(' ');
83
+ shell = 'powershell';
84
+ }
85
+ else if (name === 'cmd') {
86
+ const flag = words.findIndex((value, at) => at > index && /^\/[ck]$/i.test(value));
87
+ if (flag > 0) {
88
+ script = words.slice(flag + 1).join(' ');
89
+ shell = 'cmd';
90
+ }
91
+ }
92
+ else if (POWERSHELL.has(name)) {
93
+ script = powershellScript(words, index + 1);
94
+ shell = 'powershell';
95
+ }
96
+ if (script?.trim())
97
+ found.push({ script, shell });
98
+ }
99
+ return found;
100
+ }
@@ -0,0 +1 @@
1
+ export declare function designDelete(command: string, cwd: string): boolean;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Design turns may delete files inside `design/` and `prototype/` without asking: a single
3
+ * delete command, alone, whose every path stays below one of those folders. The approval record
4
+ * (`prototype/versions`) is never one of them, and neither is either folder as a whole.
5
+ */
6
+ import { isAbsolute, relative, resolve } from 'node:path';
7
+ import { commandParts, partWords, programName } from './command-parts.js';
8
+ const DELETES = new Set(['rm', 'del', 'erase', 'ri', 'remove-item', 'rmdir']);
9
+ const OPTION = /^-(?:[rRfv]+|-recursive|-force|recurse|force)$/i;
10
+ const GLOB = /[*?[\]]/;
11
+ function deletable(word, cwd) {
12
+ if (/[$`{}~%!]/.test(word))
13
+ return false;
14
+ const path = relative(cwd, resolve(cwd, word));
15
+ if (!path || isAbsolute(path))
16
+ return false;
17
+ const parts = path.split(/[\\/]+/);
18
+ const [top, second] = parts;
19
+ if (parts.includes('..') || parts.length < 2 || !top || !second)
20
+ return false;
21
+ if (top !== 'design' && top !== 'prototype')
22
+ return false;
23
+ // The first two names are literal, so a pattern can never reach the approval record.
24
+ if (GLOB.test(top) || GLOB.test(second))
25
+ return false;
26
+ return !(top === 'prototype' && second.toLowerCase() === 'versions');
27
+ }
28
+ export function designDelete(command, cwd) {
29
+ const parts = commandParts(command);
30
+ if (parts.length !== 1)
31
+ return false;
32
+ const [program, ...rest] = partWords(parts[0]);
33
+ if (!program || !DELETES.has(programName(program)) || program !== program.trim())
34
+ return false;
35
+ const paths = rest.filter((word) => !OPTION.test(word));
36
+ if (rest.some((word) => word.startsWith('-') && !OPTION.test(word)))
37
+ return false;
38
+ return paths.length > 0 && paths.every((word) => deletable(word, cwd));
39
+ }
@@ -0,0 +1,28 @@
1
+ import { type AgentsFile } from '@buffcore/contracts/workbench';
2
+ import type { Start, stopTree } from '../runner.ts';
3
+ import type { FreshStore } from './fresh-store.ts';
4
+ export interface CritiqueSource {
5
+ change?: string;
6
+ checkout: string;
7
+ }
8
+ export declare class CritiqueTurns {
9
+ private run?;
10
+ private queued?;
11
+ private closed;
12
+ private readonly root;
13
+ private readonly start;
14
+ private readonly stop;
15
+ private readonly store;
16
+ private readonly settings;
17
+ constructor(root: string, start: Start, stop: typeof stopTree, store: FreshStore, settings: () => AgentsFile | undefined);
18
+ /** A Prototype turn ended: a passing full snapshot it took itself (since it began) starts one. */
19
+ afterTurn(startedAt: number): Promise<void>;
20
+ /** A full snapshot passed: start its critique, or queue it behind the one running. */
21
+ after(source: CritiqueSource, report?: string): boolean;
22
+ private agent;
23
+ private begin;
24
+ running(): boolean;
25
+ close(): void;
26
+ }
27
+ /** A record that cannot be written never fails the turn that started it. */
28
+ export declare function keep(write: () => void): boolean;
@@ -0,0 +1,121 @@
1
+ // The critique as its own turn (0.8.43): after a passing full snapshot (taken from the Prototype
2
+ // page, or by the Prototype step's agent during its turn) a fresh, read-only turn reads it and the
3
+ // studio writes design/critique.md from its answer. One at a time, one queued, and never twice for
4
+ // the same report in the same checkout.
5
+ import { mkdirSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { CRITIQUE_FILE } from '@buffcore/contracts/workbench';
8
+ import { factsChanged } from '../merge-events.js';
9
+ import { runFresh, stopFresh } from './fresh-launch.js';
10
+ import { critiquePrompt, critiqueText } from './fresh-prompts.js';
11
+ import { passingFullReport } from './fresh-report.js';
12
+ import { plainPath } from './store.js';
13
+ const REPORT = /^prototype\/snapshots\/[a-f0-9]{7,64}$/;
14
+ const keyOf = ({ source, report }) => (report ? `${source.checkout}|${report}` : '');
15
+ export class CritiqueTurns {
16
+ run;
17
+ queued;
18
+ closed = false;
19
+ root;
20
+ start;
21
+ stop;
22
+ store;
23
+ settings;
24
+ constructor(root, start, stop, store, settings) {
25
+ this.root = root;
26
+ this.start = start;
27
+ this.stop = stop;
28
+ this.store = store;
29
+ this.settings = settings;
30
+ }
31
+ /** A Prototype turn ended: a passing full snapshot it took itself (since it began) starts one. */
32
+ async afterTurn(startedAt) {
33
+ const report = await passingFullReport(this.root, startedAt).catch(() => undefined);
34
+ if (report)
35
+ this.after({ checkout: this.root }, report);
36
+ }
37
+ /** A full snapshot passed: start its critique, or queue it behind the one running. */
38
+ after(source, report) {
39
+ const pending = { source, ...(report && REPORT.test(report) ? { report } : {}) };
40
+ const key = keyOf(pending);
41
+ if (this.closed || (key && (this.store.critiqued(key) || this.run?.key === key)))
42
+ return false;
43
+ if (this.agent() !== 'claude')
44
+ return false;
45
+ if (this.run) {
46
+ this.queued = pending;
47
+ return false;
48
+ }
49
+ this.begin(pending, key);
50
+ return true;
51
+ }
52
+ agent() {
53
+ const settings = this.settings();
54
+ return settings?.work.validation ?? settings?.default ?? 'claude';
55
+ }
56
+ begin(pending, key) {
57
+ const settings = this.settings();
58
+ const choice = {
59
+ ...(settings?.model?.validation ? { model: settings.model.validation } : {}),
60
+ ...(settings?.effort?.validation ? { effort: settings.effort.validation } : {}),
61
+ };
62
+ const { source, report } = pending;
63
+ const record = {
64
+ agent: 'claude',
65
+ at: new Date().toISOString(),
66
+ ...(source.change ? { change: source.change } : {}),
67
+ ...(report ? { report } : {}),
68
+ };
69
+ keep(() => this.store.saveCritique({ ...record, state: 'running' }));
70
+ const folder = source.checkout;
71
+ const prompt = critiquePrompt(report);
72
+ const run = runFresh(this.start, { folder, prompt, checks: true, ...choice });
73
+ this.run = { ...run, key };
74
+ void run.result.then(({ text, seconds }) => {
75
+ this.run = undefined;
76
+ if (this.closed)
77
+ return;
78
+ const body = text === undefined ? undefined : critiqueText(text);
79
+ const written = !!body && keep(() => writeCritique(folder, body));
80
+ if (written && key)
81
+ keep(() => this.store.markCritiqued(key));
82
+ keep(() => this.store.saveCritique({
83
+ ...record,
84
+ seconds,
85
+ state: written ? 'done' : 'failed',
86
+ ...(written ? { file: CRITIQUE_FILE } : {}),
87
+ }));
88
+ if (written)
89
+ factsChanged('unsaved');
90
+ const next = this.queued;
91
+ this.queued = undefined;
92
+ if (next)
93
+ this.after(next.source, next.report);
94
+ });
95
+ }
96
+ running() {
97
+ return !!this.run;
98
+ }
99
+ close() {
100
+ this.closed = true;
101
+ this.queued = undefined;
102
+ if (this.run)
103
+ stopFresh(this.run, this.stop);
104
+ }
105
+ }
106
+ /** A record that cannot be written never fails the turn that started it. */
107
+ export function keep(write) {
108
+ try {
109
+ write();
110
+ return true;
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }
116
+ /** The studio writes the critique; the agent's turn wrote nothing. Never through a link. */
117
+ function writeCritique(folder, body) {
118
+ const design = plainPath(join(folder, 'design'));
119
+ mkdirSync(design, { recursive: true });
120
+ writeFileSync(plainPath(join(design, 'critique.md')), body);
121
+ }
@@ -0,0 +1,31 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ import type { AgentEffort } from '@buffcore/contracts/workbench';
3
+ import type { Start } from '../runner.ts';
4
+ import { stopTree } from '../runner.ts';
5
+ export interface FreshLaunch {
6
+ /** The product folder the turn reads. */
7
+ folder: string;
8
+ prompt: string;
9
+ model?: string;
10
+ effort?: AgentEffort;
11
+ /** The critique may run the design and i18n checks; the review runs nothing. */
12
+ checks?: boolean;
13
+ /** The person's home, whose Claude settings give their denies and sign-in (tests set it). */
14
+ home?: string;
15
+ }
16
+ export interface FreshResult {
17
+ /** The agent's final answer; absent when the turn failed. */
18
+ text?: string;
19
+ seconds: number;
20
+ }
21
+ /** The read-only arguments for one fresh Claude turn. */
22
+ export declare function freshArgs(launch: FreshLaunch, settings: string): string[];
23
+ /** A running fresh turn: its child, to stop it, and its result. */
24
+ export interface FreshRun {
25
+ child?: ChildProcess;
26
+ result: Promise<FreshResult>;
27
+ }
28
+ /** Start one fresh turn; its result never rejects (a failure has no text). */
29
+ export declare function runFresh(start: Start, launch: FreshLaunch): FreshRun;
30
+ /** Stop a fresh turn's process tree. */
31
+ export declare function stopFresh(run: FreshRun, stop?: typeof stopTree): void;
@@ -0,0 +1,122 @@
1
+ import { stopTree } from '../runner.js';
2
+ import { stdinInput } from './attachments.js';
3
+ import { secretReads } from './claude-permissions.js';
4
+ import { AGENT_DEFS } from './defs.js';
5
+ import { openFreshSettings, settingDenies } from './fresh-settings.js';
6
+ import { scrubLaunchIds } from './launch-ids.js';
7
+ import { claudeAdapter } from './parse-claude.js';
8
+ import { COMMENT_PATH } from './permissions.js';
9
+ import { PLANNING_LIMITS } from './planning-limits.js';
10
+ import { jsonLine } from './prompt.js';
11
+ import { launchArguments } from './turn-guard.js';
12
+ import { turnOverrides } from './turn-overrides.js';
13
+ /**
14
+ * Checks the critique may run, exactly as written: no prefix rule, so no added argument or
15
+ * redirection to a file matches. The review runs none.
16
+ */
17
+ const CRITIQUE_CHECKS = ['pnpm ape design check', 'pnpm ape i18n check'];
18
+ /** Every tool that writes, runs or reaches out, or starts another agent; reads stay. */
19
+ const WRITES = ['Edit', 'Write', 'NotebookEdit', 'WebFetch', 'WebSearch', 'Task', 'Agent'];
20
+ /** The read-only arguments for one fresh Claude turn. */
21
+ export function freshArgs(launch, settings) {
22
+ const turn = AGENT_DEFS.find((def) => def.id === 'claude')?.turn;
23
+ if (!turn)
24
+ throw new Error('claude has no headless turn');
25
+ const checks = launch.checks
26
+ ? CRITIQUE_CHECKS.flatMap((command) => [`Bash(${command})`, `PowerShell(${command})`])
27
+ : [];
28
+ return [
29
+ ...turn.start,
30
+ '--permission-mode',
31
+ 'dontAsk',
32
+ // No user, project or local settings: their allow rules could widen what dontAsk runs.
33
+ '--setting-sources=',
34
+ '--settings',
35
+ settings,
36
+ '--allowedTools',
37
+ 'Read',
38
+ 'Glob',
39
+ 'Grep',
40
+ ...checks,
41
+ '--disallowedTools',
42
+ ...WRITES,
43
+ ...(launch.checks ? [] : ['Bash', 'PowerShell']),
44
+ `Read(//**/${COMMENT_PATH}/**)`,
45
+ ...secretReads(launch.folder),
46
+ ...PLANNING_LIMITS,
47
+ ...settingDenies(launch.folder, launch.home),
48
+ ...turnOverrides('claude', { model: launch.model, effort: launch.effort }).args,
49
+ ...turn.stdin,
50
+ ];
51
+ }
52
+ /** Start one fresh turn; its result never rejects (a failure has no text). */
53
+ export function runFresh(start, launch) {
54
+ const started = Date.now();
55
+ const seconds = () => Math.max(0, Math.floor((Date.now() - started) / 1000));
56
+ const settings = openFreshSettings(launch.home);
57
+ const args = freshArgs(launch, settings.value);
58
+ const allowed = launchArguments(args);
59
+ const release = () => {
60
+ allowed();
61
+ settings.close();
62
+ };
63
+ let child;
64
+ try {
65
+ child = start({ program: 'pnpm', args: ['exec', 'claude', ...args], json: true }, launch.folder);
66
+ }
67
+ catch {
68
+ release();
69
+ return { result: Promise.resolve({ seconds: seconds() }) };
70
+ }
71
+ const result = new Promise((done) => {
72
+ const adapter = claudeAdapter();
73
+ let pending = '';
74
+ let answer;
75
+ let last;
76
+ let failed = false;
77
+ const line = (text) => {
78
+ const record = jsonLine(text);
79
+ if (record.type === 'result') {
80
+ if (record.is_error === true || record.subtype !== 'success')
81
+ failed = true;
82
+ else if (typeof record.result === 'string')
83
+ answer = record.result;
84
+ }
85
+ for (const event of adapter.parse(text)) {
86
+ if (event.kind === 'text')
87
+ last = event.text;
88
+ if (event.kind === 'error')
89
+ failed = true;
90
+ }
91
+ };
92
+ child.stdout?.setEncoding('utf8');
93
+ child.stdout?.on('data', (chunk) => {
94
+ const lines = (pending + chunk).split('\n');
95
+ pending = lines.pop() ?? '';
96
+ for (const text of lines)
97
+ if (text.trim())
98
+ line(text);
99
+ });
100
+ let ended = false;
101
+ const end = (code) => {
102
+ if (ended)
103
+ return;
104
+ ended = true;
105
+ release();
106
+ if (pending.trim())
107
+ line(pending);
108
+ const text = failed || code !== 0 ? undefined : (answer ?? last);
109
+ done({ ...(text?.trim() ? { text: scrubLaunchIds(text) } : {}), seconds: seconds() });
110
+ };
111
+ child.once('error', () => end(1));
112
+ child.once('close', (code) => end(code));
113
+ });
114
+ child.stdin?.on('error', () => { });
115
+ child.stdin?.end(stdinInput('claude', launch.prompt, []));
116
+ return { child, result };
117
+ }
118
+ /** Stop a fresh turn's process tree. */
119
+ export function stopFresh(run, stop = stopTree) {
120
+ if (run.child)
121
+ stop(run.child, true);
122
+ }
@@ -0,0 +1,17 @@
1
+ import { type Chat, type ReviewStep } from '@buffcore/contracts/workbench';
2
+ /** A review step whose turn just wrote one of its own files, by the turn's own edit calls. */
3
+ export declare function reviewStepOf(chat: Chat, firstMessage: number): ReviewStep | undefined;
4
+ /** The step's last recorded model and effort, as its own turn asked for them. */
5
+ export declare function stepChoice(chat: Chat): {
6
+ model?: string | undefined;
7
+ effort?: "high" | "low" | "max" | "medium" | "xhigh" | undefined;
8
+ };
9
+ export declare function reviewPrompt(step: ReviewStep): string;
10
+ export declare function critiquePrompt(report: string | undefined): string;
11
+ /** The findings in a reviewer's answer: one JSON object, perhaps fenced; else none. */
12
+ export declare function parseFindings(text: string): string[] | undefined;
13
+ /**
14
+ * The critique's Markdown, without a fence the agent may have wrapped it in; none unless it has
15
+ * the skill's shape (a reply such as "I couldn't write the file" is not a critique).
16
+ */
17
+ export declare function critiqueText(text: string): string | undefined;
@@ -0,0 +1,76 @@
1
+ // What a fresh turn is asked, and how its answer is read: the review's findings (at most seven, one
2
+ // sentence each; anything malformed is dropped quietly) and the critique's Markdown.
3
+ import { FINDING_LENGTH, MAX_FINDINGS, REVIEW_STEPS, stepOwnsFile, stepSaveFiles, } from '@buffcore/contracts/workbench';
4
+ import { createI18n, matchLocale } from '@buffcore/i18n';
5
+ import { en } from './fresh.en.js';
6
+ import { es } from './fresh.es.js';
7
+ import { isPlanning } from './permissions.js';
8
+ import { writtenFiles } from './turn-scenes.js';
9
+ const messages = createI18n({ catalogs: [{ en, es }] });
10
+ const t = (key, values) => messages.t(matchLocale((process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || 'en')
11
+ .replace('_', '-')
12
+ .split('.')[0], messages.locales), key, values);
13
+ /** A review step whose turn just wrote one of its own files, by the turn's own edit calls. */
14
+ export function reviewStepOf(chat, firstMessage) {
15
+ const step = REVIEW_STEPS.find((name) => name === chat.page);
16
+ if (!step || chat.change || !isPlanning(chat.work) || chat.title !== step)
17
+ return;
18
+ const written = [...writtenFiles(chat, firstMessage)];
19
+ return written.some((file) => stepOwnsFile(step, file)) ? step : undefined;
20
+ }
21
+ /** The step's last recorded model and effort, as its own turn asked for them. */
22
+ export function stepChoice(chat) {
23
+ const turn = chat.messages.findLast((message) => message.turn)?.turn;
24
+ const model = turn?.model.requested ?? undefined;
25
+ const effort = turn?.effort.requested ?? undefined;
26
+ return {
27
+ ...(model && model !== 'auto' ? { model } : {}),
28
+ ...(effort && effort !== 'auto' ? { effort } : {}),
29
+ };
30
+ }
31
+ const files = (steps) => steps.flatMap((step) => stepSaveFiles[step]).join(', ') || t('fresh.none');
32
+ export function reviewPrompt(step) {
33
+ const earlier = REVIEW_STEPS.slice(0, REVIEW_STEPS.indexOf(step));
34
+ const shape = JSON.stringify({ findings: [t('fresh.example')] });
35
+ return `${t('fresh.review', { step, files: files([step]), earlier: files(earlier) })}\n${shape}\n${t('fresh.reviewLimit')}\n`;
36
+ }
37
+ export function critiquePrompt(report) {
38
+ return `${t('fresh.critique', { report: report ? `${report}/report.json` : 'prototype/snapshots/' })}\n`;
39
+ }
40
+ /** The findings in a reviewer's answer: one JSON object, perhaps fenced; else none. */
41
+ export function parseFindings(text) {
42
+ const start = text.indexOf('{');
43
+ const end = text.lastIndexOf('}');
44
+ if (start < 0 || end <= start)
45
+ return;
46
+ let value;
47
+ try {
48
+ value = JSON.parse(text.slice(start, end + 1));
49
+ }
50
+ catch {
51
+ return;
52
+ }
53
+ const list = value?.findings;
54
+ if (!Array.isArray(list))
55
+ return;
56
+ const findings = list
57
+ .filter((item) => typeof item === 'string')
58
+ .map((item) => item.replace(/\s+/g, ' ').trim())
59
+ .filter((item) => item.length > 0 && item.length <= FINDING_LENGTH)
60
+ .slice(0, MAX_FINDINGS);
61
+ // Findings that were all malformed are no answer, never a clean read.
62
+ return list.length && !findings.length ? undefined : findings;
63
+ }
64
+ /** The report's shape in the ape-critique skill: its title and the sections it always has. */
65
+ const CRITIQUE_SECTIONS = [/^## Scores\b/m, /^## Keep\b/m, /^## Fix\b/m];
66
+ /**
67
+ * The critique's Markdown, without a fence the agent may have wrapped it in; none unless it has
68
+ * the skill's shape (a reply such as "I couldn't write the file" is not a critique).
69
+ */
70
+ export function critiqueText(text) {
71
+ const fenced = /^```(?:markdown|md)?\r?\n([\s\S]*?)\r?\n```\s*$/.exec(text.trim());
72
+ const body = (fenced?.[1] ?? text).trim();
73
+ if (!/^# Critique\b/.test(body) || !CRITIQUE_SECTIONS.every((section) => section.test(body)))
74
+ return;
75
+ return `${body.slice(0, 200_000)}\n`;
76
+ }
@@ -0,0 +1,8 @@
1
+ import type { Chat } from '@buffcore/contracts/workbench';
2
+ /** A Prototype step's own chat: its turns draw the scenes and take the snapshots. */
3
+ export declare const prototypeTurn: (chat: Chat) => boolean;
4
+ /**
5
+ * The newest report's folder (`prototype/snapshots/<commit>`) when it is full, passed and was
6
+ * written at or after `since` (the turn's start): a report the turn never took does not count.
7
+ */
8
+ export declare function passingFullReport(root: string, since: number): Promise<string | undefined>;
@@ -0,0 +1,36 @@
1
+ // The snapshot a Prototype turn's own `ape prototype snapshot` wrote: the newest report under
2
+ // prototype/snapshots/, read only. A full one (no scene filter) with no problems passed.
3
+ import { readdir, readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ const isReport = (value) => {
6
+ const report = value;
7
+ return (typeof report?.commit === 'string' &&
8
+ /^[a-f0-9]{7,64}$/.test(report.commit) &&
9
+ typeof report.createdAt === 'string' &&
10
+ Array.isArray(report.problems));
11
+ };
12
+ /** A Prototype step's own chat: its turns draw the scenes and take the snapshots. */
13
+ export const prototypeTurn = (chat) => chat.page === 'prototype' && chat.title === 'prototype' && chat.work === 'design';
14
+ /**
15
+ * The newest report's folder (`prototype/snapshots/<commit>`) when it is full, passed and was
16
+ * written at or after `since` (the turn's start): a report the turn never took does not count.
17
+ */
18
+ export async function passingFullReport(root, since) {
19
+ const dir = join(root, 'prototype', 'snapshots');
20
+ const folders = await readdir(dir, { withFileTypes: true }).catch(() => []);
21
+ const reports = await Promise.all(folders
22
+ .filter((folder) => folder.isDirectory() && !folder.isSymbolicLink())
23
+ .map((folder) => readFile(join(dir, folder.name, 'report.json'), 'utf8').then((text) => {
24
+ const report = JSON.parse(text);
25
+ return isReport(report) && report.commit === folder.name ? report : undefined;
26
+ }, () => undefined)));
27
+ const newest = reports
28
+ .filter((report) => report !== undefined)
29
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
30
+ if (!newest || newest.scene !== undefined || newest.problems.length)
31
+ return;
32
+ const created = Date.parse(newest.createdAt);
33
+ if (!(created >= since))
34
+ return;
35
+ return `prototype/snapshots/${newest.commit}`;
36
+ }
@@ -0,0 +1,3 @@
1
+ import type { UiRoute } from '../routes.ts';
2
+ import type { FreshLooks } from './fresh.ts';
3
+ export declare function freshRoutes(fresh: FreshLooks, root: string): UiRoute[];
@@ -0,0 +1,64 @@
1
+ // The fresh turns' routes: read a step's review or the critique, Take or Leave a finding, and the
2
+ // review's setting (Settings › Agents), kept in plan/agents.md with the other agent settings.
3
+ import { freshAnswerBody, freshReplySchema, freshStepSchema, reviewSettingBody, } from '@buffcore/contracts/workbench';
4
+ import { readAgentsFile, writeAgentsFile } from '../../agents-file.js';
5
+ import { queueAgentsWrite } from '../agents-route.js';
6
+ import { factsChanged } from '../merge-events.js';
7
+ import { t } from './prompt.js';
8
+ const invalid = { status: 400, body: { error: t('chat.invalid') } };
9
+ async function saveSetting(root, on) {
10
+ const before = (await readAgentsFile(root)) ?? {
11
+ default: 'claude',
12
+ work: {},
13
+ level: 'guide',
14
+ };
15
+ const { review: _old, ...rest } = before;
16
+ if ((before.review !== false) === on)
17
+ return;
18
+ await writeAgentsFile(root, on ? rest : { ...rest, review: false });
19
+ factsChanged('levels', 'unsaved');
20
+ }
21
+ export function freshRoutes(fresh, root) {
22
+ return [
23
+ {
24
+ method: 'GET',
25
+ path: '/api/fresh/:step',
26
+ right: 'read:chats',
27
+ handle: ({ params }) => {
28
+ const step = freshStepSchema.safeParse(params.step);
29
+ if (!step.success)
30
+ return invalid;
31
+ return { status: 200, body: freshReplySchema.parse(fresh.read(step.data)) };
32
+ },
33
+ },
34
+ {
35
+ method: 'POST',
36
+ path: '/api/fresh/:step/answer',
37
+ right: 'build',
38
+ origin: true,
39
+ handle: async ({ params, body }) => {
40
+ const step = freshStepSchema.safeParse(params.step);
41
+ const answer = freshAnswerBody.safeParse(await body().catch(() => undefined));
42
+ if (!step.success || step.data === 'prototype' || !answer.success)
43
+ return invalid;
44
+ const { id, answer: choice } = answer.data;
45
+ return fresh.answer(step.data, id, choice)
46
+ ? { status: 200, body: { ok: true } }
47
+ : { status: 404, body: { error: t('chat.missing') } };
48
+ },
49
+ },
50
+ {
51
+ method: 'POST',
52
+ path: '/api/agents/review',
53
+ right: 'settings',
54
+ origin: true,
55
+ handle: async ({ body }) => {
56
+ const setting = reviewSettingBody.safeParse(await body().catch(() => undefined));
57
+ if (!setting.success)
58
+ return invalid;
59
+ await queueAgentsWrite(root, () => saveSetting(root, setting.data.on));
60
+ return { status: 202, body: { ok: true } };
61
+ },
62
+ },
63
+ ];
64
+ }