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/domain.js CHANGED
@@ -4,7 +4,9 @@
4
4
  // draws these and builds each command from `args` and `fields`; it hard-codes none of them.
5
5
  import { ITEM_MOVES, STORED } from './transitions.js';
6
6
  import { DEFAULT_GATE, GATES, ITEM_TYPES, SEVERITIES, UNIT_ITEM_TYPES } from './validate-item.js';
7
- import { BASE_CATEGORIES, mergeVocabulary, questionOnly } from './inbox-categories.js';
7
+ import { BASE_CATEGORIES, mergeVocabulary, questionOnly, REPORT_TO } from './inbox-categories.js';
8
+ import { DROP_REASONS } from './inbox.js';
9
+ import { INSTRUCTION_PATHS, RULE_FILES, RULE_MAX } from './rules.js';
8
10
  import { NOTE_MAX } from './work-ops.js';
9
11
  import { SESSION_TTL_MS } from './session-mark.js';
10
12
  import { RUN_MODES } from './gcf-paths.js';
@@ -188,7 +190,9 @@ const ITEM_SPECS = {
188
190
  label: 'model / effort',
189
191
  help: 'The model and effort of its runs: the next run takes them',
190
192
  args: ['gcf', 'item', 'agent', '{id}'],
191
- fields: [MODEL, EFFORT],
193
+ // `phase`: a board's Plan / Implement pick fills it, the phase's own then
194
+ // (Plan-Review-Rework-Plan d10); none, the item's own.
195
+ fields: [MODEL, EFFORT, text('phase', 'Phase: plan | implement', { hidden: true })],
192
196
  rare: true,
193
197
  },
194
198
  gates: {
@@ -283,11 +287,12 @@ const ITEM_SPECS = {
283
287
  { key: 'text', label: 'Blocks to replace', kind: 'longtext', stdin: true },
284
288
  { key: 'add', label: 'Lines to add to notes', kind: 'longtext', max: NOTE_MAX },
285
289
  text('title', 'Title'),
286
- text('from', 'Inbox entry it takes: erased'),
290
+ text('from', 'Inbox entry it takes: erased', { help: 'several of one cause as in-a,in-b' }),
287
291
  text('base', 'Read at', { hidden: true }),
288
292
  ],
289
293
  rare: true,
290
294
  propose: true,
295
+ proposal_trailer: true,
291
296
  // `--dry-run --json` says what it would change: a board shows that before the move.
292
297
  preview: true,
293
298
  // A human fixing a built card: the fix reaches its next run, not the code it has.
@@ -377,9 +382,20 @@ const NEW_ITEM = {
377
382
  max: NOTE_MAX,
378
383
  stdin: true,
379
384
  },
380
- // The inbox entry it comes from: the form fills it, the operator does not.
381
- text('from', 'From inbox entry', { hidden: true }),
385
+ // The inbox entries it comes from: the form fills it, the operator does not; an agent
386
+ // proposes the group it read (Lessons-Review-Plan d7).
387
+ {
388
+ key: 'from',
389
+ label: 'From inbox entries',
390
+ kind: 'ids',
391
+ inbox: true,
392
+ help: 'erased in its commit; several are a bullet each in its note, unless a note is given',
393
+ hidden: true,
394
+ propose: true,
395
+ },
382
396
  ],
397
+ // Its commit names the board's proposal it makes (`--proposal`): a recovery finds it by that.
398
+ proposal_trailer: true,
383
399
  };
384
400
 
385
401
  // A part of the design a save names (`gcf design part`): its kind, and the hash it was read at.
@@ -503,6 +519,16 @@ const PLAY_SAY =
503
519
  'command, or the folder is not ignored, propose a tech card with propose_item_new instead: one ' +
504
520
  'command builds the game into an ignored folder, one starts it with the folder and a port, ' +
505
521
  'AGENTS.md names both.';
522
+ // The files that steer an agent (rules.js INSTRUCTION_PATHS: a file as it is, a folder whole, no
523
+ // `:(exclude)` left, a plan is no review's to write either): a lessons review's
524
+ // agent writes none of them, by an edit or by a shell command that names one.
525
+ // shortcut: a command that spells a path another way (`.claude\x`, a variable, an assembled
526
+ // string) passes the shell rule, and native Windows has no Claude Code sandbox to stop it; the
527
+ // backstop is the board's Changes mark of dirty instruction files (`gcf changes` `instructions`).
528
+ // Upgrade when the agent runs in a sandbox that confines its writes.
529
+ const INSTRUCTION_EDITS = INSTRUCTION_PATHS.filter((p) => !p.startsWith(':')).map((p) =>
530
+ RULE_FILES.includes(p) ? p : `${p}/**`,
531
+ );
506
532
  const STARTS = {
507
533
  vision: {
508
534
  label: 'Create with agent',
@@ -621,6 +647,24 @@ const STARTS = {
621
647
  say: `${PLAY_SAY} The setup now and what went wrong: {text}`,
622
648
  edits: [],
623
649
  },
650
+ // A lessons review (Lessons-Review-Plan d1, d2): `{text}` the lesson ids, the board passes only
651
+ // inbox entries of category `entries`. Its agent proposes, the operator clicks; a rule goes
652
+ // through `rules add`, never an edit: `deny` holds under YOLO too. `next`: what the board's
653
+ // Next sends once the agent's turn with its cards is over (gcf-triage: "the human says next").
654
+ 'lessons-review': {
655
+ label: 'Review lessons',
656
+ help: 'The agent groups the lessons by cause and proposes one outcome a group: you click',
657
+ skill: 'gcf-triage',
658
+ takes: 'text',
659
+ entries: 'lesson',
660
+ say: 'Review the lessons {text} with me, group by group.',
661
+ edits: [],
662
+ deny: INSTRUCTION_EDITS.flatMap((pattern) => [
663
+ { kind: 'edit', pattern },
664
+ { kind: 'shell', pattern: `*${pattern.replace('/**', '/')}*` },
665
+ ]),
666
+ next: 'next',
667
+ },
624
668
  };
625
669
 
626
670
  // The way from an empty project to its first work, in order: the board shows each step done or
@@ -739,13 +783,28 @@ const BLOCK_SPECS = {
739
783
  ],
740
784
  propose: true,
741
785
  },
786
+ // A group of entries in one commit (Lessons-Review-Plan d3): `{ids}`, why in its commit.
742
787
  'inbox-drop': {
743
788
  label: 'erase',
744
- help: 'Noise: the entry is erased, nothing is made of it',
745
- args: ['gcf', 'inbox', 'drop', '{id}', '--commit'],
746
- fields: [],
789
+ help: 'Noise: the entries are erased, nothing is made of them',
790
+ args: ['gcf', 'inbox', 'drop', '{ids}', '--commit'],
791
+ fields: [
792
+ {
793
+ key: 'reason',
794
+ label: 'Why',
795
+ kind: 'choice',
796
+ options: [
797
+ { value: '', label: 'not said' },
798
+ ...Object.entries(DROP_REASONS).map(([value, help]) => ({ value, label: value, help })),
799
+ ],
800
+ },
801
+ text('of', 'Of: the item, entry or commit it duplicates or that did it', {
802
+ when: { key: 'reason', is: ['done', 'duplicate', 'reported', 'amended'] },
803
+ }),
804
+ ],
747
805
  danger: true,
748
806
  propose: true,
807
+ proposal_trailer: true,
749
808
  },
750
809
  'inbox-category': {
751
810
  label: 'sort',
@@ -757,10 +816,11 @@ const BLOCK_SPECS = {
757
816
  },
758
817
  'inbox-later': {
759
818
  label: 'later',
760
- help: 'Put the entry away to Later: nothing there asks for you now',
761
- args: ['gcf', 'inbox', 'later', '{id}', '--commit'],
819
+ help: 'Put the entries away to Later: nothing there asks for you now',
820
+ args: ['gcf', 'inbox', 'later', '{ids}', '--commit'],
762
821
  fields: [],
763
822
  propose: true,
823
+ proposal_trailer: true,
764
824
  },
765
825
  'inbox-back': {
766
826
  label: 'back',
@@ -768,6 +828,74 @@ const BLOCK_SPECS = {
768
828
  args: ['gcf', 'inbox', 'later', '{id}', '--off', '--commit'],
769
829
  fields: [],
770
830
  },
831
+ // The outcomes of a lessons review the core writes (Lessons-Review-Plan d5-d7): the human's
832
+ // moves, an agent proposes them. `preview`: a board shows their `--dry-run --json` (the rules'
833
+ // diff, the report's files) before the move.
834
+ 'rules-add': {
835
+ label: 'add rule',
836
+ help: 'A line under ## Project rules of AGENTS.md, and of a CLAUDE.md that does not import it',
837
+ args: ['gcf', 'rules', 'add', '--commit'],
838
+ fields: [
839
+ text('text', 'Rule: one line every agent of the project reads', {
840
+ required: true,
841
+ max: RULE_MAX,
842
+ }),
843
+ { key: 'from', label: 'Inbox entries it settles: erased', kind: 'ids', inbox: true },
844
+ // The board fills it from the dry run it showed: files changed since are refused.
845
+ text('base', 'Read at', { hidden: true }),
846
+ ],
847
+ propose: true,
848
+ proposal_trailer: true,
849
+ preview: true,
850
+ },
851
+ 'lessons-report': {
852
+ label: 'report',
853
+ help: 'Lessons about GCF or the template: a file each in ~/.gcf/lessons/, the entries erased',
854
+ args: ['gcf', 'lessons', 'report', '--commit'],
855
+ fields: [
856
+ { key: 'from', label: 'Lessons', kind: 'ids', required: true, inbox: true },
857
+ {
858
+ key: 'to',
859
+ label: 'To',
860
+ kind: 'choice',
861
+ required: true,
862
+ options: REPORT_TO.map((value) => ({ value, label: value })),
863
+ },
864
+ ],
865
+ propose: true,
866
+ proposal_trailer: true,
867
+ preview: true,
868
+ },
869
+ // The Rules screen's save (d8): the human's whole text of one file, GCF's block as it was read.
870
+ // The screen fills every field: `base` from `gcf rules --json`, so a file changed since is
871
+ // refused; the text goes on stdin. Its preview is the diff from HEAD.
872
+ 'rules-save': {
873
+ label: 'save rules',
874
+ help: "Save the human's text of AGENTS.md or CLAUDE.md; GCF's block stays as it is",
875
+ args: ['gcf', 'rules', 'save', '--commit'],
876
+ fields: [
877
+ {
878
+ key: 'file',
879
+ label: 'File',
880
+ kind: 'choice',
881
+ required: true,
882
+ hidden: true,
883
+ options: RULE_FILES.map((value) => ({ value, label: value })),
884
+ },
885
+ text('base', 'Read at', { required: true, hidden: true }),
886
+ // `clear`: an empty text is a value, a file with no block emptied.
887
+ {
888
+ key: 'text',
889
+ label: 'Text',
890
+ kind: 'longtext',
891
+ required: true,
892
+ clear: true,
893
+ stdin: true,
894
+ hidden: true,
895
+ },
896
+ ],
897
+ preview: true,
898
+ },
771
899
  // A chat's button to play: the board opens what it starts (docs/Play-Plan.md d17).
772
900
  play: {
773
901
  label: 'play',
@@ -962,7 +1090,9 @@ const SECTIONS = {
962
1090
  // `commit`: its `gcf changes commit` takes the operator's ticked files and message.
963
1091
  // `push`, `pull`: `gcf changes push|pull`, fast-forward only (docs/Push-Plan.md).
964
1092
  changes: { commit: true, push: true, pull: true },
965
- lessons: {},
1093
+ // A lessons review (Lessons-Review-Plan d1, d10): the start, and the moves of the manual strip
1094
+ // beside the inbox's own erase and Later.
1095
+ lessons: { review: 'lessons-review', rule: 'rules-add', report: 'lessons-report' },
966
1096
  playtest: {
967
1097
  // The inbox category a note from the playtest screen goes with.
968
1098
  category: 'playtest',
@@ -1033,6 +1163,9 @@ const CHANGES = [
1033
1163
  'inbox migrate',
1034
1164
  'inbox drop',
1035
1165
  'lessons add',
1166
+ 'lessons report',
1167
+ 'rules add',
1168
+ 'rules save',
1036
1169
  'config set',
1037
1170
  'permissions',
1038
1171
  'worktree',
package/lib/gcf-paths.js CHANGED
@@ -29,6 +29,16 @@ export const DEFAULT_CONFIG = {
29
29
  session_timeout_min: 120,
30
30
  };
31
31
 
32
+ // The phases of an item's run, each with its own model and effort (Plan-Review-Rework-Plan d10).
33
+ export const RUN_PHASES = ['plan', 'implement'];
34
+
35
+ // GCF's own model and effort of a phase: below the project's `agent.model|effort`, over the
36
+ // agent's defaults. The plan's author judges the review's findings: high.
37
+ export const PHASE_DEFAULTS = {
38
+ plan: { model: null, effort: 'high' },
39
+ implement: { model: null, effort: null },
40
+ };
41
+
32
42
  // A model or effort word as the agent's command line takes it; a leading hyphen would read as a
33
43
  // flag of it.
34
44
  export const RUN_WORD = /^[A-Za-z0-9][\w.-]*$/;
@@ -113,11 +123,12 @@ function gatesOf(v = {}) {
113
123
 
114
124
  // The review passes of a plan and of the code (Operator-Tasks-Plan t2 d1): row k makes pass k,
115
125
  // the next goes only while the last found something blocking; the rows over, the operator
116
- // decides. An empty list: no review of that kind.
126
+ // decides. An empty list: no review of that kind. The plan's first row makes the one full review,
127
+ // the rest check the author's fixes (Plan-Review-Rework-Plan d3, d9): the first runs high.
117
128
  export const REVIEW_AGENTS = ['claude', 'codex'];
118
129
  export const REVIEW_DEFAULTS = {
119
130
  plan: [
120
- { agent: 'codex', model: 'astra', effort: 'medium' },
131
+ { agent: 'codex', model: 'astra', effort: 'high' },
121
132
  { agent: 'claude', model: 'fable', effort: 'medium' },
122
133
  { agent: 'claude', model: 'fable', effort: 'medium' },
123
134
  ],
package/lib/git.js CHANGED
@@ -117,9 +117,39 @@ export const GATE_SCOPE = [
117
117
  * @param {Iterable<string>} [skip]
118
118
  */
119
119
  export function dirtyGcf(projectDir, skip = []) {
120
+ // A rename's old path is a deletion the gate sees too, so it goes with it (under gcf/).
121
+ const paths = dirtyIn(
122
+ projectDir,
123
+ GATE_SCOPE,
124
+ (old) => old.startsWith('gcf/') || old === 'GLOSSARY.md',
125
+ );
126
+ const off = new Set([...skip].map((p) => relOf(projectDir, p)));
127
+
128
+ return paths.filter((p) => !off.has(p));
129
+ }
130
+
131
+ /**
132
+ * Every path git sees changed under pathspecs `specs`, staged or not, or new, from the project
133
+ * with `/`, sorted. `renamedFrom`: whether a rename's old path counts too; a copy's never does.
134
+ * @param {string} projectDir
135
+ * @param {string[]} specs
136
+ * @param {(old: string) => boolean} [renamedFrom]
137
+ */
138
+ export function dirtyIn(projectDir, specs, renamedFrom = () => false) {
120
139
  const res = spawnSync(
121
140
  'git',
122
- ['-c', 'core.quotePath=false', 'status', '--porcelain', '-z', '-uall', '--', ...GATE_SCOPE],
141
+ // No index.lock: a move waiting behind a run asks this each second, and would break its commit.
142
+ [
143
+ '--no-optional-locks',
144
+ '-c',
145
+ 'core.quotePath=false',
146
+ 'status',
147
+ '--porcelain',
148
+ '-z',
149
+ '-uall',
150
+ '--',
151
+ ...specs,
152
+ ],
123
153
  { windowsHide: true, cwd: projectDir, encoding: 'utf8' },
124
154
  );
125
155
  if (res.status !== 0) return [];
@@ -136,28 +166,29 @@ export function dirtyGcf(projectDir, skip = []) {
136
166
  const rec = recs[i];
137
167
  if (rec.length < 4) continue;
138
168
  paths.push(ours(rec.slice(3)));
139
- // A rename or a copy: its old path is the next record. A rename's is a deletion the gate
140
- // sees too, so it goes with it (under gcf/); a copy's source is unchanged.
169
+ // A rename or a copy: its old path is the next record; a copy's source is unchanged.
141
170
  const xy = rec.slice(0, 2);
142
171
  if (!/[RC]/.test(xy)) continue;
143
172
  i++;
144
173
  const old = ours(recs[i] ?? '');
145
- if (xy.includes('R') && (old.startsWith('gcf/') || old === 'GLOSSARY.md')) paths.push(old);
174
+ if (xy.includes('R') && renamedFrom(old)) paths.push(old);
146
175
  }
147
176
 
148
- const off = new Set([...skip].map((p) => relOf(projectDir, p)));
149
-
150
- return [...new Set(paths)].filter((p) => !off.has(p)).sort();
177
+ return [...new Set(paths)].sort();
151
178
  }
152
179
 
153
180
  /**
154
181
  * The refusal of a move that uncommitted gcf/ edits stop: `dirty` with `paths` (dirtyGcf) when
155
- * there are any, so a board offers to show, commit or discard them; else the words alone.
182
+ * there are any, so a board offers to show, commit or discard them; else the words alone. `move`
183
+ * names the move it stops: one that waits behind a main run says it (lib/main-lock.js).
156
184
  * @param {string[]} paths
157
185
  * @param {string} message
186
+ * @param {{message: string, items?: string[]}} move
158
187
  */
159
- export const dirtyRefusal = (paths, message) =>
160
- paths.length ? refusal('dirty', { paths }, message) : new Error(message);
188
+ export const dirtyRefusal = (paths, message, move) =>
189
+ Object.assign(paths.length ? refusal('dirty', { paths }, message) : new Error(message), {
190
+ move: { ...move, items: move.items ?? [] },
191
+ });
161
192
 
162
193
  /** A path from the project with `/`, from an absolute one or one already relative. */
163
194
  const relOf = (projectDir, p) =>
@@ -230,11 +261,11 @@ export function needOperator(move, env = process.env) {
230
261
  /**
231
262
  * The trailer paragraph of a move's commit as `git commit`/`git merge` arguments (`gcf item
232
263
  * history` reads it): the items and units it touched, the domain's move key, who made it, and
233
- * the board's proposal it carries out (its recovery finds the move by it). A separate `-m`, not
234
- * `--trailer`: any git version takes it. None without a move key.
235
- * @param {{key?: string, items?: string[], proposal?: string}} [move]
264
+ * the board's proposal it carries out (its recovery finds the move by it), why it was made. A
265
+ * separate `-m`, not `--trailer`: any git version takes it. None without a move key.
266
+ * @param {{key?: string, items?: string[], proposal?: string, reason?: string}} [move]
236
267
  */
237
- export function moveTrailers({ key, items = [], proposal } = {}) {
268
+ export function moveTrailers({ key, items = [], proposal, reason } = {}) {
238
269
  if (!key) return [];
239
270
  const ids = [...new Set(items)];
240
271
  const lines = [
@@ -242,6 +273,7 @@ export function moveTrailers({ key, items = [], proposal } = {}) {
242
273
  `GCF-Move: ${key}`,
243
274
  `GCF-By: ${moveBy()}`,
244
275
  ...(proposal ? [`GCF-Proposal: ${proposal}`] : []),
276
+ ...(reason ? [`GCF-Reason: ${reason}`] : []),
245
277
  ];
246
278
 
247
279
  return ['-m', lines.join('\n')];
@@ -269,11 +301,13 @@ function commitRefusal(message, out) {
269
301
  * Stage and commit exactly `paths`: `git add -- gcf/` would stage a user's unrelated edits
270
302
  * under gcf/, and a rollback only restores what it snapshotted. A path that neither exists nor
271
303
  * is tracked is left out — git refuses a pathspec that matches nothing. `move` gives the
272
- * commit its trailers (moveTrailers). Returns the new HEAD.
304
+ * commit its trailers (moveTrailers); `empty` commits with nothing to change. Returns the new
305
+ * HEAD.
273
306
  * @param {string} projectDir
274
307
  * @param {string} message
275
308
  * @param {string[]} paths
276
- * @param {{key?: string, items?: string[], proposal?: string}} [move]
309
+ * @param {{key?: string, items?: string[], proposal?: string, reason?: string,
310
+ * empty?: boolean}} [move]
277
311
  */
278
312
  export function commitPaths(projectDir, message, paths, move = {}) {
279
313
  const staged = paths.filter((p) => existsSync(p) || tracked(projectDir, p));
@@ -288,7 +322,17 @@ export function commitPaths(projectDir, message, paths, move = {}) {
288
322
  // nothing: no pathspec.
289
323
  const real = paths.filter((p) => existsSync(p) || inHead(projectDir, p));
290
324
 
291
- return commitOnly(projectDir, message, real, ['-m', message, ...moveTrailers(move)]);
325
+ try {
326
+ return commitOnly(projectDir, message, real, [
327
+ '-m',
328
+ message,
329
+ ...moveTrailers(move),
330
+ ...(move.empty ? ['--allow-empty'] : []),
331
+ ]);
332
+ } catch (e) {
333
+ if (e.move) e.move.items = move.items ?? [];
334
+ throw e;
335
+ }
292
336
  }
293
337
 
294
338
  /**
@@ -327,6 +371,7 @@ export function commitOnly(projectDir, message, paths, msg) {
327
371
  loose,
328
372
  `cannot record ${message} while gcf/ holds uncommitted changes: ${loose.join(', ')} — ` +
329
373
  'commit or discard them, then try again',
374
+ { message },
330
375
  );
331
376
  }
332
377
 
@@ -59,6 +59,9 @@ export const ORIGINS = ['you', 'agent', 'automation'];
59
59
  /** The kinds of an agent's lesson (lib/lessons.js asks one question each): a lesson's details. */
60
60
  export const LESSON_KINDS = ['tool', 'rules', 'framework', 'template', 'other'];
61
61
 
62
+ /** Where `gcf lessons report` sends a lesson: the kinds the project's agent never fixes itself. */
63
+ export const REPORT_TO = ['framework', 'template'];
64
+
62
65
  /** A detail: one lowercase word after the category (`lesson:framework`, `request:asset`). */
63
66
  export const DETAIL = /^[a-z0-9][a-z0-9-]{0,29}$/;
64
67
 
package/lib/inbox.js CHANGED
@@ -437,14 +437,14 @@ export async function planDrop(root, id) {
437
437
 
438
438
  /**
439
439
  * Entry `id` taken into an item (`item new --from`): its title, its text, its pictures moved
440
- * into `toDir`, the entry erased. `files` names every path it touches, `inputs` the ones that
441
- * may carry edits not yet committed.
440
+ * into `toDir` (their names after `prefix`), the entry erased. `files` names every path it
441
+ * touches, `inputs` the ones that may carry edits not yet committed.
442
442
  */
443
- export async function planTake(root, id, toDir) {
443
+ export async function planTake(root, id, toDir, prefix = '') {
444
444
  const entry = await inboxEntry(root, id);
445
445
  const pictures = await filesUnder(attachDir(root, id));
446
446
  const from = attachDir(root, id);
447
- const moves = pictures.map((f) => [f, path.join(toDir, path.relative(from, f))]);
447
+ const moves = pictures.map((f) => [f, path.join(toDir, prefix + path.relative(from, f))]);
448
448
  const drop = await planDrop(root, id);
449
449
 
450
450
  return {
@@ -459,6 +459,71 @@ export async function planTake(root, id, toDir) {
459
459
  };
460
460
  }
461
461
 
462
+ // Why entries are erased, as `inbox drop --reason` takes it (Lessons-Review-Plan d3): the
463
+ // commit's subject and its GCF-Reason say it.
464
+ export const DROP_REASONS = {
465
+ done: 'what it asks for is done',
466
+ duplicate: 'another entry or a card says it already',
467
+ noise: 'nothing to make of it',
468
+ reported: 'reported to the framework or the template',
469
+ amended: 'its words went into a card',
470
+ };
471
+
472
+ /** The entries a move takes (`--from in-a,in-b`, or a list): each once, in the order given. */
473
+ export const entryIds = (from) =>
474
+ [
475
+ ...new Set(
476
+ (Array.isArray(from) ? from : String(from ?? '').split(',')).map((s) => String(s).trim()),
477
+ ),
478
+ ].filter(Boolean);
479
+
480
+ /**
481
+ * The plans of entries `ids` as one (Lessons-Review-Plan d3): each made before any applies, so
482
+ * one refused leaves every entry as it is.
483
+ * @param {string[]} ids
484
+ * @param {(id: string) => Promise<{files: string[], inputs?: string[],
485
+ * apply: () => Promise<unknown>}>} plan
486
+ */
487
+ export async function planGroup(ids, plan) {
488
+ const plans = [];
489
+ for (const id of new Set(ids)) plans.push(await plan(id));
490
+
491
+ return {
492
+ files: plans.flatMap((p) => p.files),
493
+ inputs: plans.flatMap((p) => p.inputs ?? p.files),
494
+ apply: async () => {
495
+ for (const p of plans) await p.apply();
496
+ },
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Entries `ids` taken into an item at once (Lessons-Review-Plan d3): each checked before any is
502
+ * written; with more than one, each picture's name starts with its entry's id, so two never
503
+ * clash. `relink(s, item)` points their links at the item's attachments.
504
+ */
505
+ export async function planTakeGroup(root, ids, toDir) {
506
+ const many = ids.length > 1;
507
+ const takes = [];
508
+ for (const id of ids) takes.push(await planTake(root, id, toDir, many ? `${id}-` : ''));
509
+
510
+ return {
511
+ entries: takes.map((t) => t.entry),
512
+ pictures: takes.flatMap((t) => t.pictures),
513
+ files: takes.flatMap((t) => t.files),
514
+ inputs: takes.flatMap((t) => t.inputs),
515
+ relink: (s, item) =>
516
+ ids.reduce(
517
+ (t, id) =>
518
+ t.replaceAll(`${id}/attachments/`, `${item}/attachments/${many ? `${id}-` : ''}`),
519
+ s,
520
+ ),
521
+ apply: async () => {
522
+ for (const t of takes) await t.apply();
523
+ },
524
+ };
525
+ }
526
+
462
527
  /**
463
528
  * Add an entry at once (planAdd), the operator's note unless `opts` say; returns it.
464
529
  * @param {string} root
package/lib/lessons.js CHANGED
@@ -4,13 +4,16 @@
4
4
  // any raw input and the
5
5
  // board shows where agents struggle. The questions stay out of the agent's working context until
6
6
  // the session ends: the harness asks them in one more turn, `/gcf-run` asks them at its close.
7
- import { readFile } from 'node:fs/promises';
7
+ import { mkdir, open, readFile, rm } from 'node:fs/promises';
8
+ import os from 'node:os';
8
9
  import path from 'node:path';
9
10
  import { uiLanguage } from './aif-config.js';
10
- import { readRawConfig } from './gcf-paths.js';
11
- import { planAdd } from './inbox.js';
12
- import { LESSON_KINDS } from './inbox-categories.js';
11
+ import { gcfRoot, readRawConfig } from './gcf-paths.js';
12
+ import { entryIds, inboxEntry, planAdd } from './inbox.js';
13
+ import { LESSON_KINDS, REPORT_TO } from './inbox-categories.js';
13
14
  import { isValidId } from './id.js';
15
+ import { extensionsOf } from './board.js';
16
+ import { commitWithEntries } from './commit-move.js';
14
17
 
15
18
  export const KINDS = LESSON_KINDS;
16
19
 
@@ -155,6 +158,132 @@ export async function addLessons(root, id, lessons) {
155
158
  return plan.entries;
156
159
  }
157
160
 
161
+ /** The account's folder of the board: GCF_BOARD_HOME, else `~/.gcf` (as gcf-board's homeDir). */
162
+ const boardHome = () => process.env.GCF_BOARD_HOME ?? path.join(os.homedir(), '.gcf');
163
+
164
+ // shortcut: the folder's name as the board names a project it adds, not the name the operator
165
+ // may have given it in the board; read ~/.gcf/projects.json when the two differ in use.
166
+ const projectName = (projectDir) =>
167
+ path
168
+ .basename(path.resolve(projectDir))
169
+ .toLowerCase()
170
+ .replace(/[^a-z0-9]+/g, '-')
171
+ .replace(/^-+|-+$/g, '') || 'project';
172
+
173
+ /**
174
+ * The versions a report names: this core's own, the harness the project lists, if any, and the
175
+ * board that runs the move (GCF_BOARD_VERSION, which gcf-board sets); none from a console.
176
+ */
177
+ async function versionsOf(projectDir) {
178
+ const own = new URL('../package.json', import.meta.url);
179
+ const { extensions } = await extensionsOf(projectDir);
180
+
181
+ return {
182
+ core: JSON.parse(await readFile(own, 'utf8')).version,
183
+ harness: extensions['gcf-harness-aif-ext'] ?? null,
184
+ board: process.env.GCF_BOARD_VERSION || null,
185
+ };
186
+ }
187
+
188
+ /** The file of one reported lesson: where it came from, then its words. */
189
+ function reportText(entry, { project, to, versions, date }) {
190
+ return [
191
+ `# ${entry.title}`,
192
+ '',
193
+ `- project: ${project}`,
194
+ `- lesson: ${entry.id}, kind ${entry.detail ?? 'other'}, to ${to}`,
195
+ `- item: ${entry.item ?? 'none'}`,
196
+ `- recorded: ${entry.at ?? 'unknown'}; reported: ${date}`,
197
+ `- core: ${versions.core}; harness: ${versions.harness ?? 'none'}; ` +
198
+ `board: ${versions.board ?? 'none'}`,
199
+ '',
200
+ entry.text,
201
+ '',
202
+ ].join('\n');
203
+ }
204
+
205
+ /**
206
+ * `gcf lessons report` (Lessons-Review-Plan d5): a file for each lesson of `from` in
207
+ * `<GCF_BOARD_HOME or ~/.gcf>/lessons/<to>/<project>-<id>.md`, for the GCF session or the
208
+ * template's agent to read; then the entries erased in one commit, reason `reported`. The core
209
+ * writes it, not the project's agent: GCF and the template stay out of its reach. Lessons only.
210
+ * `dryRun` gives the files and writes nothing.
211
+ * @public gcf.js imports lib modules by name at run time, out of knip's sight.
212
+ * @param {string} projectDir
213
+ * @param {{from?: string | string[], to: string, dryRun?: boolean, commit?: boolean,
214
+ * proposal?: string}} opts
215
+ */
216
+ export async function reportLessons(projectDir, { from, to, dryRun = false, commit, proposal }) {
217
+ if (!REPORT_TO.includes(to)) throw new Error(`--to is ${REPORT_TO.join(' | ')}, not ${to}`);
218
+ const ids = entryIds(from);
219
+ if (!ids.length) throw new Error('--from names the lessons to report');
220
+ const plan = async () => {
221
+ const root = gcfRoot(projectDir);
222
+ const entries = [];
223
+ for (const id of ids) entries.push(await inboxEntry(root, id));
224
+ const not = entries.filter((e) => e.category !== 'lesson').map((e) => e.id);
225
+ if (not.length) throw new Error(`${not.join(', ')}: not a lesson; only lessons are reported`);
226
+ const facts = {
227
+ project: projectName(projectDir),
228
+ to,
229
+ versions: await versionsOf(projectDir),
230
+ date: new Date().toISOString().slice(0, 10),
231
+ };
232
+ const dir = path.join(boardHome(), 'lessons', to);
233
+ const files = entries.map((e) => ({
234
+ path: path.join(dir, `${facts.project}-${e.id}.md`),
235
+ text: reportText(e, facts),
236
+ }));
237
+
238
+ return files;
239
+ };
240
+
241
+ if (dryRun) return { to, from: ids, files: await plan() };
242
+
243
+ return { to, from: ids, ...(await reportCommit(projectDir, ids, plan, { commit, proposal })) };
244
+ }
245
+
246
+ /**
247
+ * The report's files written, its entries erased in one commit; a failed attempt removes what it
248
+ * wrote. A report of a lesson still in the inbox is a leftover of an attempt stopped before its
249
+ * commit (a kill): written over, since a report that went through erased its lesson.
250
+ */
251
+ async function reportCommit(projectDir, ids, plan, { commit = true, proposal }) {
252
+ let files = [];
253
+ const move = { ids, commit, key: 'lessons-report', reason: 'reported', proposal, empty: true };
254
+ const hash = await commitWithEntries(
255
+ projectDir,
256
+ `gcf(inbox): drop ${ids.join(', ')} (reported)`,
257
+ move,
258
+ async () => {
259
+ files = await plan();
260
+ const made = [];
261
+
262
+ return {
263
+ files: [],
264
+ write: async () => {
265
+ for (const f of files) {
266
+ await mkdir(path.dirname(f.path), { recursive: true });
267
+ const handle = await open(f.path, 'w');
268
+ // Ours from its open: a write failing after it (ENOSPC) leaves a file undo removes.
269
+ made.push(f.path);
270
+ try {
271
+ await handle.writeFile(f.text);
272
+ } finally {
273
+ await handle.close();
274
+ }
275
+ }
276
+ },
277
+ undo: async () => {
278
+ for (const p of made.splice(0)) await rm(p, { force: true });
279
+ },
280
+ };
281
+ },
282
+ );
283
+
284
+ return { files: files.map((f) => f.path), hash };
285
+ }
286
+
158
287
  /**
159
288
  * The lessons of a JSON file: an array, as the harness writes it.
160
289
  * @public gcf.js imports lib modules by name at run time, out of knip's sight.