gcf-aif-ext 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,292 @@
1
+ // The operator's commit from the Changes screen (Board-PRD decision 50, docs/Round11-Plan.md): the
2
+ // files they ticked with their own message, in the main checkout. Not `commitMove`: its rollback
3
+ // rewrites the files it read, so a save during a slow hook would go, and it always takes INDEX.md,
4
+ // so a commit of code alone would enter the gate. The working tree is never written, but INDEX.md
5
+ // when gcf/ is committed; on a refusal the index and INDEX.md are as they were.
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { rowsToCommit } from './changes.js';
11
+ import {
12
+ commitOnly,
13
+ dirtyGcf,
14
+ dirtyRefusal,
15
+ inParts,
16
+ literal,
17
+ moveTrailers,
18
+ operationInProgress,
19
+ } from './git.js';
20
+ import { writeIndex } from './index-gen.js';
21
+ import { MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
22
+ import { refusal } from './refusal.js';
23
+ import { onWorkBranch } from './unit-ops.js';
24
+
25
+ const INDEX = 'gcf/INDEX.md';
26
+ // The ids a commit touches, as `gcf edits commit` finds them: item history reads them.
27
+ const ITEM_PATH = /^gcf\/work\/([^/]+?)(?:\.md$|\/)/;
28
+ const UNFIT = ['nested repository', 'not a regular file'];
29
+
30
+ /** Whether the commit gate reads `p` (GATE_SCOPE in git.js). */
31
+ const inGate = (p) =>
32
+ p === 'GLOSSARY.md' ||
33
+ (p.startsWith('gcf/') &&
34
+ !p.startsWith('gcf/.metrics/') &&
35
+ !/^gcf\/source\/[^/]+\.import\.json$/.test(p));
36
+
37
+ const git = (dir, args, opts = {}) =>
38
+ spawnSync('git', ['-c', 'core.quotePath=false', ...args], {
39
+ cwd: dir,
40
+ encoding: 'utf8',
41
+ ...opts,
42
+ });
43
+
44
+ const nul = (dir, paths) => paths.map((p) => `${literal(dir, p)}\0`).join('');
45
+
46
+ /** A commit needs a branch to land on: an unborn one is one, a detached HEAD is not. */
47
+ function refuseWhereNoCommitBelongs(dir, subject) {
48
+ if (onWorkBranch(dir))
49
+ throw new Error(`cannot record ${subject} on a work/ branch: a run commits its own work`);
50
+ const busy = operationInProgress(dir);
51
+ if (busy) throw new Error(`cannot record ${subject} while ${busy} is in progress`);
52
+ if (git(dir, ['symbolic-ref', '-q', 'HEAD']).status !== 0)
53
+ throw new Error(`cannot record ${subject} on a detached HEAD: check out a branch first`);
54
+ if (runHolder(dir, MAIN_RUN))
55
+ throw refusal('running', {}, `cannot record ${subject}: a run writes in the main checkout`);
56
+ }
57
+
58
+ /** A staged rename only: the index holds the old file's text under the new name. */
59
+ const onlyMoved = (dir, r) =>
60
+ r.xy[0] === 'R' &&
61
+ git(dir, ['rev-parse', `:./${r.path}`]).stdout ===
62
+ git(dir, ['rev-parse', `HEAD:./${r.from}`]).stdout;
63
+
64
+ /**
65
+ * What the disk would overwrite: `--only` takes the disk, so a text staged and changed again
66
+ * would go without a trace, and a file out of the index by `rm --cached` would come back.
67
+ */
68
+ function stagedAway(dir, base, rows) {
69
+ const out = git(dir, [
70
+ 'diff',
71
+ '--cached',
72
+ '--no-renames',
73
+ '--diff-filter=D',
74
+ '--name-only',
75
+ '-z',
76
+ '--relative',
77
+ base,
78
+ ]);
79
+ const removed = new Set(out.stdout.split('\0'));
80
+
81
+ return rows.filter((r) =>
82
+ r.status === 'untracked'
83
+ ? removed.has(r.path)
84
+ : r.xy && !r.xy.includes('.') && !onlyMoved(dir, r),
85
+ );
86
+ }
87
+
88
+ // A whole block, not one line: `=======` alone underlines a Markdown heading.
89
+ const MARKERS = /^<{7}[ \r\n][\s\S]*?^={7}\r?$[\s\S]*?^>{7}[ \r\n]/m;
90
+ const MARKERS_READ = 16 * 1024 * 1024;
91
+
92
+ /** The text of a file on the disk with a conflict's markers in it that the last commit lacks. */
93
+ function newMarkers(dir, r) {
94
+ const file = path.join(dir, r.path);
95
+ if (r.status === 'deleted' || !existsSync(file)) return false;
96
+ const st = lstatSync(file);
97
+ if (!st.isFile() || st.size > MARKERS_READ) return false;
98
+ const bytes = readFileSync(file);
99
+ if (bytes.includes(0) || !MARKERS.test(bytes.toString('latin1'))) return false;
100
+ const old = git(dir, ['show', `HEAD:./${r.from ?? r.path}`]);
101
+
102
+ return !(old.status === 0 && MARKERS.test(old.stdout));
103
+ }
104
+
105
+ /**
106
+ * A return's conflict leaves its markers in a plain modified file: git sees no conflict, and
107
+ * whatever `-diff` says of it, a commit would take them.
108
+ */
109
+ function refuseMarkers(dir, rows, subject) {
110
+ const marked = rows.filter((r) => newMarkers(dir, r)).map((r) => r.path);
111
+ if (marked.length)
112
+ throw refusal(
113
+ 'unfit',
114
+ { paths: marked },
115
+ `cannot record ${subject}: ${marked.join(', ')} still hold conflict markers: resolve them ` +
116
+ 'first; a file meant to hold them goes by Commit with agent',
117
+ );
118
+ }
119
+
120
+ /** Stops before anything is written. */
121
+ function refuseRows(dir, base, rows, subject) {
122
+ const unfit = rows
123
+ .filter((r) => r.status === 'conflict' || UNFIT.includes(r.why))
124
+ .map((r) => r.path);
125
+ if (unfit.length)
126
+ throw refusal(
127
+ 'unfit',
128
+ { paths: unfit },
129
+ `cannot record ${subject}: ${unfit.join(', ')} cannot be committed: resolve a conflict ` +
130
+ 'first; a nested repository or anything but a file stays out',
131
+ );
132
+ refuseMarkers(dir, rows, subject);
133
+ // `--only` takes the disk for the old name too: a new file there would ride along, unticked.
134
+ // Only its letters changed: on a disk that ignores case the old name is the new file.
135
+ const reused = rows.filter(
136
+ (r) =>
137
+ r.status === 'renamed' &&
138
+ r.from &&
139
+ r.from.toLowerCase() !== r.path.toLowerCase() &&
140
+ existsSync(path.join(dir, r.from)),
141
+ );
142
+ if (reused.length)
143
+ throw refusal(
144
+ 'staged',
145
+ { paths: reused.map((r) => r.path) },
146
+ `cannot record ${subject}: something new stands at the old name of ` +
147
+ `${reused.map((r) => `${r.from} → ${r.path}`).join(', ')}: commit that first, ` +
148
+ 'or use Commit with agent',
149
+ );
150
+ const staged = stagedAway(dir, base, rows).map((r) => r.path);
151
+ if (staged.length)
152
+ throw refusal(
153
+ 'staged',
154
+ { paths: staged },
155
+ `cannot record ${subject}: ${staged.join(', ')} ha${staged.length === 1 ? 's' : 've'} ` +
156
+ 'staged text the disk does not hold, and this commit takes the disk: `git add` to take ' +
157
+ 'the disk, `git restore --staged` to drop what is staged, or use Commit with agent',
158
+ );
159
+ }
160
+
161
+ /** The gate reads the whole of its scope: its dirty files go together, or not at all. */
162
+ function refuseGateRest(dir, names, subject) {
163
+ const rest = dirtyGcf(dir, [...names.filter(inGate), INDEX]);
164
+ if (rest.length)
165
+ throw dirtyRefusal(
166
+ rest,
167
+ `cannot record ${subject} while gcf/ holds uncommitted changes: ${rest.join(', ')} — ` +
168
+ 'commit or discard them, then try again',
169
+ );
170
+ }
171
+
172
+ /** `git commit -F`, as a message of many lines and a list on stdin share no command line. */
173
+ function commitWith(dir, subject, specs, text) {
174
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'gcf-commit-'));
175
+ const file = path.join(tmp, 'message');
176
+ try {
177
+ writeFileSync(file, text);
178
+
179
+ return commitOnly(dir, subject, specs, ['-F', file, '--cleanup=whitespace']);
180
+ } finally {
181
+ rmSync(tmp, { recursive: true, force: true });
182
+ }
183
+ }
184
+
185
+ /** Stage `add`, commit `all`; `clean` when nothing of it differs from the last commit. */
186
+ function stageAndCommit(dir, { add, all, subject, text }) {
187
+ // No paths: `git add -A` on an empty list takes the whole tree, a staged text's copy too.
188
+ if (add.length) {
189
+ const staged = git(dir, ['add', '-A', '--pathspec-from-file=-', '--pathspec-file-nul'], {
190
+ input: nul(dir, add),
191
+ });
192
+ if (staged.status !== 0) throw new Error(`commit failed: ${staged.stderr.trim()}`);
193
+ }
194
+
195
+ const specs = all.map((p) => literal(dir, p));
196
+ const same = inParts(specs).every(
197
+ (part) => git(dir, ['diff', '--cached', '--quiet', 'HEAD', '--', ...part]).status === 0,
198
+ );
199
+ if (same)
200
+ throw refusal(
201
+ 'clean',
202
+ { paths: all, left: [] },
203
+ `cannot record ${subject}: nothing left to commit in these files`,
204
+ );
205
+
206
+ return commitWith(dir, subject, all, text);
207
+ }
208
+
209
+ /** The index file's bytes, and how to put them back: `git add` of a folder takes more. */
210
+ function indexKeeper(dir) {
211
+ const file = path.resolve(dir, git(dir, ['rev-parse', '--git-path', 'index']).stdout.trim());
212
+ const bytes = existsSync(file) ? readFileSync(file) : null;
213
+ const head = git(dir, ['rev-parse', '-q', '--verify', 'HEAD']).stdout;
214
+
215
+ return () => {
216
+ // Someone committed meanwhile: this index is theirs now.
217
+ if (git(dir, ['rev-parse', '-q', '--verify', 'HEAD']).stdout !== head) return;
218
+ if (bytes) writeFileSync(file, bytes);
219
+ else rmSync(file, { force: true });
220
+ };
221
+ }
222
+
223
+ /** `run` with INDEX.md and the index put back if it throws. */
224
+ async function undoingOnRefusal(dir, gated, run) {
225
+ const index = path.join(dir, INDEX);
226
+ const before = gated && existsSync(index) ? readFileSync(index) : null;
227
+ const putBack = indexKeeper(dir);
228
+ try {
229
+ if (gated) await writeIndex(path.join(dir, 'gcf'));
230
+
231
+ return run();
232
+ } catch (e) {
233
+ putBack();
234
+ if (before) writeFileSync(index, before);
235
+ else if (gated) rmSync(index, { force: true });
236
+ throw e;
237
+ }
238
+ }
239
+
240
+ /** The message as the operator wrote it, and a move's trailers when the commit moves gcf/. */
241
+ function messageOf(message, rows, gated) {
242
+ if (!gated) return message;
243
+ const items = rows.flatMap((r) => ITEM_PATH.exec(r.path)?.[1] ?? []);
244
+ const lines = moveTrailers({ key: 'edits-commit', items })[1];
245
+
246
+ return `${message.trimEnd()}\n\n${lines}\n`;
247
+ }
248
+
249
+ /**
250
+ * Commit these rows of the main checkout with `message`: a rename takes both names, a ticked file
251
+ * gone clean meanwhile drops out. Other staged files stay staged, out of the commit.
252
+ * @param {string} projectDir
253
+ * @param {{message: unknown, paths: unknown}} fields
254
+ */
255
+ export async function commitFiles(projectDir, { message, paths }) {
256
+ const dir = path.resolve(projectDir);
257
+ const subject = typeof message === 'string' ? message.trim().split('\n')[0].trim() : '';
258
+ if (!subject) throw new Error('changes commit: write the message first');
259
+ if (!Array.isArray(paths) || !paths.length || paths.some((p) => typeof p !== 'string'))
260
+ throw new Error('changes commit: name the paths, as `gcf changes` lists them');
261
+
262
+ return withMainLock(dir, async () => {
263
+ refuseWhereNoCommitBelongs(dir, subject);
264
+ const { base, rows } = await rowsToCommit(dir);
265
+ const wanted = new Set(paths);
266
+ const picked = rows.filter((r) => wanted.has(r.path));
267
+ if (!picked.length)
268
+ throw refusal(
269
+ 'clean',
270
+ { paths, left: [] },
271
+ `cannot record ${subject}: nothing left to commit in these files`,
272
+ );
273
+ refuseRows(dir, base, picked, subject);
274
+ const moved = picked.flatMap((r) => (r.status === 'renamed' && r.from ? [r.from] : []));
275
+ const names = [...picked.map((r) => r.path), ...moved];
276
+ const gated = names.some(inGate) && existsSync(path.join(dir, 'gcf'));
277
+ if (gated) refuseGateRest(dir, names, subject);
278
+ const all = [...new Set(gated ? [...names, INDEX] : names)];
279
+ // Neither on disk nor in the index, git add finds nothing by them; `--only` finds them in HEAD.
280
+ const gone = new Set([...moved, ...picked.filter((r) => r.xy?.[0] === 'D').map((r) => r.path)]);
281
+ const text = messageOf(message, picked, gated);
282
+ const hash = await undoingOnRefusal(dir, gated, () =>
283
+ stageAndCommit(dir, { add: all.filter((p) => !gone.has(p)), all, subject, text }),
284
+ );
285
+
286
+ return {
287
+ hash: git(dir, ['rev-parse', '--short', hash]).stdout.trim(),
288
+ subject,
289
+ files: picked.length,
290
+ };
291
+ });
292
+ }
package/lib/config-set.js CHANGED
@@ -106,6 +106,31 @@ export const SETTINGS = [
106
106
  presets: 'effort',
107
107
  label: 'the effort an item or a chat thread without its own runs with (not set: High)',
108
108
  },
109
+ // The plan's outside reviewer (Hold-Plan d17): a read-only audit pass, Claude's when it fails.
110
+ {
111
+ key: 'plan_review.agent',
112
+ kind: 'word',
113
+ label:
114
+ 'the outside reviewer of a plan that keeps finding blocking issues ' +
115
+ '(not set: codex; none: off)',
116
+ },
117
+ {
118
+ key: 'plan_review.model',
119
+ kind: 'word',
120
+ label: 'the model of the plan review (not set: gpt-6-astra)',
121
+ },
122
+ {
123
+ key: 'plan_review.effort',
124
+ kind: 'word',
125
+ label: 'the effort of the plan review (not set: medium)',
126
+ },
127
+ {
128
+ key: 'plan_review.at',
129
+ kind: 'number',
130
+ label:
131
+ 'the improve pass the outside reviewer makes, when the one before found blocking ' +
132
+ 'issues (not set: 3)',
133
+ },
109
134
  {
110
135
  key: 'chat.ask',
111
136
  kind: 'mode',
@@ -224,6 +249,10 @@ const GROUPS = [
224
249
  'agent.model',
225
250
  'agent.effort',
226
251
  'plan_passes',
252
+ 'plan_review.agent',
253
+ 'plan_review.model',
254
+ 'plan_review.effort',
255
+ 'plan_review.at',
227
256
  'dod_attempts',
228
257
  ],
229
258
  ],
package/lib/domain.js CHANGED
@@ -212,6 +212,37 @@ const ITEM_SPECS = {
212
212
  },
213
213
  ],
214
214
  },
215
+ // Planning that does not converge (Hold-Plan d16): the run's stall, the operator's two answers.
216
+ plan_stall: {
217
+ label: 'planning stall',
218
+ help: "The run's stop: the plan's passes keep finding blocking issues past plan_passes",
219
+ args: ['gcf', 'plan', 'stall', '{id}'],
220
+ fields: [
221
+ { key: 'passes', label: 'Blocking findings of each pass', kind: 'text', required: true },
222
+ { key: 'reason', label: 'Reason', kind: 'longtext' },
223
+ ],
224
+ },
225
+ plan_more: {
226
+ label: 'more passes',
227
+ help: 'The plan improves N more passes, then the same check decides',
228
+ args: ['gcf', 'plan', 'more', '{id}'],
229
+ fields: [
230
+ {
231
+ key: 'passes',
232
+ label: 'More passes',
233
+ kind: 'choice',
234
+ required: true,
235
+ default: '2',
236
+ options: ['1', '2', '3', '5'].map((n) => ({ value: n, label: n })),
237
+ },
238
+ ],
239
+ },
240
+ plan_accept: {
241
+ label: 'implement as is',
242
+ help: 'The plan goes to implementation as it is, its open findings with it',
243
+ args: ['gcf', 'plan', 'accept', '{id}'],
244
+ fields: [],
245
+ },
215
246
  mode: {
216
247
  label: 'run mode',
217
248
  help: 'Where its runs go: the project folder or a worktree of their own; the next run takes it',
@@ -702,6 +733,28 @@ const BLOCK_SPECS = {
702
733
  args: ['gcf', 'inbox', 'later', '{id}', '--off', '--commit'],
703
734
  fields: [],
704
735
  },
736
+ // A chat's button to play: the board opens what it starts (docs/Play-Plan.md d17).
737
+ play: {
738
+ label: 'play',
739
+ help: "Start the card's own build on a target; its verdict stops it",
740
+ args: ['gcf', 'playtest', 'start', '{id}', '--json'],
741
+ fields: [text('target', 'Where to play', { required: true })],
742
+ propose: true,
743
+ },
744
+ 'play-setup': {
745
+ label: 'set up play',
746
+ help: 'How this project builds and starts its game: a card keeps its own build to play',
747
+ args: ['gcf', 'playtest', 'setup'],
748
+ fields: [
749
+ text('build', 'Build command'),
750
+ text('output', 'Folder it builds to: inside the project, ignored by git'),
751
+ text('target', 'Target name'),
752
+ text('start', 'Start command: {dir} the build, {port} a free port, {lan} this machine'),
753
+ text('open', 'What to open: a URL or words'),
754
+ text('stop', 'Command after the player stops'),
755
+ ],
756
+ propose: true,
757
+ },
705
758
  'question-answer': {
706
759
  label: 'answer',
707
760
  help: 'The answer goes into the record; the next agent on its units puts it in place',
@@ -839,7 +892,8 @@ const SECTIONS = {
839
892
  // A move's `dirty` refusal: the board reads `gcf edits diff` and offers these.
840
893
  edits: { commit: 'edits-commit', discard: 'edits-discard' },
841
894
  // `gcf changes` reads what is uncommitted: the board's Changes screen and its header's marker.
842
- changes: {},
895
+ // `commit`: its `gcf changes commit` takes the operator's ticked files and message.
896
+ changes: { commit: true },
843
897
  lessons: {},
844
898
  playtest: {
845
899
  // The inbox category a note from the playtest screen goes with.
@@ -885,6 +939,7 @@ const CHANGES = [
885
939
  'design discard',
886
940
  'edits commit',
887
941
  'edits discard',
942
+ 'changes commit',
888
943
  'take',
889
944
  'done',
890
945
  'drop',
@@ -898,6 +953,10 @@ const CHANGES = [
898
953
  'decide',
899
954
  'block',
900
955
  'unblock',
956
+ 'plan pass',
957
+ 'plan stall',
958
+ 'plan more',
959
+ 'plan accept',
901
960
  'inbox add',
902
961
  'inbox category',
903
962
  'inbox later',
@@ -911,6 +970,10 @@ const CHANGES = [
911
970
  'phase next',
912
971
  'hooks-install',
913
972
  'pillar',
973
+ 'playtest build',
974
+ 'playtest start',
975
+ 'playtest stop',
976
+ 'playtest setup',
914
977
  ];
915
978
 
916
979
  // The project chat of a GCF project (AD-5, AD-6): its skill, and the commands it asks for.
package/lib/git.js CHANGED
@@ -277,8 +277,20 @@ export function commitPaths(projectDir, message, paths, move = {}) {
277
277
  // path commits the deletion. A file staged but never committed and now deleted matches
278
278
  // nothing: no pathspec.
279
279
  const real = paths.filter((p) => existsSync(p) || inHead(projectDir, p));
280
- const msg = ['-m', message, ...moveTrailers(move)];
281
- const only = real.map((p) => literal(projectDir, p));
280
+
281
+ return commitOnly(projectDir, message, real, ['-m', message, ...moveTrailers(move)]);
282
+ }
283
+
284
+ /**
285
+ * `git commit --only` of `paths`, whatever they are, with `msg` its message arguments: the gate's
286
+ * refusals in the words of `message`. Returns the new HEAD.
287
+ * @param {string} projectDir
288
+ * @param {string} message
289
+ * @param {string[]} paths
290
+ * @param {string[]} msg
291
+ */
292
+ export function commitOnly(projectDir, message, paths, msg) {
293
+ const only = paths.map((p) => literal(projectDir, p));
282
294
  // A list past one command line goes on stdin (git 2.25+); a move's few paths as arguments.
283
295
  const long = inParts(only).length > 1;
284
296
  const res = spawnSync(
@@ -299,7 +311,7 @@ export function commitPaths(projectDir, message, paths, move = {}) {
299
311
  // The gate reads the whole gcf/ tree: another file's edit stops the move, in the Operator's
300
312
  // words. Its paths from git: the move's own staged files ride along and stop nothing.
301
313
  if (res.status !== 0 && /gcf\/ has changes outside the index/.test(out)) {
302
- const loose = dirtyGcf(projectDir, real);
314
+ const loose = dirtyGcf(projectDir, paths);
303
315
  throw dirtyRefusal(
304
316
  loose,
305
317
  `cannot record ${message} while gcf/ holds uncommitted changes: ${loose.join(', ')} — ` +
package/lib/integrate.js CHANGED
@@ -497,14 +497,20 @@ export async function integrate(projectDir, ids = []) {
497
497
  throw new Error(`integrate runs in the main checkout on its branch, not on ${branch}`);
498
498
  // The session of the item that run works now merges as before (gcf-run's step 1): it works the
499
499
  // checkout itself. A worktree session of the same harness inherits its owner, not that item.
500
- const main = runHolder(projectDir, MAIN_RUN);
501
- const own =
502
- process.env.GCF_RUN_OWNER === `run:${main}` &&
503
- Boolean(process.env.GCF_RUN_ITEM) &&
504
- process.env.GCF_RUN_ITEM === lockedItem(projectDir, MAIN_RUN);
505
- if (main && !own) throw new Error(`${MAIN_BUSY} (pid ${main}): integrate after it ends`);
500
+ const refuseBusy = () => {
501
+ const main = runHolder(projectDir, MAIN_RUN);
502
+ const own =
503
+ process.env.GCF_RUN_OWNER === `run:${main}` &&
504
+ Boolean(process.env.GCF_RUN_ITEM) &&
505
+ process.env.GCF_RUN_ITEM === lockedItem(projectDir, MAIN_RUN);
506
+ if (main && !own) throw new Error(`${MAIN_BUSY} (pid ${main}): integrate after it ends`);
507
+ };
508
+
509
+ refuseBusy();
506
510
 
507
511
  return withMainLock(projectDir, async () => {
512
+ // Again: the checkout may have been taken while this waited for the lock.
513
+ refuseBusy();
508
514
  // The run logs go in at every integrate, a main-mode run's first one too: nothing else
509
515
  // commits them there. Nothing to merge leaves the rest of main alone: a run's first
510
516
  // integrate must not refuse a dirty tree.
package/lib/main-lock.js CHANGED
@@ -31,6 +31,30 @@ export const alive = (pid) => {
31
31
  */
32
32
  export const MAIN_RUN = '.main-run';
33
33
 
34
+ /**
35
+ * Take the main checkout's run lock for work that is no run (a build by click): a main run refuses
36
+ * to start and `integrate` leaves its branches, as under a run. The second line is a token, no
37
+ * item: no card reads as run by it. The release, or null while a live run holds the checkout.
38
+ */
39
+ export async function claimMainRun(projectDir) {
40
+ const file = path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${MAIN_RUN}.lock`);
41
+ await mkdir(path.dirname(file), { recursive: true });
42
+ const token = randomUUID();
43
+ for (let tries = 0; tries < 3; tries++) {
44
+ if (await take(file, token))
45
+ return async () => {
46
+ if ((await readFile(file, 'utf8').catch(() => '')).includes(token))
47
+ await unlink(file).catch(() => {});
48
+ };
49
+
50
+ const dead = await staleText(file);
51
+ if (dead === null) return null;
52
+ await clearStale(file, dead);
53
+ }
54
+
55
+ return null;
56
+ }
57
+
34
58
  /** The item a run lock names on its second line (a main run's: what it works now), or null. */
35
59
  export function lockedItem(projectDir, id) {
36
60
  try {
package/lib/plan-check.js CHANGED
@@ -3,13 +3,74 @@
3
3
  // Whether the plan is any good is the improve passes' job; this only says it is usable. Its
4
4
  // form against the `plan` profile (CNL-P: blocks, one idea a line, no fact twice) is reported
5
5
  // as `format` lines, never a problem: a long line must not cost the item its paid passes.
6
- import { existsSync, readFileSync } from 'node:fs';
6
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { bodyIssues } from 'cnlp-kit';
9
9
  import { glossaryAvoids, GLOSSARY_NAME } from 'cnlp-kit/config';
10
10
  import { buildLedger } from './ledger.js';
11
11
  import { buildContext } from './context.js';
12
12
  import { loadDocProfile } from './design.js';
13
+ import { readConfig } from './gcf-paths.js';
14
+
15
+ // A pass of the plan's improve loop (Hold-Plan d12): `- pass K[ (cycle C)]: blocking N, polish M[,
16
+ // by codex]`, one line each in its `## Passes` section, written by `gcf plan pass`.
17
+ const PASS_LINE =
18
+ /^- pass (\d+)(?: \(cycle (\d+)\))?: blocking (\d+), polish (\d+)(?:, by (\w+))?$/;
19
+ const PASSES = /^## Passes\s*$/;
20
+ const PASSES_ANY = /^## Passes\s*$/m;
21
+
22
+ /** The passes a plan's `## Passes` section records, of every cycle, in order. */
23
+ export function planPasses(text) {
24
+ const out = [];
25
+ let inside = false;
26
+ for (const line of text.split(/\r?\n/)) {
27
+ if (/^## /.test(line)) inside = PASSES.test(line);
28
+ const m = inside ? PASS_LINE.exec(line.trim()) : null;
29
+ if (!m) continue;
30
+ const by = m[5] ? { by: m[5] } : {};
31
+ out.push({ pass: +m[1], cycle: +(m[2] ?? 0), blocking: +m[3], polish: +m[4], ...by });
32
+ }
33
+
34
+ return out;
35
+ }
36
+
37
+ /**
38
+ * The verdict on one cycle's passes (Hold-Plan d12): `converged` when the last found nothing
39
+ * blocking; `continue` while the count is within `plan_passes` (raised by the operator's `more`);
40
+ * `stalled` past it: one technical pass over the limit, then the operator decides.
41
+ */
42
+ export function passVerdict(passes, planPasses, more = 0) {
43
+ if (planPasses === 0) return 'converged';
44
+ const last = passes.at(-1);
45
+ if (!last) return 'continue';
46
+ if (last.blocking === 0) return 'converged';
47
+
48
+ return passes.length > planPasses + more ? 'stalled' : 'continue';
49
+ }
50
+
51
+ /**
52
+ * Where the item's planning stands: the passes of its current cycle (`plan_cycle`), and the
53
+ * verdict on them. The operator's `stall.accepted` converges it; a plan written before this
54
+ * version (no `plan_cycle`, no `## Passes`, a task ticked) counts as converged: work in flight
55
+ * does not stop at an upgrade.
56
+ */
57
+ async function passesOf(projectDir, data, text, done) {
58
+ const cycle = Number(data.plan_cycle ?? 0);
59
+ const passes = planPasses(text).filter((x) => x.cycle === cycle);
60
+ const stall = data.stall ?? null;
61
+ let limit = 3;
62
+ try {
63
+ limit = Number((await readConfig(path.join(path.resolve(projectDir), 'gcf'))).plan_passes);
64
+ } catch {
65
+ // A broken config.yml: the default limit; the config's own check says what is wrong.
66
+ }
67
+
68
+ const legacy = data.plan_cycle === undefined && !PASSES_ANY.test(text) && done > 0;
69
+ const verdict =
70
+ stall?.accepted || legacy ? 'converged' : passVerdict(passes, limit, Number(stall?.more ?? 0));
71
+
72
+ return { cycle, passes, verdict };
73
+ }
13
74
 
14
75
  /**
15
76
  * An item's plan and its task checkboxes: `{plan, tasks, done}`, `tasks` null when there is no
@@ -81,10 +142,60 @@ export async function planCheck(projectDir, id) {
81
142
  const ctx = await buildContext(projectDir, id);
82
143
  if (ctx.over_budget)
83
144
  problems.push(`readset ~${ctx.total_tokens_est} tokens is over the budget ${ctx.budget}`);
84
- const format =
85
- found === null
86
- ? []
87
- : await planFormat(projectDir, readFileSync(path.resolve(projectDir, plan), 'utf8'));
145
+ const text = found === null ? '' : readFileSync(path.resolve(projectDir, plan), 'utf8');
146
+ const format = found === null ? [] : await planFormat(projectDir, text);
147
+ const { cycle, passes, verdict } = await passesOf(projectDir, item.data, text, done);
148
+
149
+ return {
150
+ ...{ id, plan, tasks, done, problems, format, ok: problems.length === 0 },
151
+ ...{ cycle, passes, converged: verdict === 'converged', stalled: verdict === 'stalled' },
152
+ };
153
+ }
154
+
155
+ /**
156
+ * `gcf plan pass` (Hold-Plan d12): record pass K of the current cycle in the plan's `## Passes`
157
+ * section, K the next number, and answer the verdict on the cycle's passes so far.
158
+ * @param {string} projectDir
159
+ * @param {string} id
160
+ * @param {{blocking: number, polish: number, by?: string}} pass
161
+ */
162
+ export async function recordPass(projectDir, id, { blocking, polish, by }) {
163
+ passArgs(blocking, polish, by);
164
+ const item = (await buildLedger(projectDir)).item(id);
165
+ if (!item) throw new Error(`${id} is not a work item of gcf/work/`);
166
+ const { plan } = planTicks(projectDir, { ...item.data, id });
167
+ const file = path.resolve(projectDir, plan);
168
+ if (!existsSync(file)) throw new Error(`no plan at ${plan}: write it first`);
169
+ const text = readFileSync(file, 'utf8');
170
+ const cycle = Number(item.data.plan_cycle ?? 0);
171
+ const k = planPasses(text).filter((x) => x.cycle === cycle).length + 1;
172
+ const tag = cycle ? ` (cycle ${cycle})` : '';
173
+ const line = `- pass ${k}${tag}: blocking ${blocking}, polish ${polish}${by ? `, by ${by}` : ''}`;
174
+ writeFileSync(file, withPass(text, line));
175
+ const r = await planCheck(projectDir, id);
176
+ const verdict = r.converged ? 'converged' : r.stalled ? 'stalled' : 'continue';
177
+
178
+ return { id, pass: k, cycle, verdict, passes: r.passes.map((x) => x.blocking) };
179
+ }
180
+
181
+ /** The refusal of a pass's counts and reviewer, if any. */
182
+ function passArgs(blocking, polish, by) {
183
+ for (const [k, v] of Object.entries({ blocking, polish }))
184
+ if (!Number.isInteger(v) || v < 0) throw new Error(`--${k} is a count of findings, 0 or more`);
185
+ if (by !== undefined && !/^\w+$/.test(by)) throw new Error('--by is one word: the reviewer');
186
+ }
187
+
188
+ /** The plan with `line` at the end of its `## Passes` section, the section added when none. */
189
+ function withPass(text, line) {
190
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
191
+ const lines = text.split(/\r?\n/);
192
+ const at = lines.findIndex((l) => PASSES.test(l));
193
+ if (at < 0) return `${text.replace(/\s*$/, '')}${eol}${eol}## Passes${eol}${eol}${line}${eol}`;
194
+ let end = lines.findIndex((l, n) => n > at && /^## /.test(l));
195
+ if (end < 0) end = lines.length;
196
+ // After the section's last line with words: its blank lines stay below it.
197
+ while (end > at + 1 && !lines[end - 1].trim()) end--;
198
+ lines.splice(end, 0, line);
88
199
 
89
- return { id, plan, tasks, done, problems, format, ok: problems.length === 0 };
200
+ return lines.join(eol);
90
201
  }