gcf-aif-ext 0.34.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/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
+ }
@@ -77,6 +77,10 @@ const FIELDS = [
77
77
  'live',
78
78
  'model',
79
79
  'effort',
80
+ 'plan_model',
81
+ 'plan_effort',
82
+ 'implement_model',
83
+ 'implement_effort',
80
84
  'run_mode',
81
85
  'skip_gates',
82
86
  'gate_why',
@@ -226,6 +230,11 @@ const RULES = {
226
230
  live: (v) => liveProblem(v) ?? true,
227
231
  model: (v) => nullable(isText)(v) || 'model must be text or null',
228
232
  effort: (v) => nullable(isText)(v) || 'effort must be text or null',
233
+ // A phase's own (Plan-Review-Rework-Plan d10): over the item's model and effort in that phase.
234
+ plan_model: (v) => nullable(isText)(v) || 'plan_model must be text or null',
235
+ plan_effort: (v) => nullable(isText)(v) || 'plan_effort must be text or null',
236
+ implement_model: (v) => nullable(isText)(v) || 'implement_model must be text or null',
237
+ implement_effort: (v) => nullable(isText)(v) || 'implement_effort must be text or null',
229
238
  run_mode: (v) =>
230
239
  nullable((x) => ['main', 'worktree'].includes(x))(v) || 'run_mode must be main | worktree',
231
240
  skip_gates: (v) => typeof v === 'boolean' || 'skip_gates must be true or false',