gcf-aif-ext 0.22.1 → 0.24.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.
@@ -59,8 +59,14 @@ export function putBlock(lines, specs, spec, rendered, { raw = false } = {}) {
59
59
  // Header fields stand line under line; a block stands apart from its neighbours.
60
60
  const tight = (b) => Boolean(spec.header && header(b));
61
61
  const prev = blocks.filter((b) => order.indexOf(b.key) < order.indexOf(spec.key)).at(-1);
62
- if (!prev)
63
- return blocks.length ? [...rendered, ...(tight(blocks[0]) ? [] : ['']), ...lines] : rendered;
62
+ if (!prev && blocks.length) return [...rendered, ...(tight(blocks[0]) ? [] : ['']), ...lines];
63
+ if (!prev) {
64
+ // A body of words with no block keeps them, over the new one.
65
+ const last = lines.findLastIndex((l) => l.trim());
66
+
67
+ return last < 0 ? rendered : [...lines.slice(0, last + 1), '', ...rendered, ''];
68
+ }
69
+
64
70
  const tail = lines.slice(prev.end);
65
71
  const gap = tight(prev) ? [] : [''];
66
72
  const after = !tight(prev) && tail[0]?.trim() ? [''] : [];
@@ -97,11 +103,53 @@ export function upsertBlock(rawBody, key, addLines, order) {
97
103
  while (lines.length > 1 && !lines[0].trim()) lines.shift();
98
104
  while (lines.length > 1 && !lines.at(-1).trim() && !lines.at(-2).trim()) lines.pop();
99
105
  }
106
+
100
107
  const put = putBlock(lines, specs, { key }, [`${key}:`, ...kept, ...fresh], { raw: true });
101
108
 
102
109
  return `${lead}${put.join('\n')}`.replace(/\n{3,}/g, '\n\n');
103
110
  }
104
111
 
112
+ /**
113
+ * The blocks a text names, each with its lines as written, and `outside`: its first line with
114
+ * words that stand in no block, or null. `lines` empty: only its key, with no value or item.
115
+ * @param {string} rawText
116
+ */
117
+ export function blocksNamed(rawText) {
118
+ const text = lf(rawText);
119
+ const raw = text.split('\n');
120
+ const blocks = blocksOf(text, { raw: true });
121
+ const inBlock = (n) => blocks.some((b) => n >= b.start && n <= b.end);
122
+ const outside = parseBlocks(text).lines.findIndex((l, i) => l.trim() && !inBlock(i + 1));
123
+ const lines = (b) => {
124
+ const own = raw.slice(b.start - 1, b.end);
125
+
126
+ return own.length === 1 && !String(b.value ?? '').trim() ? [] : own;
127
+ };
128
+
129
+ return {
130
+ blocks: blocks.map((b) => ({ key: b.key, lines: lines(b) })),
131
+ outside: outside < 0 ? null : raw[outside],
132
+ };
133
+ }
134
+
135
+ /**
136
+ * The body with block `key` set to `rendered`: in place, or where `order` (the profile's block
137
+ * keys, see blockOrder) puts a new one; `rendered` empty takes it out.
138
+ * @param {string} rawBody
139
+ * @param {string} key
140
+ * @param {string[]} rendered
141
+ * @param {string[]} order
142
+ */
143
+ export function replaceBlock(rawBody, key, rendered, order) {
144
+ const body = lf(rawBody);
145
+ const specs = (order.includes(key) ? order : [...order, key]).map((k) => ({ key: k }));
146
+ const lead = body.match(/^\n*/)[0];
147
+ const lines = body.slice(lead.length).split('\n');
148
+ const put = putBlock(lines, specs, { key }, rendered, { raw: true });
149
+
150
+ return `${lead}${put.join('\n')}`.replace(/\n{3,}/g, '\n\n');
151
+ }
152
+
105
153
  /**
106
154
  * The `key:` bullet block without `dropLines` — the inverse of upsertBlock. A block left empty
107
155
  * gets the `- none:` placeholder back, as a new systems doc starts.
@@ -38,6 +38,8 @@ const FROM = {
38
38
  mode: STORED,
39
39
  // Nor its card's gates: they hold its next move.
40
40
  gates: STORED,
41
+ // Nor a fix of its text; only an unplayed body is frozen (§5.4).
42
+ amend: STORED.filter((s) => s !== 'unplayed'),
41
43
  };
42
44
 
43
45
  /** Every move an item may be offered, in the board's order. */
package/lib/work-ops.js CHANGED
@@ -16,7 +16,7 @@ import { allowedFrom, decisionFits, FEATURE_ONLY, fromOf } from './transitions.j
16
16
  import { ITEM_TYPES, DEFAULT_GATE, GATES, SEVERITIES, UNIT_ITEM_TYPES } from './validate-item.js';
17
17
  import { deriveId, isValidId } from './id.js';
18
18
  import { commitMove, addConstraints, onWorkBranch } from './unit-ops.js';
19
- import { openSystemDoc, upsertBlock } from './systems-doc.js';
19
+ import { blocksNamed, blocksOf, openSystemDoc, replaceBlock, upsertBlock } from './systems-doc.js';
20
20
  import { blockOrder } from './design.js';
21
21
  import {
22
22
  collapseLines,
@@ -41,6 +41,7 @@ import { cycleMessage, dependsGraph, gameMilestones, pathTo } from './design-che
41
41
  import { refuseByPhase } from './phase.js';
42
42
  import { locked, runHolder } from './main-lock.js';
43
43
  import { dropAgentSession, ownsMark, releaseSession, sessionActive } from './session-mark.js';
44
+ import { clearCard, inSwitch, isShelved, leaveFolder, wholeOnShelf } from './shelf.js';
44
45
  import { dropStamp, unverifiedProblem } from './verify-stamp.js';
45
46
  import { planTicks } from './plan-check.js';
46
47
  import {
@@ -54,6 +55,7 @@ import {
54
55
  } from './git.js';
55
56
  import { verdictDeferred } from './gates.js';
56
57
  import { appendQuestions, questionsFile } from './questions.js';
58
+ import { refusal } from './refusal.js';
57
59
 
58
60
  /**
59
61
  * Options of a committed move; each move reads the ones it needs.
@@ -204,14 +206,15 @@ function refuseRunning(projectDir, id, self = process.env.GCF_RUN_ITEM ?? null)
204
206
  * Open a move on item `id` from the statuses `move` allows: the files it touches, its steps,
205
207
  * and the LIVE.md edits folded into a single write at the end.
206
208
  */
207
- async function begin(projectDir, id, move) {
209
+ async function begin(projectDir, id, move, refuse = refuseRunning) {
208
210
  const root = gcfOf(projectDir);
209
211
  const ledger = await buildLedger(projectDir);
210
212
  const item = itemOf(ledger, id);
211
213
  need(move, item);
212
- refuseRunning(projectDir, id);
214
+ refuse(projectDir, id);
213
215
  const files = [item.file];
214
216
  const steps = [];
217
+ const after = [];
215
218
  const liveOps = [];
216
219
 
217
220
  return {
@@ -219,13 +222,18 @@ async function begin(projectDir, id, move) {
219
222
  root,
220
223
  ledger,
221
224
  item,
225
+ ran: after,
222
226
  /** @type {Set<string>} ids leaving systems/ in this move */
223
227
  leaving: new Set(),
224
228
  /** @type {Set<string>} every item the move touches, for its commit's GCF-Items */
225
229
  items: new Set([id]),
226
230
  files,
231
+ /** @type {string[]} the files it may carry with edits not yet committed */
232
+ inputs: [item.file],
227
233
  touch: (...f) => files.push(...f.filter((x) => !files.includes(x))),
228
234
  step: (fn) => steps.push(fn),
235
+ /** After the commit: refs that hold work go only once the move stands. */
236
+ after: (fn) => after.push(fn),
229
237
  live: (fn) => {
230
238
  if (!files.includes(liveFile(root))) files.push(liveFile(root));
231
239
  liveOps.push(fn);
@@ -250,7 +258,7 @@ async function finish(m, key, tail, commit) {
250
258
  files: m.files,
251
259
  mutate: m.run,
252
260
  commit,
253
- inputs: [m.item.file],
261
+ inputs: m.inputs,
254
262
  key,
255
263
  items: [...m.items],
256
264
  });
@@ -259,10 +267,35 @@ async function finish(m, key, tail, commit) {
259
267
  releaseSession(m.projectDir, String(m.item.data.id));
260
268
  dropAgentSession(m.projectDir, String(m.item.data.id));
261
269
  dropStamp(m.projectDir, String(m.item.data.id));
270
+ // A caller that commits later cleans up after it: a refused commit rolls the files back, and
271
+ // refs gone by then would not come back.
272
+ if (commit === false) return hash;
273
+ // Its work is committed: what still lies loose is no longer the card's to carry.
274
+ if (move === 'submit' || move === 'close') leaveFolder(m.projectDir, String(m.item.data.id));
275
+ for (const fn of m.ran) fn();
262
276
 
263
277
  return hash;
264
278
  }
265
279
 
280
+ /** A card's work waits on its branch: it has to come back before it can be judged. */
281
+ function needInFolder(m, item = m.item) {
282
+ const id = String(item.data.id);
283
+ if (!isShelved(m.projectDir, id)) return;
284
+ const reason = `its work is shelved on work/${id}: run it, or gcf claim ${id}, to bring it back`;
285
+ throw refusal('shelve', { reason }, `${id}: ${reason}`);
286
+ }
287
+
288
+ /**
289
+ * A card that ends while a switch moves its work: the switch would finish after, and leave its
290
+ * branch and refs for no card at all, with nothing to take them away.
291
+ */
292
+ function needNoSwitch(m, item) {
293
+ const id = String(item.data.id);
294
+ if (!inSwitch(m.projectDir, id)) return;
295
+ const reason = `a switch of its work has not finished: gcf claim ${id} finishes it`;
296
+ throw refusal('shelve', { reason }, `${id}: ${reason}`);
297
+ }
298
+
266
299
  /**
267
300
  * `close` and `submit` from a command (Methodology §6): the code as it is now needs a green
268
301
  * `gcf verify`, unless the operator says why not (`unverified`, written into the move's
@@ -456,6 +489,9 @@ const detailOf = (item, archived) =>
456
489
  */
457
490
  function endToHistory(m, item, event, { applyLive = true } = {}) {
458
491
  const id = String(item.data.id);
492
+ // Accepted with its work on a branch, the branch would go and the work with it.
493
+ needInFolder(m, item);
494
+ needNoSwitch(m, item);
459
495
  if (item.data.type === 'release') recordRelease(m, item);
460
496
  m.touch(path.join(m.root, 'history.md'));
461
497
  m.step(() => recordLine(m.root, id, event));
@@ -467,6 +503,7 @@ function endToHistory(m, item, event, { applyLive = true } = {}) {
467
503
 
468
504
  dropKnownIssue(m, id);
469
505
  m.step(() => unlink(item.file));
506
+ m.after(() => clearCard(m.projectDir, id));
470
507
  }
471
508
 
472
509
  /**
@@ -548,6 +585,7 @@ function endToGraveyard(
548
585
  const id = String(item.data.id);
549
586
  const why = String(reason ?? '').trim();
550
587
  if (!why) throw new Error(`${id}: the graveyard keeps a reason — give one`);
588
+ needNoSwitch(m, item);
551
589
  m.touch(path.join(m.root, 'graveyard.md'), item.file);
552
590
  // A feature's kill takes its live children down in the same commit.
553
591
  m.items.add(id);
@@ -559,6 +597,7 @@ function endToGraveyard(
559
597
  if (!quiet) parentWaits(m, item);
560
598
  const removed = removal ? removalItem(m, item, why) : null;
561
599
  m.step(() => unlink(item.file));
600
+ m.after(() => clearCard(m.projectDir, id));
562
601
 
563
602
  return removed;
564
603
  }
@@ -569,19 +608,29 @@ function endToGraveyard(
569
608
  * code was committed. `--no-remove` overrides it.
570
609
  */
571
610
  const IN_MAIN = ['awaiting-verdict', 'awaiting-decision', 'unplayed', 'blocked', 'parked'];
572
- const codeInMain = (item) =>
611
+ const codeInMain = (projectDir, item) =>
573
612
  item.data.type !== 'spike' &&
574
- (IN_MAIN.includes(item.data.status) || (item.data.tune_count ?? 0) > 0);
613
+ (IN_MAIN.includes(item.data.status) || (item.data.tune_count ?? 0) > 0) &&
614
+ !shelvedWhole(projectDir, item);
615
+
616
+ /**
617
+ * A card whose code never reached main: all of it sits on its shelf, and goes with it. Only a
618
+ * shelve says so: a tuned card's earlier build is on main.
619
+ */
620
+ const shelvedWhole = (projectDir, item) =>
621
+ !(item.data.tune_count > 0) && wholeOnShelf(projectDir, String(item.data.id));
575
622
 
576
623
  /**
577
624
  * A feature's own status says nothing about its code: it is in main when a child ended
578
625
  * accepted, or a live child's code is.
579
626
  */
580
- const featureShipped = (ledger, feature) =>
627
+ const featureShipped = (projectDir, ledger, feature) =>
581
628
  (feature.data.children ?? []).some((c) => {
582
629
  const child = ledger.item(c);
583
630
 
584
- return child ? codeInMain(child) : ledger.where(c).terminal.some((t) => t !== 'killed');
631
+ return child
632
+ ? codeInMain(projectDir, child)
633
+ : ledger.where(c).terminal.some((t) => t !== 'killed');
585
634
  });
586
635
 
587
636
  function refuseOpenDepends(m, move, opts = {}) {
@@ -660,6 +709,7 @@ async function submitItemUnlocked(projectDir, id, opts = {}) {
660
709
  const changes = playChanges(m.item);
661
710
  // Unplayed needs its dependencies played, as a close does: not one still waiting (§4.1).
662
711
  refuseOpenDepends(m, 'submit', { waiting: !deferred || changes.length > 0 });
712
+ needInFolder(m);
663
713
  needTicked(m, opts);
664
714
  needVerified(m, opts);
665
715
  assumeInto(m, opts.assume);
@@ -751,6 +801,7 @@ async function closeItemUnlocked(projectDir, id, opts = {}) {
751
801
  throw new Error(`${id} has gate ${m.item.data.gate}: submit it, the operator closes it`);
752
802
  // A4: it will wait for a verdict, so a dependency waiting for its own is no bar.
753
803
  refuseOpenDepends(m, 'close', { waiting: changes.length > 0 });
804
+ needInFolder(m);
754
805
  needTicked(m, opts);
755
806
  needVerified(m, opts);
756
807
  if (changes.length) awaitVerdict(m, `modifies ${changes.join(', ')}`);
@@ -966,6 +1017,7 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
966
1017
  const files = changedIn(projectDir).map((c) => path.join(projectDir, c.file));
967
1018
  const message = `gcf(verdict): keep ${name} → ${order.join(', ')}${played}`;
968
1019
  const hash = commitPaths(projectDir, message, files, { key: 'verdict:keep', items: order });
1020
+ for (const id of order) clearCard(projectDir, id);
969
1021
 
970
1022
  return { milestone: name, ids: order, hash };
971
1023
  } catch (e) {
@@ -990,7 +1042,7 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
990
1042
  /** decide kill: the live children go down with the feature, without removal items of their own. */
991
1043
  function killFeature(m, { reason, remove }) {
992
1044
  const { item, ledger } = m;
993
- const shipped = featureShipped(ledger, item);
1045
+ const shipped = featureShipped(m.projectDir, ledger, item);
994
1046
  const children = (item.data.children ?? []).map((c) => ledger.item(c)).filter(Boolean);
995
1047
  // A child's file goes with the feature: an agent working it would lose it mid-run.
996
1048
  // No session kills its own item through its feature: the claimed child counts as running too.
@@ -1018,12 +1070,16 @@ function park(m) {
1018
1070
  const DECIDE = {
1019
1071
  go: (m) => endToHistory(m, m.item, 'decided') ?? null,
1020
1072
  no: (m, o) =>
1021
- endToGraveyard(m, m.item, { reason: o.reason, removal: o.remove ?? codeInMain(m.item) }),
1073
+ endToGraveyard(m, m.item, {
1074
+ reason: o.reason,
1075
+ removal: o.remove ?? codeInMain(m.projectDir, m.item),
1076
+ }),
1022
1077
  // A bug not to be fixed has fix code in main only when a started fix got blocked.
1023
1078
  wontfix: (m, o) =>
1024
1079
  endToGraveyard(m, m.item, {
1025
1080
  reason: o.reason,
1026
- removal: o.remove ?? m.item.data.status === 'blocked',
1081
+ removal:
1082
+ o.remove ?? (m.item.data.status === 'blocked' && !shelvedWhole(m.projectDir, m.item)),
1027
1083
  }),
1028
1084
  known: park,
1029
1085
  close: (m) => closeFeature(m) ?? null,
@@ -1107,6 +1163,181 @@ async function unblockItemUnlocked(projectDir, id, opts = {}) {
1107
1163
  return { id, hash: await finish(m, 'unblock', id, commit) };
1108
1164
  }
1109
1165
 
1166
+ // The blocks `amend` leaves alone: where the card came from, and the record of its verdicts.
1167
+ const NOT_AMENDED = ['provenance', 'tuning'];
1168
+
1169
+ /** Refuse a fix of the text a live run reads, in words a person can act on. */
1170
+ function refuseAmendLive(projectDir, id) {
1171
+ if (!runHolder(projectDir, id) && !sessionActive(projectDir, id)) return;
1172
+ throw refusal(
1173
+ 'running',
1174
+ {},
1175
+ `${id} is being worked on right now, and that agent reads this text: tell it through the ` +
1176
+ 'chat of its run, or amend the card once the run has ended',
1177
+ );
1178
+ }
1179
+
1180
+ /** The hash of what a card's form shows: an edit of its text since then is not overwritten. */
1181
+ const amendBase = ({ data, body }) =>
1182
+ createHash('sha1')
1183
+ .update(`${data.title ?? ''}\n${String(body).replace(/\r\n/g, '\n').trim()}`)
1184
+ .digest('hex');
1185
+
1186
+ /** The card's text a human edits: the blocks `amend` may replace. */
1187
+ const amendableText = (body) => {
1188
+ const text = NOT_AMENDED.reduce((t, key) => replaceBlock(t, key, [], []), body);
1189
+ const lines = text.split('\n');
1190
+
1191
+ // The blocks alone: words outside them stay in the card, and a text may not name them.
1192
+ return blocksOf(text, { raw: true })
1193
+ .map((b) => lines.slice(b.start - 1, b.end).join('\n'))
1194
+ .join('\n\n');
1195
+ };
1196
+
1197
+ /** The lines of each block of a body, by key. */
1198
+ const blockLinesOf = (body) => {
1199
+ const lines = String(body).split('\n');
1200
+
1201
+ return new Map(
1202
+ blocksOf(body, { raw: true }).map((b) => [b.key, lines.slice(b.start - 1, b.end)]),
1203
+ );
1204
+ };
1205
+
1206
+ /** What a fix changes, block by block, in the order of the new text. */
1207
+ function amendChanges(item, title, body) {
1208
+ const before = blockLinesOf(String(item.body).replace(/\r\n/g, '\n'));
1209
+ const after = blockLinesOf(body);
1210
+ const same = (a = [], b = []) => a.join('\n') === b.join('\n');
1211
+ const keys = [...after.keys(), ...[...before.keys()].filter((k) => !after.has(k))];
1212
+ const was = item.data.title ?? '';
1213
+
1214
+ return [
1215
+ ...(title === was ? [] : [{ block: 'title', old: was ? [was] : [], new: [title] }]),
1216
+ ...keys
1217
+ .filter((k) => !same(before.get(k), after.get(k)))
1218
+ .map((k) => ({ block: k, old: before.get(k) ?? [], new: after.get(k) ?? [] })),
1219
+ ];
1220
+ }
1221
+
1222
+ /** `text`, in block syntax, over `body`: the blocks it names, none the card must keep. */
1223
+ function replaceNamed(body, text, item, order) {
1224
+ const { blocks, outside } = blocksNamed(text);
1225
+ if (outside !== null)
1226
+ throw new Error(
1227
+ `the text has a line outside its blocks: "${outside}" — a block starts with its key at the ` +
1228
+ 'start of a line, e.g. check:',
1229
+ );
1230
+ if (!blocks.length) throw new Error('the text names no block: a block starts with its key');
1231
+ const named = blocks.map((b) => b.key);
1232
+ const twice = named.find((k, i) => named.indexOf(k) !== i);
1233
+ if (twice) throw new Error(`the text names block ${twice}: twice`);
1234
+ const kept = named.find((k) => NOT_AMENDED.includes(k));
1235
+ if (kept)
1236
+ throw new Error(`${kept}: stays as it is: an amend changes neither provenance: nor tuning:`);
1237
+ const alien = order && named.find((k) => !order.includes(k));
1238
+ if (alien)
1239
+ throw new Error(
1240
+ `a ${item.data.type} has no block ${alien}: its blocks are ${order.join(', ')}`,
1241
+ );
1242
+
1243
+ return blocks.reduce((b, { key, lines }) => replaceBlock(b, key, lines, order ?? []), body);
1244
+ }
1245
+
1246
+ /** The inbox entry a fix takes: its words for `notes:`, its pictures to the card, one by one. */
1247
+ async function amendEntry(projectDir, m, from) {
1248
+ if (onWorkBranch(projectDir))
1249
+ throw new Error('an inbox entry is taken on main: a work/ branch records no inbox move');
1250
+ const id = String(m.item.data.id);
1251
+ const take = await planTake(m.root, from, path.join(m.root, 'work', id, 'attachments'));
1252
+ const taken = take.pictures.filter((f) => existsSync(f)).map((f) => path.basename(f));
1253
+ if (taken.length)
1254
+ throw new Error(`gcf/work/${id}/attachments/ already holds ${taken.join(', ')}: rename it`);
1255
+ const relink = (s) => s.replaceAll(`${from}/attachments/`, `${id}/attachments/`);
1256
+ const lines = take.entry.text.split('\n');
1257
+ const rest = lines
1258
+ .slice(lines.findIndex((l) => l.trim()) + 1)
1259
+ .join('\n')
1260
+ .trim();
1261
+
1262
+ // An entry of one line is its title: nothing of what it says may be lost with it.
1263
+ return { ...take, note: relink(rest || take.entry.title), relink };
1264
+ }
1265
+
1266
+ /**
1267
+ * Fix a live card's text (docs/Amend-Plan.md): `text` replaces the blocks it names, `add` goes to
1268
+ * `notes:`, `title` replaces the title, `from` takes an inbox entry in the same commit. Its status
1269
+ * stays; a finding on the new text comes from the pre-commit gate, with its rollback. `dryRun`
1270
+ * writes nothing and may read a card a run holds: a form and a proposal show it.
1271
+ * @param {string} projectDir
1272
+ * @param {string} id
1273
+ * @param {{text?: string, add?: string, title?: string, from?: string, base?: string,
1274
+ * dryRun?: boolean, commit?: boolean}} [opts]
1275
+ */
1276
+ async function amendItemUnlocked(projectDir, id, opts = {}) {
1277
+ const { dryRun = false, commit = true } = opts;
1278
+ const asked = amendAsked(opts);
1279
+ const m = await begin(projectDir, id, 'amend', dryRun ? () => {} : refuseAmendLive);
1280
+ const entry = asked.from ? await amendEntry(projectDir, m, asked.from) : null;
1281
+ const { body, title } = await amendedCard(m.item, asked, entry);
1282
+ const changes = amendChanges(m.item, title, body);
1283
+ if (dryRun) return { id, base: amendBase(m.item), title, text: amendableText(body), changes };
1284
+ refuseAmendPointless(m.item, { asked, base: opts.base, changes, entry });
1285
+ if (entry) carryEntry(m, entry, commit);
1286
+ const data = asked.title ? { ...m.item.data, title } : m.item.data;
1287
+ m.step(() => writeItem(m.item, data, body));
1288
+
1289
+ return { id, changes, hash: await finish(m, 'amend', id, commit) };
1290
+ }
1291
+
1292
+ /** What a fix asks for, trimmed: a blank field is none, an over-long or broken one refused. */
1293
+ function amendAsked(opts) {
1294
+ const [text, add, title, from] = [opts.text, opts.add, opts.title, opts.from].map((v) =>
1295
+ String(v ?? '').trim(),
1296
+ );
1297
+ if (add.length > NOTE_MAX)
1298
+ throw new Error(`the lines to add are ${add.length} characters: up to ${NOTE_MAX}`);
1299
+ if (/[\r\n]/.test(title)) throw new Error('--title is one line');
1300
+
1301
+ return { text, add, title, from };
1302
+ }
1303
+
1304
+ /** The card's title and body after a fix: the blocks named, then the lines added. */
1305
+ async function amendedCard(item, { text, add, title }, entry) {
1306
+ const type = item.data.type;
1307
+ const order = UNIT_ITEM_TYPES.includes(type) ? await blockOrder(`unit-${type}`) : null;
1308
+ const named = text
1309
+ ? replaceNamed(String(item.body), text, item, order)
1310
+ : String(item.body).replace(/\r\n/g, '\n');
1311
+ const note = add ? (entry?.relink(add) ?? add) : entry?.note;
1312
+
1313
+ return {
1314
+ title: title || (item.data.title ?? ''),
1315
+ body: note ? await upsertItemNote({ ...item, body: named }, 'notes', note) : named,
1316
+ };
1317
+ }
1318
+
1319
+ /** A fix with nothing in it, or over a card edited since its form was read. */
1320
+ function refuseAmendPointless(item, { asked, base, changes, entry }) {
1321
+ const id = item.data.id;
1322
+ if (!asked.text && !asked.add && !asked.title && !asked.from)
1323
+ throw new Error(`${id}: nothing to change: give --text, --add, --title or --from`);
1324
+ if (base && base !== amendBase(item))
1325
+ throw refusal(
1326
+ 'stale',
1327
+ {},
1328
+ `${id} changed since this form was opened: read it again, nothing was written`,
1329
+ );
1330
+ if (!changes.length && !entry) throw new Error(`${id}: the card already says this`);
1331
+ }
1332
+
1333
+ /** An entry into the move's commit; one added without a commit rides along, as with `item new`. */
1334
+ function carryEntry(m, entry, commit) {
1335
+ const loose = commit ? untrackedEntries(m.projectDir) : [];
1336
+ m.touch(...entry.files, ...loose);
1337
+ m.inputs.push(...entry.inputs, ...loose);
1338
+ m.step(entry.apply);
1339
+ }
1340
+
1110
1341
  /** Any stored status → graveyard; an unplayed item leaves as a kill does.
1111
1342
  * @param {MoveOpts} [opts]
1112
1343
  */
@@ -1116,7 +1347,9 @@ async function dropItemUnlocked(projectDir, id, opts = {}) {
1116
1347
  if (m.item.data.type === 'feature' && (m.item.data.children ?? []).some((c) => m.ledger.item(c)))
1117
1348
  throw new Error(`${id} still has live children: drop them first, or decide kill ${id}`);
1118
1349
  const shipped =
1119
- m.item.data.type === 'feature' ? featureShipped(m.ledger, m.item) : codeInMain(m.item);
1350
+ m.item.data.type === 'feature'
1351
+ ? featureShipped(projectDir, m.ledger, m.item)
1352
+ : codeInMain(projectDir, m.item);
1120
1353
  const removal = endToGraveyard(m, m.item, { reason, tags, removal: remove ?? shipped });
1121
1354
 
1122
1355
  return { id, hash: await finish(m, 'drop', id, commit), removal };
@@ -1366,7 +1599,8 @@ async function setDependsUnlocked(projectDir, id, { add = [], remove = [], commi
1366
1599
 
1367
1600
  /**
1368
1601
  * Set how item `id`'s runs go: its `model` and `effort`, each given one a plain word, `default`
1369
- * taking the field off (the project's `agent.model|effort`, else Opus and High). One commit `gcf(item)`. A run in progress keeps
1602
+ * taking the field off (the project's `agent.model|effort`, else Opus and High). One commit
1603
+ * `gcf(item)`. A run in progress keeps
1370
1604
  * its own; the item's next run takes the new value.
1371
1605
  * @param {string} projectDir
1372
1606
  * @param {string} id
@@ -1578,8 +1812,9 @@ async function newItemUnlocked(projectDir, given) {
1578
1812
  if (spec.note !== undefined && spec.note.length > NOTE_MAX)
1579
1813
  throw new Error(`the note is ${spec.note.length} characters: up to ${NOTE_MAX}`);
1580
1814
  const take = await takeEntry(projectDir, root, spec);
1581
- // The note given first, then what the inbox entry it comes from says.
1582
- const note = [spec.note, take.note].filter((x) => x?.trim()).join('\n\n') || undefined;
1815
+ // A note given goes over what the entry says: a board's form shows that text and sends it back,
1816
+ // and a human's edit of it is the note.
1817
+ const note = spec.note?.trim() ? take.relink(spec.note) : take.note || undefined;
1583
1818
  const item = { ...spec, title: take.title, note };
1584
1819
 
1585
1820
  const writes = [
@@ -1613,7 +1848,14 @@ async function newItemUnlocked(projectDir, given) {
1613
1848
  */
1614
1849
  async function takeEntry(projectDir, root, spec) {
1615
1850
  if (!spec.from)
1616
- return { title: spec.title, note: undefined, files: [], inputs: [], apply: async () => {} };
1851
+ return {
1852
+ title: spec.title,
1853
+ note: undefined,
1854
+ relink: (s) => s,
1855
+ files: [],
1856
+ inputs: [],
1857
+ apply: async () => {},
1858
+ };
1617
1859
  if (onWorkBranch(projectDir))
1618
1860
  throw new Error('an inbox entry is taken on main: a work/ branch records no inbox move');
1619
1861
  const pictures = path.join(root, 'work', spec.id, 'attachments');
@@ -1643,6 +1885,7 @@ async function takeEntry(projectDir, root, spec) {
1643
1885
  ...take,
1644
1886
  title,
1645
1887
  note,
1888
+ relink,
1646
1889
  files: [...take.files, ...loose],
1647
1890
  inputs: [...take.inputs, ...loose],
1648
1891
  };
@@ -1669,6 +1912,11 @@ export const blockItem = (projectDir, id, opts = {}) =>
1669
1912
  /** @type {typeof unblockItemUnlocked} */
1670
1913
  export const unblockItem = (projectDir, id, opts = {}) =>
1671
1914
  locked(projectDir, opts.commit ?? true, () => unblockItemUnlocked(projectDir, id, opts));
1915
+ /** @type {typeof amendItemUnlocked} */
1916
+ export const amendItem = (projectDir, id, opts = {}) =>
1917
+ locked(projectDir, !opts.dryRun && (opts.commit ?? true), () =>
1918
+ amendItemUnlocked(projectDir, id, opts),
1919
+ );
1672
1920
  /** @type {typeof dropItemUnlocked} */
1673
1921
  export const dropItem = (projectDir, id, opts = {}) =>
1674
1922
  locked(projectDir, opts.commit ?? true, () => dropItemUnlocked(projectDir, id, opts));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.22.1",
3
+ "version": "0.24.0",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -8,7 +8,8 @@ mode: human gate
8
8
  purpose:
9
9
  - answer the human's questions about the game, its design, its work items and its runs from what `gcf/` and the run files say
10
10
  - turn a bug, an idea or a task the talk finds into a proposed work item the human accepts with one click
11
- - propose a move on an item, an inbox entry or an open question (block, drop, depends, unblock, a verdict, a decision, an answer, inbox add, category, Later, erase) as a card the human makes with one click
11
+ - propose a move on an item, an inbox entry or an open question (amend, block, drop, depends, unblock, a verdict, a decision, an answer, inbox add, category, Later, erase) as a card the human makes with one click
12
+ - carry a decision the talk takes about a live item into that item's text, with one proposal
12
13
  - make another move the human asks for through its `ai-factory gcf` command, which the chat shows the human as a card first
13
14
 
14
15
  inputs:
@@ -22,7 +23,9 @@ preconditions:
22
23
  - with YOLO a framework move that changes the project runs without a card too: a move with a `propose_` tool stays a proposal, and any other move is one the human asked for
23
24
 
24
25
  forbidden_behaviors:
25
- - do not make the human's moves: `verdict`, `decide`, `question answer`, `unblock`, `phase next`, `pillar`, `permissions`, `config set`, `hooks-install`, `edits commit`, `edits discard`; the rules refuse them to any agent
26
+ - do not make the human's moves: `verdict`, `decide`, `question answer`, `unblock`, `item amend`, `phase next`, `pillar`, `permissions`, `config set`, `hooks-install`, `edits commit`, `edits discard`, `changes commit`; the rules refuse them
27
+ - do not put a decision about a live item into the inbox or a new item: a run reads neither, and it blocks on what its card does not say; the decision goes into the card with `propose_amend`
28
+ - do not add a line to `notes:` that contradicts a slot of the card: replace the slot through `text`, as only the slots reach the documents of the systems
26
29
  - do not run a verdict, a decision, an unblock or an answer: propose it to the human with its `propose_` tool
27
30
  - do not run `ai-factory gcf-harness run|stop|chat|init` or `ai-factory extension`: the rules refuse them; name the board's button instead
28
31
  - do not make a new item with `ai-factory gcf item new`: propose it with the `propose_item_new` tool of the `gcf` MCP server, and the human's click makes it
@@ -40,13 +43,17 @@ workflow:
40
43
  1. read `gcf/INDEX.md`, then run `ai-factory gcf board --json` for the phase, the items by status and the inbox
41
44
  2. a thread bound to an item: read the item's file, its plan, its run's log and run chat first, the paths the context file names, before the first answer
42
45
  3. answer the question from the files you read, with the paths that say it; for the runs' numbers run `ai-factory gcf-harness metrics` when the project has the harness
43
- 4. a bug, an idea or a task that is new work: call `propose_item_new` with its title, type, subsystems and a note of what its run should know, no id: the core makes it from the title; note length <= 4000 characters
44
- 5. a raw thought that is not work yet: propose it for the inbox with `propose_inbox_add` and the category it is: `idea`, `request` (what only a person can give), `bug` or `finding` (a remark about the code), a detail word when one fits
45
- 6. a move the human asks for, or one the talk shows is due, that has a `propose_<move>` tool: call it with the `id` of the item, inbox entry or question it acts on, and say why in one line; name an item by its title with the id in brackets
46
- 7. a kill, a no or a wontfix: its reason is the human's words; the graveyard keeps it, and the move does not go without it
47
- 8. an open D1 question the talk answers: call `propose_question_answer` with its id and the human's words, or your draft when the human asks for one
48
- 9. another move the human asks for: run its `ai-factory gcf` command; the human approves it on the card, or refuses it
49
- 10. say in one line what changed, or that nothing did
46
+ 4. a decision about a live item, or a line of its card the talk shows wrong: call `propose_amend` with its `id`
47
+ 5. its `text` holds the blocks it replaces in the card's block syntax, each whole; a superseded note leaves by `notes:` there, whole, without that line
48
+ 6. its `add` holds only what adds to them, length <= 4000 characters
49
+ 7. a run works that item: call `propose_amend` all the same: the human's card sends the decision to the run's chat; say so in one line
50
+ 8. a bug, an idea or a task that is new work: call `propose_item_new` with its title, type, subsystems and a note of what its run should know, no id: the core makes it from the title; note length <= 4000 characters
51
+ 9. a raw thought that is not work yet: propose it for the inbox with `propose_inbox_add` and the category it is: `idea`, `request` (what only a person can give), `bug` or `finding` (a remark about the code), a detail word when one fits
52
+ 10. a move the human asks for, or one the talk shows is due, that has a `propose_<move>` tool: call it with the `id` of the item, inbox entry or question it acts on, and say why in one line; name an item by its title with the id in brackets
53
+ 11. a kill, a no or a wontfix: its reason is the human's words; the graveyard keeps it, and the move does not go without it
54
+ 12. an open D1 question the talk answers: call `propose_question_answer` with its id and the human's words, or your draft when the human asks for one
55
+ 13. another move the human asks for: run its `ai-factory gcf` command; the human approves it on the card, or refuses it
56
+ 14. say in one line what changed, or that nothing did
50
57
 
51
58
  invocation:
52
59
  - run at the start of a project chat thread the board opens, and when the user types `/gcf-chat`
@@ -18,22 +18,24 @@ forbidden_behaviors:
18
18
  - do not create an item or erase an entry without the human's yes: the agent proposes, the human approves
19
19
  - do not turn a feel complaint into a bug: "jump feels floaty" is a tune of the item that owns the jump, a bug is behaviour that breaks a rule or a test
20
20
  - do not open a second item for something `gcf/graveyard.md` already buried: name the line and ask whether the reason still holds
21
- - do not edit or delete a file in `gcf/inbox/` by hand: `ai-factory gcf item new --from`, `ai-factory gcf inbox category`, `inbox later` and `inbox drop` own the entries
21
+ - do not run `ai-factory gcf item amend`: it is the human's move
22
+ - do not edit or delete a file in `gcf/inbox/` by hand: `item new --from`, `item amend --from`, `inbox category`, `later` and `drop` own the entries
22
23
  - do not triage on a `work/` branch: `inbox category`, `inbox later`, `inbox drop` and `item new --from` refuse there; triage on main
23
24
 
24
25
  workflow:
25
26
  1. run `ai-factory gcf inbox --json`; read `gcf/LIVE.md` and `gcf/INDEX.md` to know what exists and what is in work
26
- 2. classify each entry: bug, tune of a live or unplayed item, idea for the design, request (an asset file, a question), duplicate, or noise; search `gcf/graveyard.md` for each idea and bug; an `unsorted` entry gets a category
27
+ 2. classify each entry: bug, tune of a live or unplayed item, a fix of a live item, idea for the design, request (an asset file, a question), duplicate, or noise; search `gcf/graveyard.md` for each idea and bug; an `unsorted` entry gets a category
27
28
  3. a lesson (category `lesson`, its kind the `detail`, with the `item` it came from) is what got in an agent's way: propose the fix it asks for - a project rule, a tech item, a note for the framework or the template - or noise
28
29
  4. for each entry propose one call with its fields: a bug gets type `bug`, severity and a repro; a tune names the item and the note; an idea names the subsystem; a duplicate names the item it repeats
29
30
  5. present the calls to the human, calls per message <= 5, and apply only the approved ones
30
31
  6. a bug or other work: run `ai-factory gcf item new --type <type> [--severity <level>] --from <in-id>`; the core makes the id from the title and prints it first; then write its `intent:` and `repro:`
31
32
  7. `--from` without `--title` makes the entry's title the item's title and puts the rest of its text in a `note:` block, its pictures in `gcf/work/<id>/attachments/`; with your own `--title` the whole text goes into `note:`
32
- 8. a tune of an item waiting for its verdict or unplayed: leave the entry in the inbox, the note's only copy, until `/gcf-verdict <id> tune --note` records it and drops it; a tune of a kept mechanic is new work with `--reopens <id>`
33
- 9. an idea for the design: write a unit with `TBD` slots in `gcf/design/<system>.md` and its backlog line, then run `ai-factory gcf inbox drop <in-id>`
34
- 10. a duplicate or noise: run `ai-factory gcf inbox drop <in-id>`
35
- 11. an entry the human sorts: `ai-factory gcf inbox category <in-id> --category <c> [--detail <word>]` (`inbox categories` lists them); one kept for later: `ai-factory gcf inbox later <in-id>`, left in the inbox
36
- 12. report what each entry became and how many entries remain
33
+ 8. a fix of a live item's text: in the board's chat call `propose_amend` with its `id` and `from`; in a console give the human the line `ai-factory gcf item amend <id> --from <in-id>` to run
34
+ 9. a tune of an item waiting for its verdict or unplayed: leave the entry in the inbox, the note's only copy, until `/gcf-verdict <id> tune --note` records it and drops it; a tune of a kept mechanic is new work with `--reopens <id>`
35
+ 10. an idea for the design: write a unit with `TBD` slots in `gcf/design/<system>.md` and its backlog line, then run `ai-factory gcf inbox drop <in-id>`
36
+ 11. a duplicate or noise: run `ai-factory gcf inbox drop <in-id>`
37
+ 12. an entry the human sorts: `ai-factory gcf inbox category <in-id> --category <c> [--detail <word>]` (`inbox categories` lists them); one kept for later: `ai-factory gcf inbox later <in-id>`, left in the inbox
38
+ 13. report what each entry became and how many entries remain
37
39
 
38
40
  invocation:
39
41
  - run after a playtest session, after a CI run that added entries, or when the user asks to triage