gcf-aif-ext 0.32.0 → 0.36.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.
package/lib/play.js CHANGED
@@ -17,7 +17,7 @@ import { configDoc } from './config-doc.js';
17
17
  import { readConfig } from './gcf-paths.js';
18
18
  import { isValidId } from './id.js';
19
19
  import { buildLedger } from './ledger.js';
20
- import { alive, claimMainRun, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
20
+ import { alive, claimMainRun, locked, MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
21
21
  import { atomicWrite, renameRetrying } from './safe-path.js';
22
22
  import { commitMove } from './commit-move.js';
23
23
  import { commandEnv } from './shell-env.js';
@@ -1848,25 +1848,26 @@ export async function setupPlay(projectDir, opts) {
1848
1848
  const o = { ...rest, words };
1849
1849
  needSetup(dir, o);
1850
1850
  const file = path.join(dir, 'gcf', 'config.yml');
1851
- const was = existsSync(file) ? readFileSync(file, 'utf8') : '';
1852
- const doc = playDoc(was, o);
1853
- // The same setup again (an agent proposed what is there): nothing to write, nothing to commit.
1854
- const same =
1855
- JSON.stringify(configDoc(was).toJS()?.play ?? null) === JSON.stringify(doc.toJS().play);
1856
- const hash = same
1857
- ? null
1858
- : await commitMove(dir, 'gcf(config): play', {
1859
- files: [file],
1860
- commit,
1861
- key: 'config',
1862
- mutate: async () => {
1863
- // Read again under the lock: a move meanwhile may have changed the file.
1864
- const now = existsSync(file) ? readFileSync(file, 'utf8') : '';
1865
- const next = playDoc(now, o);
1866
- playOf(next.toJS());
1867
- await atomicWrite(file, next.toString());
1868
- },
1869
- });
1851
+ // Under the lock from the first read: a move that waited behind a main run reads again.
1852
+ const hash = await locked(dir, commit, async () => {
1853
+ const was = existsSync(file) ? readFileSync(file, 'utf8') : '';
1854
+ const doc = playDoc(was, o);
1855
+ // The same setup again (an agent proposed what is there): nothing to write, nothing to commit.
1856
+ const same =
1857
+ JSON.stringify(configDoc(was).toJS()?.play ?? null) === JSON.stringify(doc.toJS().play);
1858
+
1859
+ return same
1860
+ ? null
1861
+ : commitMove(dir, 'gcf(config): play', {
1862
+ files: [file],
1863
+ commit,
1864
+ key: 'config',
1865
+ mutate: async () => {
1866
+ playOf(doc.toJS());
1867
+ await atomicWrite(file, doc.toString());
1868
+ },
1869
+ });
1870
+ });
1870
1871
 
1871
1872
  return { hash, play: playOf(await readConfig(path.join(dir, 'gcf'))) };
1872
1873
  }
package/lib/review.js CHANGED
@@ -2,14 +2,23 @@
2
2
  // from `review.plan|code` of gcf/config.yml (row k, past the end the last), and, for the code,
3
3
  // the diff the reviewer reads: from where the card's work started to the disk, new files in,
4
4
  // the framework's own files out, the project's `no_diff` named and not shown, cut as Changes cuts.
5
+ // For the plan, the plan each pass saw and the pass's mode: full, or a check of the fixes by the
6
+ // diff from the earlier pass's plan (Plan-Review-Rework-Plan d3).
5
7
  import { spawnSync } from 'node:child_process';
6
- import { mkdirSync, writeFileSync } from 'node:fs';
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
9
  import path from 'node:path';
8
10
  import { cutOf, globTest } from './changes.js';
9
11
  import { onWorkBranch } from './commit-move.js';
10
12
  import { fallbackOf, gcfRoot, readConfig } from './gcf-paths.js';
11
13
  import { buildLedger } from './ledger.js';
12
- import { KINDS, stallOf } from './plan-check.js';
14
+ import {
15
+ KINDS,
16
+ planPasses,
17
+ planStalled,
18
+ reviewMark,
19
+ snapshotFiles,
20
+ stallOf,
21
+ } from './plan-check.js';
13
22
  import { codeTree, NOT_CODE } from './verify-stamp.js';
14
23
 
15
24
  const git = (dir, args) =>
@@ -38,8 +47,11 @@ export async function reviewRow(projectDir, id, { kind, pass, diff = false }) {
38
47
  const row = rows.length ? rows[Math.min(pass, rows.length) - 1] : null;
39
48
  const stall = stallOf(item.data, kind) ?? {};
40
49
  const withDiff = diff && kind === 'code';
50
+ await notStalled(projectDir, id, item.data, kind);
51
+ const seen = planReview(projectDir, id, item.data, { kind, pass, diff });
41
52
 
42
53
  return {
54
+ ...seen,
43
55
  ...{ id, kind, pass, rows: rows.length, row },
44
56
  plan: item.data.plan ?? `.ai-factory/plans/${id}.md`,
45
57
  more: Number(stall.more ?? 0),
@@ -53,6 +65,103 @@ export async function reviewRow(projectDir, id, { kind, pass, diff = false }) {
53
65
  };
54
66
  }
55
67
 
68
+ /**
69
+ * Refuse a plan pass (none of the code's) while the review is stalled: it waits for the
70
+ * operator (`review more|accept`), and a pass asked now would turn the snapshot past a pass
71
+ * nobody records.
72
+ */
73
+ async function notStalled(projectDir, id, data, kind) {
74
+ if (kind === 'plan' && (await planStalled(projectDir, { ...data, id })))
75
+ throw new Error(
76
+ `${id}: the plan review is stalled: it waits for the operator's review more or accept`,
77
+ );
78
+ }
79
+
80
+ /**
81
+ * What the reviewer of plan pass `pass` sees (Plan-Review-Rework-Plan d3): the plan as it is now
82
+ * kept in `.gcf-session/plans/<id>.md`, beside it the record of the pass and cycle it belongs to;
83
+ * `mode` full with no snapshot before this pass, check when an earlier pass's is there (a new
84
+ * cycle keeps it), and, with `diff`, the diff from that snapshot to the plan, written once when
85
+ * the pass is first asked. The same pass asked again gets the same mode and diff; any pass but
86
+ * the next one the plan waits for is refused. Not the code's: none.
87
+ * shortcut: no way back to a full review (d3); a `review more --full` deleting the snapshot when
88
+ * an operator asks for one.
89
+ * shortcut: the snapshot lives in the checkout that runs the review; a worktree's goes at its
90
+ * integrate (integrate.js cleanUp), so an amend after the merge gets a full review, the safe
91
+ * side; resolve the main checkout by `--git-common-dir`, as `baseOf` does, if that costs passes.
92
+ */
93
+ function planReview(projectDir, id, data, { kind, pass, diff }) {
94
+ if (kind !== 'plan') return {};
95
+ const dir = path.resolve(projectDir);
96
+ const plan = data.plan ?? `.ai-factory/plans/${id}.md`;
97
+ const cycle = Number(data.plan_cycle ?? 0);
98
+ const rec = snapshot(dir, id, plan, { cycle, pass });
99
+
100
+ // `cycle`: the check's prompt names the findings file of the pass before.
101
+ return { mode: rec.mode, cycle, ...(diff ? { diff: rec.diff ?? null } : {}) };
102
+ }
103
+
104
+ /**
105
+ * Keep the plan as pass `pass` of `cycle` sees it, once a pass, and the diff of a check from the
106
+ * pass before: the pass's record `{cycle, pass, mode, diff?}`. Only the next pass the plan's
107
+ * `## Passes` waits for is asked: a look-ahead or a typo would turn the snapshot past a pass not
108
+ * yet recorded, and its check would miss the fixes.
109
+ */
110
+ function snapshot(dir, id, plan, { cycle, pass }) {
111
+ const { home, snap, mark, next: fresh } = snapshotFiles(dir, id);
112
+ const src = path.resolve(dir, plan);
113
+ const had = existsSync(snap);
114
+ if (!existsSync(src)) {
115
+ // No plan yet and none kept: nothing to review against; a plan gone after a pass: refused.
116
+ if (!had) return { mode: 'full' };
117
+ throw new Error(`no plan at ${plan}: the plan review needs it`);
118
+ }
119
+
120
+ const text = readFileSync(src, 'utf8');
121
+ const next = planPasses(text, 'plan').filter((x) => x.cycle === cycle).length + 1;
122
+ if (pass !== next)
123
+ throw new Error(
124
+ `plan pass ${pass} is not the next: ${plan} records ${next - 1} pass(es)` +
125
+ `${cycle ? ` of cycle ${cycle}` : ''}, ask pass ${next}`,
126
+ );
127
+ const was = reviewMark(dir, id);
128
+ if (was && was.cycle === cycle && was.pass === pass) {
129
+ // A pass cut off after its record: its snapshot goes in now.
130
+ if (existsSync(fresh)) renameSync(fresh, snap);
131
+
132
+ return was;
133
+ }
134
+
135
+ const diff = had ? planDiff(dir, id, snap, src) : null;
136
+ // The old snapshot stays the baseline till the record is out: a cut-off write retries as it.
137
+ // shortcut: a pass cut off after its record and asked of no one again turns no snapshot; the
138
+ // next pass then diffs from the older plan or goes full, the safe side.
139
+ mkdirSync(home, { recursive: true });
140
+ writeFileSync(fresh, text);
141
+ const rec = { cycle, pass, mode: had ? 'check' : 'full', ...(diff ? { diff } : {}) };
142
+ writeFileSync(mark, `${JSON.stringify(rec)}\n`);
143
+ renameSync(fresh, snap);
144
+
145
+ return rec;
146
+ }
147
+
148
+ /** The diff of the plan from the earlier pass's snapshot, as the code's (`reviewDiff`). */
149
+ function planDiff(dir, id, from, src) {
150
+ const rel = (p) => path.relative(dir, p).replaceAll('\\', '/');
151
+ const r = git(dir, ['diff', '--no-index', '--', rel(from), rel(src)]);
152
+ // No git, or more than its buffer: the spawn's own error.
153
+ if (r.error) throw new Error(`git diff --no-index: ${r.error.message}`);
154
+ // --no-index answers 1 when the files differ.
155
+ if (r.status !== 0 && r.status !== 1)
156
+ throw new Error(`git diff --no-index: ${(r.stderr ?? '').trim() || `exit ${r.status}`}`);
157
+ const { text, cut } = cutOf(r.stdout);
158
+ const file = path.join(dir, '.gcf-session', 'review', `${id}.plan.diff`);
159
+ mkdirSync(path.dirname(file), { recursive: true });
160
+ writeFileSync(file, text);
161
+
162
+ return { file: rel(file), files: text ? [rel(src)] : [], no_diff: [], cut };
163
+ }
164
+
56
165
  /** A row as a pass's `by`: `agent:model:effort` (t2 d2); null with no row. */
57
166
  const byOf = (row) => (row ? `${row.agent}:${row.model}:${row.effort}` : null);
58
167
 
package/lib/rules.js ADDED
@@ -0,0 +1,428 @@
1
+ // The project's rules for its agents (Lessons-Review-Plan d6, Board-PRD §5.18): AGENTS.md, and a
2
+ // CLAUDE.md that does not import it. The block between the gcf markers is `gcf init`'s; the
3
+ // operator's own lines go under `## Project rules`, outside it. The core is the truth: a board
4
+ // reads and writes these files only through `gcf rules`.
5
+ import { createHash } from 'node:crypto';
6
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { spawnSync } from 'node:child_process';
9
+ import path from 'node:path';
10
+ import { START, END } from './agents-block.js';
11
+ import { atomicWrite } from './safe-path.js';
12
+ import { commitMove, commitWithEntries, uncommitted } from './commit-move.js';
13
+ import { withMainLock } from './main-lock.js';
14
+ import { entryIds, planDrop, planGroup } from './inbox.js';
15
+ import { gcfRoot } from './gcf-paths.js';
16
+ import { refusal } from './refusal.js';
17
+ import { dirtyIn } from './git.js';
18
+
19
+ export const RULE_FILES = ['AGENTS.md', 'CLAUDE.md'];
20
+
21
+ /**
22
+ * What an agent reads as its instructions, as pathspecs from the project (Lessons-Review-Plan
23
+ * d9): a run's plan under `.ai-factory/plans/` and the archive are its work, not instructions.
24
+ */
25
+ export const INSTRUCTION_PATHS = [
26
+ 'AGENTS.md',
27
+ 'CLAUDE.md',
28
+ '.claude',
29
+ '.ai-factory',
30
+ ':(exclude).ai-factory/plans',
31
+ ':(exclude).ai-factory/archive',
32
+ ];
33
+ const HEX = /^[0-9a-f]{4,64}$/i;
34
+
35
+ /** Whether a path from the project's root is one of INSTRUCTION_PATHS (a board marks it). */
36
+ export const isInstruction = (p) =>
37
+ RULE_FILES.includes(p) ||
38
+ p.startsWith('.claude/') ||
39
+ (p.startsWith('.ai-factory/') && !/^\.ai-factory\/(plans|archive)\//.test(p));
40
+
41
+ /**
42
+ * `gcf rules diff`: what the commits `from..to` changed in the agent's instructions, each commit
43
+ * with its diff (git's text, the board's FileDiff splits it), and the paths it touched; merges
44
+ * and the side a merge brought in are left out (`--first-parent`), so a worktree's `gcf(sync)`
45
+ * of main does not show main's edits as the run's. The operator's own moves (`GCF-By:
46
+ * operator`), which land on main during a main run, are not the run's either.
47
+ * shortcut: a plain `git commit` of the operator's carries no trailer and counts as the run's;
48
+ * a trusted record of who made each commit would tell them apart.
49
+ * `uncommitted`: the instruction paths not committed in this checkout now. `names`: the paths
50
+ * alone, no patch (a harness reads it through a pipe of bounded size).
51
+ * @param {string} projectDir
52
+ * @param {{from?: string, to?: string, names?: boolean}} range
53
+ */
54
+ export function rulesDiff(projectDir, { from, to, names = false }) {
55
+ for (const [flag, sha] of [
56
+ ['--from', from],
57
+ ['--to', to],
58
+ ])
59
+ if (!HEX.test(String(sha ?? ''))) throw new Error(`${flag} is a commit hash, hex only`);
60
+ const log = (args) => {
61
+ const r = gitOut(
62
+ `git log ${from}..${to}`,
63
+ ['-c', 'core.quotePath=false', 'log', '--no-merges', '--first-parent', '--relative']
64
+ .concat(['--invert-grep', '--grep=^GCF-By: operator$'])
65
+ .concat(['--no-renames', '--no-color', '--no-ext-diff', ...args, `${from}..${to}`, '--'])
66
+ .concat(INSTRUCTION_PATHS),
67
+ projectDir,
68
+ );
69
+ if (r.out === null) throw new Error(`git log ${from}..${to}: ${r.err}`);
70
+
71
+ return r.out;
72
+ };
73
+
74
+ const paths = log(['--name-only', '-z', '--format=']).split('\0').filter(Boolean);
75
+ const found = {
76
+ from,
77
+ to,
78
+ paths: [...new Set(paths)].sort(),
79
+ uncommitted: dirtyIn(projectDir, INSTRUCTION_PATHS),
80
+ };
81
+ if (names) return found;
82
+
83
+ // Each commit starts at a NUL: its hash and subject on the first line, its diff after.
84
+ const commits = log(['-p', '--format=%x00%H%x09%s'])
85
+ .split('\0')
86
+ .slice(1)
87
+ .map((part) => {
88
+ const nl = part.indexOf('\n');
89
+ const head = nl < 0 ? part : part.slice(0, nl);
90
+ const tab = head.indexOf('\t');
91
+
92
+ return {
93
+ sha: head.slice(0, tab),
94
+ subject: head.slice(tab + 1),
95
+ diff: nl < 0 ? '' : part.slice(nl + 1).replace(/^\n/, ''),
96
+ };
97
+ });
98
+
99
+ return { ...found, commits };
100
+ }
101
+
102
+ export const RULE_MAX = 300;
103
+ const SECTION = '## Project rules';
104
+
105
+ const read = (projectDir, name) => {
106
+ const file = path.join(projectDir, name);
107
+
108
+ return existsSync(file) ? readFileSync(file, 'utf8') : null;
109
+ };
110
+
111
+ const eolOf = (text) => (text.includes('\r\n') ? '\r\n' : '\n');
112
+ const baseOf = (text) => createHash('sha1').update(text).digest('hex');
113
+ const importsAgents = (text) => /^@AGENTS\.md\s*$/m.test(text);
114
+ const count = (text, s) => text.split(s).length - 1;
115
+ const BOM = String.fromCharCode(0xfeff);
116
+ // The block from its start to the end after it, as blockOf reads it; line endings folded.
117
+ const blockText = (text) => {
118
+ const at = text.indexOf(START);
119
+
120
+ return text.slice(at, text.indexOf(END, at) + END.length).replace(/\r\n/g, '\n');
121
+ };
122
+
123
+ // Two rules are one when they differ only in case and spaces.
124
+ const sameRule = (a, b) =>
125
+ a.replace(/\s+/g, ' ').toLowerCase() === b.replace(/\s+/g, ' ').toLowerCase();
126
+
127
+ /** The marked block's lines, 1-based both ends, or null when there is none. */
128
+ function blockOf(text) {
129
+ const at = text.indexOf(START);
130
+ const end = text.indexOf(END, at);
131
+ if (at < 0 || end < at) return null;
132
+ const line = (i) => text.slice(0, i).split('\n').length;
133
+
134
+ return { from: line(at), to: line(end) };
135
+ }
136
+
137
+ /**
138
+ * Every `## Project rules` outside the block, in order: its heading's index in `lines`, and
139
+ * where it ends. A hand edit may leave two: each one's lines are rules all the same.
140
+ */
141
+ function sectionsOf(lines, block) {
142
+ const inBlock = (i) => block !== null && i + 1 >= block.from && i + 1 <= block.to;
143
+ const ends = (i) => i >= lines.length || /^#{1,2}\s/.test(lines[i]) || lines[i].includes(START);
144
+
145
+ return lines.flatMap((l, at) => {
146
+ if (!sameRule(l.trim(), SECTION) || inBlock(at)) return [];
147
+ let end = at + 1;
148
+ while (!ends(end)) end++;
149
+
150
+ return [{ at, end }];
151
+ });
152
+ }
153
+
154
+ /** The operator's rules of a text: the lines under `## Project rules`, a bullet's dash off. */
155
+ export function ownRules(text) {
156
+ const lines = text.split(/\r?\n/);
157
+
158
+ return sectionsOf(lines, blockOf(text)).flatMap((s) =>
159
+ lines
160
+ .slice(s.at + 1, s.end)
161
+ .map((l) => l.trim().replace(/^[-*]\s+/, ''))
162
+ .filter(Boolean),
163
+ );
164
+ }
165
+
166
+ /** `text` with `rule` the last line of its last `## Project rules`, made when absent. */
167
+ function withRule(text, rule) {
168
+ const eol = eolOf(text);
169
+ const lines = text.split(/\r?\n/);
170
+ const s = sectionsOf(lines, blockOf(text)).at(-1);
171
+ if (!s) {
172
+ // One blank line between the old text and the section, however the text ended.
173
+ const sep = !text || text.endsWith(eol + eol) ? '' : eol.repeat(text.endsWith(eol) ? 1 : 2);
174
+
175
+ return `${text}${sep}${SECTION}${eol}${eol}- ${rule}${eol}`;
176
+ }
177
+
178
+ let last = s.end;
179
+ while (last > s.at + 1 && !lines[last - 1].trim()) last--;
180
+ lines.splice(last, 0, ...(last === s.at + 1 ? ['', `- ${rule}`] : [`- ${rule}`]));
181
+
182
+ return lines.join(eol);
183
+ }
184
+
185
+ /**
186
+ * Why `rule` cannot be a rule, or null: one line that neither imports a file (`@`), opens a
187
+ * heading (`#`), holds a code fence nor GCF's marker — a rule is a standing instruction.
188
+ */
189
+ export function ruleProblem(rule) {
190
+ if (!rule) return 'a rule needs its text';
191
+ if (/[\r\n]/.test(rule)) return 'a rule is one line';
192
+ if (rule.length > RULE_MAX) return `a rule is up to ${RULE_MAX} characters`;
193
+ if (rule.includes('<!-- gcf:')) return "a rule cannot hold GCF's block marker";
194
+ if (rule.startsWith('#')) return 'a rule cannot start with # (a heading)';
195
+ // Claude Code imports `@path` anywhere in the text; `a@b.c`, an @ inside a word, imports none.
196
+ if (/(^|[^\w.@])@[^\s@]/.test(rule))
197
+ return 'a rule cannot hold an @path: Claude Code imports that file (write the path without @)';
198
+ if (/```|~~~/.test(rule)) return 'a rule cannot hold a code fence';
199
+
200
+ return null;
201
+ }
202
+
203
+ /**
204
+ * The files of agent instructions as `gcf rules --json` gives them: each that exists, with its
205
+ * text, the hash a save names (`base`), its block's lines, whether it imports AGENTS.md and has
206
+ * edits not committed; `own_rules` are the lines under `## Project rules` of AGENTS.md.
207
+ */
208
+ export function readRules(projectDir) {
209
+ const files = RULE_FILES.flatMap((name) => {
210
+ const text = read(projectDir, name);
211
+ if (text === null) return [];
212
+
213
+ return [
214
+ {
215
+ file: name,
216
+ text,
217
+ base: baseOf(text),
218
+ bytes: Buffer.byteLength(text),
219
+ block: blockOf(text),
220
+ imports_agents: importsAgents(text),
221
+ dirty: uncommitted(projectDir, path.join(projectDir, name)),
222
+ },
223
+ ];
224
+ });
225
+
226
+ return { files, own_rules: ownRules(read(projectDir, 'AGENTS.md') ?? '') };
227
+ }
228
+
229
+ // A board sends a save of up to 10 MB: its diff, old and new lines both, fits in this.
230
+ const DIFF_MAX = 64 * 1024 * 1024;
231
+
232
+ /**
233
+ * A git read: its output, or null and git's words when its exit is not one of `ok`. Past
234
+ * DIFF_MAX it says so, not "failed".
235
+ * @returns {{out: string | null, err: string}}
236
+ */
237
+ function gitOut(what, args, cwd, ok = [0]) {
238
+ const r = spawnSync('git', args, {
239
+ windowsHide: true,
240
+ cwd,
241
+ encoding: 'utf8',
242
+ maxBuffer: DIFF_MAX,
243
+ });
244
+ if (/** @type {NodeJS.ErrnoException | undefined} */ (r.error)?.code === 'ENOBUFS')
245
+ throw new Error(`${what} is over ${DIFF_MAX / 1024 / 1024} MiB: too large to show`);
246
+ if (r.error) throw new Error(`${what} failed: ${r.error.message}`);
247
+ if (r.status === null || !ok.includes(r.status))
248
+ return { out: null, err: (r.stderr ?? '').trim() };
249
+
250
+ return { out: r.stdout, err: '' };
251
+ }
252
+
253
+ /** A file's text in HEAD, '' when HEAD has none. */
254
+ function headText(projectDir, name) {
255
+ return gitOut(`${name} in HEAD`, ['show', `HEAD:./${name}`], projectDir).out ?? '';
256
+ }
257
+
258
+ /**
259
+ * The diff of `name` from HEAD to `next`: what a commit of the whole file carries, edits not
260
+ * committed before the move included. Line endings read as one: a checkout's CRLF over a stored
261
+ * LF is no change to show.
262
+ */
263
+ export function diffFromHead(projectDir, name, next) {
264
+ const tmp = mkdtempSync(path.join(tmpdir(), 'gcf-rules-'));
265
+ try {
266
+ for (const [side, text] of [
267
+ ['a', headText(projectDir, name)],
268
+ ['b', next],
269
+ ]) {
270
+ mkdirSync(path.join(tmp, side));
271
+ writeFileSync(path.join(tmp, side, name), text.replace(/\r\n/g, '\n'));
272
+ }
273
+
274
+ const args = ['diff', '--no-index', '--no-color', '--no-ext-diff', '--no-prefix', '--'];
275
+ // 1 is "they differ"; anything else, git failed.
276
+ const r = gitOut(`the diff of ${name}`, [...args, `a/${name}`, `b/${name}`], tmp, [0, 1]);
277
+ if (r.out === null) throw new Error(`git diff of ${name} failed: ${r.err}`);
278
+
279
+ return r.out;
280
+ } finally {
281
+ rmSync(tmp, { recursive: true, force: true });
282
+ }
283
+ }
284
+
285
+ const ignoredByGit = (projectDir, name) =>
286
+ spawnSync('git', ['check-ignore', '-q', '--', name], { windowsHide: true, cwd: projectDir })
287
+ .status === 0;
288
+
289
+ /** The files a rule goes to: AGENTS.md always, a CLAUDE.md that does not import it. */
290
+ function ruleTargets(projectDir) {
291
+ const claude = read(projectDir, 'CLAUDE.md');
292
+
293
+ return [
294
+ { name: 'AGENTS.md', text: read(projectDir, 'AGENTS.md') ?? '' },
295
+ ...(claude !== null && !importsAgents(claude) ? [{ name: 'CLAUDE.md', text: claude }] : []),
296
+ ];
297
+ }
298
+
299
+ /** The hash of the targets as read: which ones, and their text. */
300
+ const targetsBase = (targets) => baseOf(targets.map((t) => `${t.name}\0${t.text}`).join('\0'));
301
+
302
+ /** Each target with `rule` added; refused when one has it already. */
303
+ function ruleWrites(projectDir, targets, rule) {
304
+ return targets.map(({ name, text }) => {
305
+ // `gcf init` writes its block there all the same, but a rule is committed: say so in words.
306
+ if (ignoredByGit(projectDir, name))
307
+ throw new Error(
308
+ `${name} is ignored by git, so a rule there cannot be committed: ` +
309
+ (name === 'CLAUDE.md'
310
+ ? 'add a line `@AGENTS.md` to it to read the rules there, or stop ignoring it'
311
+ : 'stop ignoring it'),
312
+ );
313
+ if (ownRules(text).some((r) => sameRule(r, rule)))
314
+ throw new Error(`${name} has this rule already`);
315
+
316
+ return { name, file: path.join(projectDir, name), text: withRule(text, rule) };
317
+ });
318
+ }
319
+
320
+ /**
321
+ * `gcf rules add`: `text` under `## Project rules` of each file an agent reads, entries `from`
322
+ * erased in the same commit (Lessons-Review-Plan d6). A file of instructions with edits not
323
+ * committed (`gcf init` refreshed its block) goes into the commit whole; `dryRun` gives the diff
324
+ * of each from HEAD, those edits included, and writes nothing, and the `base` of the files it
325
+ * read: a move given that `base` is refused when they changed since, so what it commits is what
326
+ * the operator saw (no `base`: an older board, written over as before).
327
+ * @param {string} projectDir
328
+ * @param {{text?: string, from?: string | string[], base?: string, dryRun?: boolean,
329
+ * commit?: boolean, proposal?: string}} opts
330
+ */
331
+ export async function addRule(
332
+ projectDir,
333
+ { text, from, base, dryRun = false, commit = true, proposal },
334
+ ) {
335
+ // A bullet given with the rule is the one the section writes: not a second.
336
+ const rule = String(text ?? '')
337
+ .trim()
338
+ .replace(/^[-*]\s+/, '');
339
+ const problem = ruleProblem(rule);
340
+ if (problem) throw new Error(problem);
341
+ const ids = entryIds(from);
342
+ if (dryRun) {
343
+ await planGroup(ids, (id) => planDrop(gcfRoot(projectDir), id));
344
+ // One read for the diffs and the base: an edit between two reads would pass unseen.
345
+ const targets = ruleTargets(projectDir);
346
+ const files = ruleWrites(projectDir, targets, rule).map((w) => ({
347
+ file: w.name,
348
+ diff: diffFromHead(projectDir, w.name, w.text),
349
+ }));
350
+
351
+ return { rule, from: ids, base: targetsBase(targets), files };
352
+ }
353
+
354
+ let written = [];
355
+ const message = `gcf(rules): add a project rule${ids.length ? ` from ${ids.join(', ')}` : ''}`;
356
+ const move = { ids, commit, key: 'rules-add', proposal };
357
+ const hash = await commitWithEntries(projectDir, message, move, async () => {
358
+ const targets = ruleTargets(projectDir);
359
+ if (base && base !== targetsBase(targets))
360
+ throw new Error(
361
+ 'AGENTS.md or CLAUDE.md changed since its diff was read: read it again; nothing written',
362
+ );
363
+ const writes = ruleWrites(projectDir, targets, rule);
364
+ written = writes.map((w) => w.name);
365
+
366
+ return {
367
+ files: writes.map((w) => w.file),
368
+ write: async () => {
369
+ for (const w of writes) await atomicWrite(w.file, w.text);
370
+ },
371
+ };
372
+ });
373
+
374
+ return { rule, from: ids, files: written, hash };
375
+ }
376
+
377
+ /** Why `next` may not replace `old`: GCF's block is `gcf init`'s, kept as it is. */
378
+ function markerProblem(old, next) {
379
+ const want = blockOf(old) ? 1 : 0;
380
+ if (count(next, START) !== want || count(next, END) !== want)
381
+ return want
382
+ ? `keep GCF's block whole: one ${START} and one ${END}`
383
+ : `${START} and ${END} belong to gcf init: the file has no GCF block`;
384
+ if (want && blockText(next) !== blockText(old))
385
+ return "the GCF block is gcf init's: edit outside its markers";
386
+
387
+ return null;
388
+ }
389
+
390
+ /**
391
+ * `gcf rules save`: the operator's whole text of `file` over the one read at `base`, in the
392
+ * file's line endings; GCF's block must come back as it was. `dryRun` gives the diff from HEAD.
393
+ * @param {string} projectDir
394
+ * @param {{file: string, base?: string, text: string, dryRun?: boolean, commit?: boolean}} opts
395
+ */
396
+ export async function saveRules(projectDir, { file, base, text, dryRun = false, commit = true }) {
397
+ if (!RULE_FILES.includes(file))
398
+ throw new Error(`--file is ${RULE_FILES.join(' | ')}, not ${file}`);
399
+ if (!base) throw new Error('--base is the hash gcf rules gave the text it read');
400
+ const go = async () => {
401
+ const old = read(projectDir, file) ?? '';
402
+ if (base !== baseOf(old))
403
+ throw refusal('stale', {}, `${file} changed since it was read: read it again, nothing saved`);
404
+ // A text read through stdin lost the file's BOM: it stays the file's.
405
+ const bom = old.startsWith(BOM) && !String(text).startsWith(BOM) ? BOM : '';
406
+ const next = bom + String(text).replace(/\r?\n/g, eolOf(old));
407
+ const problem = markerProblem(old, next);
408
+ if (problem) throw new Error(problem);
409
+ if (next === old) throw new Error(`${file}: nothing to change`);
410
+ const diff = diffFromHead(projectDir, file, next);
411
+ // The file's own edits taken back to HEAD: a commit of nothing, Changes discards them.
412
+ if (!diff.trim())
413
+ throw new Error(`${file}: no change from HEAD: discard its edits in Changes instead`);
414
+ if (dryRun) return { file, base, diff };
415
+ const abs = path.join(projectDir, file);
416
+ const hash = await commitMove(projectDir, `gcf(rules): save ${file}`, {
417
+ files: [abs],
418
+ inputs: [abs],
419
+ mutate: () => atomicWrite(abs, next),
420
+ commit,
421
+ key: 'rules-save',
422
+ });
423
+
424
+ return { file, hash };
425
+ };
426
+
427
+ return commit && !dryRun ? withMainLock(projectDir, go) : go();
428
+ }
@@ -9,7 +9,7 @@ import { existsSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } f
9
9
  import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
10
10
  import { spawnSync } from 'node:child_process';
11
11
  import path from 'node:path';
12
- import { alive, withMainLock } from './main-lock.js';
12
+ import { alive, withMainLock, yieldToWaiting } from './main-lock.js';
13
13
  import { enterFolder } from './shelf.js';
14
14
 
15
15
  // A run's default timeout: an agent can implement for long without a gcf command. The harness
@@ -87,6 +87,7 @@ export async function claimSession(projectDir, id, owner = ownerOf(), opts = {})
87
87
  const file = markOf(projectDir, id);
88
88
  await excludeSession(projectDir);
89
89
  await mkdir(path.dirname(file), { recursive: true });
90
+ await yieldToWaiting(projectDir);
90
91
 
91
92
  // Under the main lock: two sessions claiming at once must not both pass the check.
92
93
  return withMainLock(projectDir, async () => {