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/git.js CHANGED
@@ -117,6 +117,25 @@ 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
141
  // No index.lock: a move waiting behind a run asks this each second, and would break its commit.
@@ -129,7 +148,7 @@ export function dirtyGcf(projectDir, skip = []) {
129
148
  '-z',
130
149
  '-uall',
131
150
  '--',
132
- ...GATE_SCOPE,
151
+ ...specs,
133
152
  ],
134
153
  { windowsHide: true, cwd: projectDir, encoding: 'utf8' },
135
154
  );
@@ -147,18 +166,15 @@ export function dirtyGcf(projectDir, skip = []) {
147
166
  const rec = recs[i];
148
167
  if (rec.length < 4) continue;
149
168
  paths.push(ours(rec.slice(3)));
150
- // A rename or a copy: its old path is the next record. A rename's is a deletion the gate
151
- // 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.
152
170
  const xy = rec.slice(0, 2);
153
171
  if (!/[RC]/.test(xy)) continue;
154
172
  i++;
155
173
  const old = ours(recs[i] ?? '');
156
- if (xy.includes('R') && (old.startsWith('gcf/') || old === 'GLOSSARY.md')) paths.push(old);
174
+ if (xy.includes('R') && renamedFrom(old)) paths.push(old);
157
175
  }
158
176
 
159
- const off = new Set([...skip].map((p) => relOf(projectDir, p)));
160
-
161
- return [...new Set(paths)].filter((p) => !off.has(p)).sort();
177
+ return [...new Set(paths)].sort();
162
178
  }
163
179
 
164
180
  /**
@@ -245,11 +261,11 @@ export function needOperator(move, env = process.env) {
245
261
  /**
246
262
  * The trailer paragraph of a move's commit as `git commit`/`git merge` arguments (`gcf item
247
263
  * history` reads it): the items and units it touched, the domain's move key, who made it, and
248
- * the board's proposal it carries out (its recovery finds the move by it). A separate `-m`, not
249
- * `--trailer`: any git version takes it. None without a move key.
250
- * @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]
251
267
  */
252
- export function moveTrailers({ key, items = [], proposal } = {}) {
268
+ export function moveTrailers({ key, items = [], proposal, reason } = {}) {
253
269
  if (!key) return [];
254
270
  const ids = [...new Set(items)];
255
271
  const lines = [
@@ -257,6 +273,7 @@ export function moveTrailers({ key, items = [], proposal } = {}) {
257
273
  `GCF-Move: ${key}`,
258
274
  `GCF-By: ${moveBy()}`,
259
275
  ...(proposal ? [`GCF-Proposal: ${proposal}`] : []),
276
+ ...(reason ? [`GCF-Reason: ${reason}`] : []),
260
277
  ];
261
278
 
262
279
  return ['-m', lines.join('\n')];
@@ -284,11 +301,13 @@ function commitRefusal(message, out) {
284
301
  * Stage and commit exactly `paths`: `git add -- gcf/` would stage a user's unrelated edits
285
302
  * under gcf/, and a rollback only restores what it snapshotted. A path that neither exists nor
286
303
  * is tracked is left out — git refuses a pathspec that matches nothing. `move` gives the
287
- * commit its trailers (moveTrailers). Returns the new HEAD.
304
+ * commit its trailers (moveTrailers); `empty` commits with nothing to change. Returns the new
305
+ * HEAD.
288
306
  * @param {string} projectDir
289
307
  * @param {string} message
290
308
  * @param {string[]} paths
291
- * @param {{key?: string, items?: string[], proposal?: string}} [move]
309
+ * @param {{key?: string, items?: string[], proposal?: string, reason?: string,
310
+ * empty?: boolean}} [move]
292
311
  */
293
312
  export function commitPaths(projectDir, message, paths, move = {}) {
294
313
  const staged = paths.filter((p) => existsSync(p) || tracked(projectDir, p));
@@ -304,7 +323,12 @@ export function commitPaths(projectDir, message, paths, move = {}) {
304
323
  const real = paths.filter((p) => existsSync(p) || inHead(projectDir, p));
305
324
 
306
325
  try {
307
- return commitOnly(projectDir, message, real, ['-m', message, ...moveTrailers(move)]);
326
+ return commitOnly(projectDir, message, real, [
327
+ '-m',
328
+ message,
329
+ ...moveTrailers(move),
330
+ ...(move.empty ? ['--allow-empty'] : []),
331
+ ]);
308
332
  } catch (e) {
309
333
  if (e.move) e.move.items = move.items ?? [];
310
334
  throw e;
@@ -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.