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.
@@ -9,7 +9,7 @@ import { existsSync } from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { commitMove } from './commit-move.js';
11
11
  import { atomicWrite } from './safe-path.js';
12
- import { gcfRoot, RUN_WORD } from './gcf-paths.js';
12
+ import { gcfRoot, PHASE_DEFAULTS, RUN_PHASES, RUN_WORD } from './gcf-paths.js';
13
13
  import { configDoc, ensureMap } from './config-doc.js';
14
14
 
15
15
  const GROUPS_SHAPE = 'gcf/config.yml: agent.groups must map a group id to true or false';
@@ -184,7 +184,8 @@ export const DENY_GROUPS = [
184
184
  id: 'human-moves',
185
185
  label:
186
186
  "the human's GCF moves: verdict, answer, unblock, a card's gates or text, phase, pillars, " +
187
- 'settings, permissions, setup, hand edits (decide the core holds by the gates)',
187
+ 'settings, permissions, setup, hand edits, project rules, lesson reports (decide the core ' +
188
+ 'holds by the gates)',
188
189
  on: true,
189
190
  rules: shell(
190
191
  'ai-factory gcf verdict*',
@@ -206,6 +207,11 @@ export const DENY_GROUPS = [
206
207
  'ai-factory gcf edits discard*',
207
208
  // What goes into the operator's commit is theirs to say; an agent commits with git.
208
209
  'ai-factory gcf changes commit*',
210
+ // The project's standing instructions to its agents, and what leaves it for GCF or the
211
+ // template (Lessons-Review-Plan d6): an agent proposes them.
212
+ 'ai-factory gcf rules add*',
213
+ 'ai-factory gcf rules save*',
214
+ 'ai-factory gcf lessons report*',
209
215
  'ai-factory gcf-harness init*',
210
216
  // The space keeps `gcf-harness runs`, the history of past runs, a read the agent may make.
211
217
  'ai-factory gcf-harness run *',
@@ -334,11 +340,11 @@ function choices(agent) {
334
340
  * without its own pick runs on; null, or `default` written by hand, leaves it to the agent's
335
341
  * defaults (Opus, High: Board-PRD decision 36). One word each, as an item's.
336
342
  */
337
- function picksOf(agent) {
343
+ function picksOf(agent, where = 'agent') {
338
344
  const pick = (k) => {
339
345
  const v = agent[k] ?? null;
340
346
  if (v !== null && !(typeof v === 'string' && RUN_WORD.test(v)))
341
- throw new Error(`gcf/config.yml: agent.${k} must be one plain word, e.g. opus`);
347
+ throw new Error(`gcf/config.yml: ${where}.${k} must be one plain word, e.g. opus`);
342
348
 
343
349
  return v?.toLowerCase() === 'default' ? null : v;
344
350
  };
@@ -346,6 +352,23 @@ function picksOf(agent) {
346
352
  return { model: pick('model'), effort: pick('effort') };
347
353
  }
348
354
 
355
+ /**
356
+ * The project's model and effort of each phase (`agent.plan|implement.model|effort`,
357
+ * Plan-Review-Rework-Plan d10), over `agent.model|effort` in that phase; `phase_defaults`, GCF's
358
+ * own of each, under them.
359
+ */
360
+ function phasePicksOf(agent) {
361
+ const out = {};
362
+ for (const phase of RUN_PHASES) {
363
+ const v = agent[phase] ?? {};
364
+ if (typeof v !== 'object' || Array.isArray(v))
365
+ throw new Error(`gcf/config.yml: agent.${phase} must map model and effort`);
366
+ out[phase] = picksOf(v, `agent.${phase}`);
367
+ }
368
+
369
+ return { ...out, phase_defaults: PHASE_DEFAULTS };
370
+ }
371
+
349
372
  /**
350
373
  * The `agent:` section resolved: the project's model and effort, each group on or off, the deny
351
374
  * rules the run gets, the extra allow rules (for an agent run without bypass). No section: the
@@ -375,6 +398,7 @@ export function agentOf(config) {
375
398
 
376
399
  return {
377
400
  ...picksOf(agent),
401
+ ...phasePicksOf(agent),
378
402
  groups,
379
403
  deny_extra: extra,
380
404
  deny: claudeOf(denied),
package/lib/audit-core.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
- import { spawnSync } from 'node:child_process';
5
4
  import {
6
5
  listItems,
7
6
  listSystems,
@@ -20,7 +19,15 @@ import { STORED } from './transitions.js';
20
19
  import { openDepends } from './work-ops.js';
21
20
  import { runHolder } from './main-lock.js';
22
21
  import { markOwner, ownerOf, sessionActive } from './session-mark.js';
23
- import { fieldOf } from './question-fields.js';
22
+ import {
23
+ blameLines,
24
+ d2States,
25
+ git,
26
+ PLACEHOLDER_RE,
27
+ UNTIL_RE,
28
+ untilStatus,
29
+ verdictMatchers,
30
+ } from './d2-states.js';
24
31
  import { inboxProblems } from './inbox.js';
25
32
  import { inboxVocabulary } from './domain.js';
26
33
  import { gatePolicy, verdictDeferred } from './gates.js';
@@ -30,21 +37,6 @@ import { cardRunMode, liveCopies } from './integrate.js';
30
37
  import { playOnIssues } from './play-on.js';
31
38
  import { platformsOf } from './playtest-list.js';
32
39
 
33
- function git(args, cwd) {
34
- // A blame of a long file overflows the 1 MiB default, and an overflow reads as a git failure.
35
- const res = spawnSync('git', args, {
36
- windowsHide: true,
37
- cwd,
38
- encoding: 'utf8',
39
- maxBuffer: 64 * 1024 * 1024,
40
- });
41
-
42
- return res.status === 0 ? res.stdout.trim() : null;
43
- }
44
-
45
- const UNTIL_RE = /\[until:\s*(verdict\([a-z0-9-]+\)|retune\([a-z0-9-]+\)|manual\([^)]*\))\]/g;
46
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
47
-
48
40
  /**
49
41
  * Whether an item runs, and who works it (`running_by`): `run`, a harness run's live lock; `you`,
50
42
  * a fresh session mark this session or its run owns (`GCF_RUN_OWNER`, else
@@ -79,12 +71,15 @@ function runningOf(projectDir, id) {
79
71
  * @property {string[]} legacy_cards
80
72
  * @property {{tokens: number, budget: number, over: boolean, count: number, too_many: boolean}
81
73
  * | null} pillars
82
- * @property {Array<{file: string, id?: string, trigger: string, status: string}>} until
74
+ * @property {Array<{file: string, id?: string, trigger: string,
75
+ * status: 'stale' | 'open' | 'manual' | 'answered', placeholder?: true}>} until a D2's
76
+ * `answered` once it has an answer: line; `placeholder`, a marker GCF wrote itself
83
77
  * @property {Record<string, object[]>} linter
84
78
  * @property {object[]} pragmas
85
79
  * @property {boolean} index_drift
86
80
  * @property {Array<{id: string, status: string}>} illegal_status
87
- * @property {Array<{id: string, commits: number | null, limit: number}>} stale_questions
81
+ * @property {Array<{id: string, commits: number | null, limit: number}>} stale_questions the
82
+ * unanswered D1 and D2 of `manual(...)` or no trigger past the limit
88
83
  * @property {{errors: string[], warnings: string[]}} play_on cards' build names (lib/play-on.js)
89
84
  * @property {number} [schema]
90
85
  * @property {Array<{id: string, type: string, gate: string, status: string, system: string[],
@@ -117,6 +112,11 @@ export async function audit(projectDir) {
117
112
  const unplayed = items.filter(
118
113
  (c) => c.data.status === 'unplayed' && !named.has(c.data.milestone),
119
114
  ).length;
115
+ const fired = verdictMatchers(projectDir, ledger, items);
116
+ const questions = await d2States(projectDir, {
117
+ fired,
118
+ limit: config.question_stale_after_commits,
119
+ });
120
120
  /** @type {AuditReport} */
121
121
  const report = {
122
122
  first_line: '',
@@ -131,17 +131,12 @@ export async function audit(projectDir) {
131
131
  },
132
132
  legacy_cards: legacyCards(root),
133
133
  pillars: await pillarsOf(root, config),
134
- until: untilRecords(
135
- items,
136
- systems,
137
- verdictMatchers(projectDir, ledger, items),
138
- await questionsText(root),
139
- ),
134
+ until: untilRecords(projectDir, { items, systems, fired, questions }),
140
135
  linter: {},
141
136
  pragmas: [],
142
137
  index_drift: await drifted(root),
143
138
  illegal_status: [],
144
- stale_questions: staleQuestions(projectDir, root, config),
139
+ stale_questions: staleQuestions(questions, config),
145
140
  inbox: await inboxProblems(root, inboxVocabulary()),
146
141
  play_on: playOnIssues(items, config, await platformsOf(root)),
147
142
  // A config from before the review rows (Operator-Tasks-Plan t2 d1): the command that moves it.
@@ -277,119 +272,58 @@ async function pillarsOf(root, config) {
277
272
  }
278
273
 
279
274
  /**
280
- * Open questions older than the limit, aged by the last commit that changed their `- id:` line
281
- * beyond whitespace (GCF-PRD §7.4): a pile of unanswered ones means the human has dropped out
282
- * of the loop.
283
- */
284
- function staleQuestions(projectDir, root, config) {
285
- if (!existsSync(path.join(root, 'open-questions.md'))) return [];
286
- // null for an untracked file or outside a repository: no commit to age from. -w: a respaced
287
- // or re-ended (CRLF/LF) line keeps the commit that wrote it.
288
- const blame = git(['blame', '-w', '--porcelain', '--', 'gcf/open-questions.md'], projectDir);
289
- if (blame === null) return [];
290
- const added = [];
291
- let hash = '';
292
- for (const line of blame.split('\n')) {
293
- const head = line.match(/^([0-9a-f]{40,64}) \d+ \d+/);
294
- if (head) hash = head[1];
295
- const id = line.match(/^\t\uFEFF?- id:\s*(\S+)/)?.[1];
296
- // An uncommitted line blames to the all-zero hash: it is new, not old.
297
- if (id && !/^0+$/.test(hash)) added.push({ id, hash });
298
- }
299
-
300
- const ages = new Map();
301
- const ageOf = (h) => {
302
- if (!ages.has(h)) {
303
- const raw = git(['rev-list', '--count', `${h}..HEAD`], projectDir);
304
- // Number(null) is 0, "fresh" — the one answer that must never be guessed (see staleEntry).
305
- ages.set(h, raw === null ? null : Number(raw));
306
- }
307
-
308
- return ages.get(h);
309
- };
310
-
311
- const limit = config.question_stale_after_commits;
312
-
313
- return added
314
- .map(({ id, hash: h }) => ({ id, commits: ageOf(h), limit }))
315
- .filter((q) => q.commits === null || q.commits > limit);
316
- }
317
-
318
- /**
319
- * Whether a verdict fired. `verdict(id)` reads the files, as the ledger does (GCF-PRD §5.8): a
320
- * keep or kill left a history or graveyard line, a tune left the item's tune_count — so a
321
- * squash or a shallow clone does not hide it, and a revert takes it back.
275
+ * Open questions the human owes past the limit, aged by the last commit that changed their
276
+ * `- id:` line beyond whitespace (GCF-PRD §7.4): a pile of them means the human has dropped out
277
+ * of the loop. An answered record is not owed; an acting D2 waits for its trigger and a fired
278
+ * one is a stale until record (lib/d2-states.js).
322
279
  */
323
- function verdictMatchers(projectDir, ledger, items) {
324
- const tuned = items.filter((c) => (c.data.tune_count ?? 0) > 0);
325
- const verdictLog =
326
- git(['log', '--basic-regexp', '--grep', '^gcf(verdict):', '--format=%s'], projectDir) ?? '';
327
-
328
- return {
329
- verdict: (id) =>
330
- ledger.where(id).terminal.some((t) => t !== 'done') || tuned.some((c) => c.data.id === id),
331
- // shortcut: a kept item's tunes leave no file behind, so retune(sys) also greps the verdict
332
- // subjects; upgrade when tunes get their own history line.
333
- retune: (system) =>
334
- tuned.some((c) => (c.data.system ?? []).includes(system)) ||
335
- new RegExp(`^gcf\\(verdict\\): tune .*→ (?:.*,)?${escapeRe(system)}(?:,|$)`, 'm').test(
336
- verdictLog,
337
- ),
338
- };
339
- }
340
-
341
- function untilStatus(trigger, fired) {
342
- if (trigger.startsWith('verdict(')) {
343
- return fired.verdict(trigger.slice(8, -1)) ? 'stale' : 'open';
344
- }
345
-
346
- if (trigger.startsWith('retune(')) {
347
- return fired.retune(trigger.slice(7, -1)) ? 'stale' : 'open';
348
- }
349
-
350
- return 'manual';
351
- }
352
-
353
- /** open-questions.md, or '' without one. */
354
- const questionsText = async (root) => {
355
- const file = path.join(root, 'open-questions.md');
356
-
357
- return existsSync(file) ? readFile(file, 'utf8') : '';
358
- };
359
-
360
- const D2_UNTIL_RE = /^(verdict\([a-z0-9-]+\)|retune\([a-z0-9-]+\)|manual\([^)]*\))/;
280
+ const staleQuestions = (questions, config) =>
281
+ questions
282
+ .filter((q) => q.aged)
283
+ .map((q) => ({ id: q.id, commits: q.commits, limit: config.question_stale_after_commits }));
361
284
 
362
285
  /**
363
286
  * Until annotations across work items and systems docs, and the `until:` of each D2 record in
364
- * open-questions.md (`questions` its text): a fired one is an assumption to ask the human again.
287
+ * open-questions.md (`questions` their states): a fired one is an assumption to ask the human
288
+ * again. A retune annotation counts the tunes after the commit that wrote its line; GCF's own
289
+ * markers (PLACEHOLDER_RE) are flagged `placeholder`.
365
290
  */
366
- function untilRecords(items, systems, fired, questions) {
291
+ function untilRecords(projectDir, { items, systems, fired, questions }) {
367
292
  const docs = [
368
- ...items.map((c) => ({ rel: `work/${c.name}`, body: c.body })),
369
- ...systems.map((s) => ({ rel: `systems/${s.name}`, body: s.body })),
293
+ ...items.map((c) => ({ rel: `gcf/work/${c.name}`, body: c.body })),
294
+ ...systems.map((s) => ({ rel: `gcf/systems/${s.name}`, body: s.body })),
370
295
  ];
371
296
  const until = [];
372
297
  for (const doc of docs) {
298
+ const lines = doc.body.split('\n').map((l) => l.replace(/\r$/, ''));
299
+ let blamed;
300
+ // The body is the file's tail, after its frontmatter: line i is blame line offset + i. No
301
+ // blame (an untracked file, no repository) or a line that does not match: no birth, any
302
+ // tune fires it as before.
303
+ const birthOf = (i) => {
304
+ blamed ??= blameLines(projectDir, doc.rel) ?? [];
305
+ const at = blamed.length - (lines.at(-1) === '' ? lines.length - 1 : lines.length) + i;
306
+
307
+ return blamed[at]?.text === lines[i] ? blamed[at].hash : undefined;
308
+ };
309
+
373
310
  // A quoted line (an inbox entry's text in a note:) holds no annotation, as for the gate.
374
- const own = doc.body
375
- .split('\n')
376
- .filter((l) => !l.startsWith('>'))
377
- .join('\n');
378
- for (const m of own.matchAll(UNTIL_RE)) {
379
- until.push({ file: `gcf/${doc.rel}`, trigger: m[1], status: untilStatus(m[1], fired) });
311
+ for (const [i, line] of lines.entries()) {
312
+ if (line.startsWith('>')) continue;
313
+ for (const m of line.matchAll(UNTIL_RE)) {
314
+ const birth = m[1].startsWith('retune(') ? birthOf(i) : undefined;
315
+ until.push({
316
+ file: doc.rel,
317
+ trigger: m[1],
318
+ status: untilStatus(m[1], fired, birth),
319
+ ...(PLACEHOLDER_RE.test(m[0]) && { placeholder: true }),
320
+ });
321
+ }
380
322
  }
381
323
  }
382
324
 
383
- for (const rec of questions.replace(/\r\n/g, '\n').split(/\n(?=- id:)/)) {
384
- const id = rec.match(/^- id:\s*(\S+)/)?.[1];
385
- const trigger = fieldOf(rec, 'until')?.match(D2_UNTIL_RE)?.[1];
386
- if (!id || !trigger || !/^D2\b/.test(fieldOf(rec, 'class') ?? '')) continue;
387
- until.push({
388
- file: 'gcf/open-questions.md',
389
- id,
390
- trigger,
391
- status: untilStatus(trigger, fired),
392
- });
325
+ for (const q of questions.filter((r) => r.trigger)) {
326
+ until.push({ file: 'gcf/open-questions.md', id: q.id, trigger: q.trigger, status: q.status });
393
327
  }
394
328
 
395
329
  return until;
@@ -421,7 +355,7 @@ const itemAlerts = (report) => [
421
355
 
422
356
  /** Alerts about the documents. @param {AuditReport} report */
423
357
  const docAlerts = (report) => [
424
- report.until.filter((u) => u.status === 'stale').length && 'stale until-records present',
358
+ staleUntil(report.until),
425
359
  report.pillars?.over && 'PILLARS over token budget',
426
360
  report.pillars?.too_many && `PILLARS has ${report.pillars.count} pillars (max ${PILLARS_MAX})`,
427
361
  report.stale_questions.length &&
@@ -435,6 +369,17 @@ const docAlerts = (report) => [
435
369
  ...inboxAlerts(report.inbox),
436
370
  ];
437
371
 
372
+ /** The fired until records, each by its D2's id or its file, for the human to answer. */
373
+ function staleUntil(until) {
374
+ const stale = until.filter((u) => u.status === 'stale');
375
+
376
+ return (
377
+ stale.length &&
378
+ `stale until-records: ${stale.map((u) => `${u.id ?? u.file} ${u.trigger}`).join(', ')}` +
379
+ ' — ask the human'
380
+ );
381
+ }
382
+
438
383
  /** Alerts about gcf/config.yml. @param {AuditReport} report */
439
384
  const configAlerts = (report) => [
440
385
  report.review_migration &&
package/lib/board.js CHANGED
@@ -19,6 +19,7 @@ import { domainOf, hasHarness, RUNS_FROM } from './domain.js';
19
19
  import { lessonRepeats } from './inbox-categories.js';
20
20
  import { openDepends } from './work-ops.js';
21
21
  import { listQuestions } from './questions.js';
22
+ import { d2States, questionRow, verdictMatchers } from './d2-states.js';
22
23
  import { sessionActive } from './session-mark.js';
23
24
  import { shelvedCards } from './shelf.js';
24
25
  import { agentOf } from './agent-permissions.js';
@@ -32,7 +33,7 @@ import { handoffOf } from './handoff.js';
32
33
 
33
34
  // The version of the JSON below (Methodology §11): a board refuses one it does not know. Bump it
34
35
  // when a field changes meaning or goes away; a new field does not bump it.
35
- export const BOARD_SCHEMA = 6;
36
+ export const BOARD_SCHEMA = 7;
36
37
 
37
38
  /**
38
39
  * Plan progress `{tasks, done}` from its checkboxes and the plan's project path, both null
@@ -147,7 +148,7 @@ async function phaseOf(projectDir) {
147
148
  * or unreadable;
148
149
  * `error` says why a file that is there cannot be read: the run buttons hide with no harness.
149
150
  */
150
- async function extensionsOf(projectDir) {
151
+ export async function extensionsOf(projectDir) {
151
152
  const file = path.join(path.resolve(projectDir), '.ai-factory.json');
152
153
  let text;
153
154
  try {
@@ -229,6 +230,14 @@ const SCALARS = [
229
230
  'since',
230
231
  'model',
231
232
  'effort',
233
+ // A phase's own model and effort (Plan-Review-Rework-Plan d10).
234
+ 'plan_model',
235
+ 'plan_effort',
236
+ 'implement_model',
237
+ 'implement_effort',
238
+ // The plan review's cycle now (a tune, an unblock, an amend opens one): which passes and
239
+ // findings a board shows as current (Plan-Review-Rework-Plan d2).
240
+ 'plan_cycle',
232
241
  'run_mode',
233
242
  'skip_gates',
234
243
  'gate_why',
@@ -439,7 +448,16 @@ export async function board(projectDir) {
439
448
  i.needed_by = items.filter((o) => o.depends.includes(i.id)).map((o) => o.id);
440
449
 
441
450
  const live = await readLive(root);
442
- const questions = await listQuestions(root);
451
+ const states = new Map(
452
+ (
453
+ await d2States(projectDir, {
454
+ fired: verdictMatchers(projectDir, ledger, ledger.items),
455
+ limit: config.question_stale_after_commits,
456
+ })
457
+ ).map((s) => [s.id, s]),
458
+ );
459
+ // The class stays in the file; the screen shows the category (§2.7, decision 32).
460
+ const questions = (await listQuestions(root)).map((q) => questionRow(q, states.get(q.id)));
443
461
  const { units, design } = await designOf(projectDir, ledger, questions);
444
462
 
445
463
  return {
@@ -480,13 +498,7 @@ export async function board(projectDir) {
480
498
  inbox,
481
499
  // A lesson kind met in 3 runs or more: it rises to Needs you (decision 32).
482
500
  inbox_repeats: lessonRepeats(inbox),
483
- // The class stays in the file; the screen shows the category (§2.7, decision 32). An agent
484
- // writes every question record: its origin is one.
485
- questions: questions.map((q) => ({
486
- ...q,
487
- category: /^D1\b/.test(q.class ?? '') ? 'decision' : 'assumption',
488
- origin: 'agent',
489
- })),
501
+ questions,
490
502
  history: await historyOf(root),
491
503
  graveyard: await graveyardOf(root),
492
504
  units: unitsOf(units),
package/lib/changes.js CHANGED
@@ -9,6 +9,7 @@ import { isValidId } from './id.js';
9
9
  import { verifiedBranches, worktreeOf } from './integrate.js';
10
10
  import { branchState } from './push.js';
11
11
  import { refusal } from './refusal.js';
12
+ import { isInstruction } from './rules.js';
12
13
  import { fileState, newFileDiff, readHead } from './tree-file.js';
13
14
 
14
15
  // What a run leaves that is not work (the harness's NOT_WORK); all else unwanted is .gitignore's.
@@ -489,7 +490,12 @@ async function readTree(projectDir, asked) {
489
490
  return { tree, rows: rowsOf(tree, worktree), noDiff: await noDiffOf(projectDir) };
490
491
  }
491
492
 
492
- const outward = ({ modes: _m, xy: _x, openFrom: _o, ...row }) => row;
493
+ // `instructions`: a file an agent reads as its instructions (Lessons-Review-Plan d9), whoever wrote
494
+ // it: the board marks it. A rename marks from either side: one renamed away is gone from them.
495
+ const outward = ({ modes: _m, xy: _x, openFrom: _o, ...row }) =>
496
+ isInstruction(row.path) || (row.from && isInstruction(row.from))
497
+ ? { ...row, instructions: true }
498
+ : row;
493
499
 
494
500
  /**
495
501
  * What is uncommitted in the main checkout, or a run's worktree (`worktree`: its item's id).
@@ -167,6 +167,7 @@ function refuseGateRest(dir, names, subject) {
167
167
  rest,
168
168
  `cannot record ${subject} while gcf/ holds uncommitted changes: ${rest.join(', ')} — ` +
169
169
  'commit or discard them, then try again',
170
+ { message: subject, items: names.flatMap((n) => ITEM_PATH.exec(n)?.[1] ?? []) },
170
171
  );
171
172
  }
172
173
 
@@ -7,6 +7,8 @@ import { withFileRollback } from './safe-path.js';
7
7
  import { writeIndex } from './index-gen.js';
8
8
  import { operationInProgress, commitPaths, dirtyGcf, dirtyRefusal } from './git.js';
9
9
  import { withMainLock } from './main-lock.js';
10
+ import { planDrop, planGroup, untrackedEntries } from './inbox.js';
11
+ import { gcfRoot } from './gcf-paths.js';
10
12
 
11
13
  /** A file's text at a git revision spec (`HEAD:./x`, `:./x` for the index), '' when absent. */
12
14
  function gitText(projectDir, spec) {
@@ -23,7 +25,7 @@ function gitText(projectDir, spec) {
23
25
  * True when `file` differs from HEAD in the index or on disk. Line endings do not count: a file
24
26
  * stored with CRLF and checked out with LF is not an edit.
25
27
  */
26
- function uncommitted(projectDir, file) {
28
+ export function uncommitted(projectDir, file) {
27
29
  const rel = `./${path.relative(projectDir, file).replaceAll('\\', '/')}`;
28
30
  const norm = (t) => String(t).replace(/\r\n/g, '\n').trimEnd();
29
31
  const head = norm(gitText(projectDir, `HEAD:${rel}`));
@@ -44,7 +46,7 @@ export const onWorkBranch = (projectDir) =>
44
46
 
45
47
  /**
46
48
  * @typedef {{files: string[], mutate: () => Promise<unknown>, commit: boolean, inputs?: string[],
47
- * key?: string, items?: string[], proposal?: string}} Move
49
+ * key?: string, items?: string[], proposal?: string, reason?: string, empty?: boolean}} Move
48
50
  */
49
51
 
50
52
  /**
@@ -55,24 +57,67 @@ export const onWorkBranch = (projectDir) =>
55
57
  * their own uncommitted edits (an answer, a live: delta) ride along on purpose.
56
58
  * @param {string} projectDir
57
59
  * @param {string} message
58
- * `key` is the domain's move key, `items` the ids it touched and `proposal` the board's proposal
59
- * it carries out: the commit's trailers (moveTrailers).
60
+ * `key` is the domain's move key, `items` the ids it touched, `proposal` the board's proposal
61
+ * it carries out and `reason` why: the commit's trailers (moveTrailers). `empty`: it commits
62
+ * even with nothing to change, so its trailers stand (an erase of entries never committed).
60
63
  * @param {Move} move
61
64
  * @returns {Promise<string | null>} the commit's hash, null when it does not commit
62
65
  */
63
66
  export async function commitMove(projectDir, message, move) {
67
+ const { proposal, reason } = move;
68
+ if (proposal !== undefined && !/^[\w-]+\/[\w-]+$/.test(proposal))
69
+ throw new Error(`--proposal is <thread>/<proposal id>, not ${proposal}`);
70
+ // A trailer is one line: a line break in it would forge another.
71
+ if (reason !== undefined && /[\r\n]/.test(reason)) throw new Error('a reason is one line');
72
+
64
73
  // A move that commits holds the main lock while it writes and commits (Methodology §7).
65
74
  return move.commit
66
75
  ? withMainLock(projectDir, () => record(projectDir, message, move))
67
76
  : record(projectDir, message, move);
68
77
  }
69
78
 
79
+ /**
80
+ * A move that writes files of its own and erases inbox entries `move.ids` in one commit
81
+ * (Lessons-Review-Plan d3): `make` gives its `files` and how to `write` them, made under the main
82
+ * lock, as the entries' plans are, each checked before any is written. Entries never committed
83
+ * ride along, as with an inbox move. Returns the commit's hash.
84
+ * @param {string} projectDir
85
+ * @param {string} message
86
+ * @param {Omit<Move, 'files' | 'mutate' | 'inputs'> & {ids: string[]}} move
87
+ * `undo` takes back what `write` put outside the project's rollback, when the attempt fails.
88
+ * @param {() => Promise<{files: string[], write: () => Promise<unknown>,
89
+ * undo?: () => Promise<unknown>}>} make
90
+ */
91
+ export async function commitWithEntries(projectDir, message, { ids, ...move }, make) {
92
+ const go = async () => {
93
+ const { files, write, undo } = await make();
94
+ const drop = await planGroup(ids, (id) => planDrop(gcfRoot(projectDir), id));
95
+ const loose = move.commit ? untrackedEntries(projectDir) : [];
96
+
97
+ try {
98
+ return await commitMove(projectDir, message, {
99
+ ...move,
100
+ files: [...files, ...drop.files, ...loose],
101
+ inputs: [...files, ...drop.inputs, ...loose],
102
+ mutate: async () => {
103
+ await write();
104
+ await drop.apply();
105
+ },
106
+ });
107
+ } catch (e) {
108
+ // What it wrote outside the rollback goes in each failed attempt: one that waits behind a
109
+ // main run and goes again (withMainLock) starts from nothing written.
110
+ await undo?.();
111
+ throw e;
112
+ }
113
+ };
114
+
115
+ return move.commit ? withMainLock(projectDir, go) : go();
116
+ }
117
+
70
118
  /** @param {string} projectDir @param {string} message @param {Move} move */
71
- async function record(
72
- projectDir,
73
- message,
74
- { files, mutate, commit, inputs = [], key, items, proposal },
75
- ) {
119
+ async function record(projectDir, message, move) {
120
+ const { files, mutate, commit, inputs = [], items } = move;
76
121
  if (commit && onWorkBranch(projectDir))
77
122
  throw new Error(
78
123
  `cannot record ${message} on a work/ branch: a worktree records no move — the run ` +
@@ -93,6 +138,7 @@ async function record(
93
138
  rels.every((r) => all.includes(r)) ? all : [],
94
139
  `commit or stash these first (an answered unit is committed before its move), ` +
95
140
  `${message} would carry them: ${rels.join(', ')}`,
141
+ { message, items },
96
142
  );
97
143
  }
98
144
 
@@ -105,7 +151,7 @@ async function record(
105
151
  async () => {
106
152
  await mutate();
107
153
  await writeIndex(root);
108
- if (commit) hash = commitPaths(projectDir, message, touched, { key, items, proposal });
154
+ if (commit) hash = commitPaths(projectDir, message, touched, move);
109
155
  },
110
156
  { gitCwd: commit ? path.resolve(projectDir) : null },
111
157
  );