fwdloop 0.16.0 → 0.18.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.
Files changed (64) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +10 -7
  3. package/package.json +1 -1
  4. package/src/authoring.js +6 -6
  5. package/src/books.js +6 -1
  6. package/src/catalogue.json +9 -3
  7. package/src/ctx-tools.js +245 -0
  8. package/src/draft-steps.js +89 -30
  9. package/src/drafter.js +28 -4
  10. package/src/draftspend.js +109 -3
  11. package/src/liveness.js +34 -10
  12. package/src/panel/author.js +125 -37
  13. package/src/panel/authorcard.js +15 -10
  14. package/src/panel/authorflows.js +9 -3
  15. package/src/panel/authorresume.js +5 -4
  16. package/src/panel/authorstart.js +21 -9
  17. package/src/panel/authortrigger.js +384 -0
  18. package/src/panel/authorvalues.js +5 -3
  19. package/src/panel/data.js +104 -16
  20. package/src/panel/index.html +257 -44
  21. package/src/panel/scheduler.js +125 -0
  22. package/src/panel/server.js +24 -10
  23. package/src/panel/settings.js +2 -2
  24. package/src/plain-checks.js +51 -0
  25. package/src/primitives.js +34 -3
  26. package/src/provider.js +17 -8
  27. package/src/run-store.js +47 -0
  28. package/src/runner.js +2 -0
  29. package/src/runvalues.js +5 -3
  30. package/src/setup.js +24 -0
  31. package/src/signed-text.js +26 -0
  32. package/src/summary-words.js +155 -0
  33. package/src/trigger-clock.js +142 -0
  34. package/src/trigger-files.js +212 -0
  35. package/src/trigger-line.js +86 -0
  36. package/src/types.js +1 -0
  37. package/src/version.js +13 -0
  38. package/types/authoring.d.ts +1 -3
  39. package/types/ctx-tools.d.ts +18 -0
  40. package/types/draft-steps.d.ts +38 -5
  41. package/types/drafter.d.ts +3 -3
  42. package/types/draftspend.d.ts +56 -0
  43. package/types/liveness.d.ts +7 -1
  44. package/types/panel/author.d.ts +149 -146
  45. package/types/panel/authorcard.d.ts +12 -2
  46. package/types/panel/authorflows.d.ts +11 -3
  47. package/types/panel/authorstart.d.ts +7 -4
  48. package/types/panel/authortrigger.d.ts +210 -0
  49. package/types/panel/authorvalues.d.ts +3 -1
  50. package/types/panel/data.d.ts +14 -7
  51. package/types/panel/scheduler.d.ts +15 -0
  52. package/types/panel/server.d.ts +11 -3
  53. package/types/plain-checks.d.ts +22 -0
  54. package/types/primitives.d.ts +0 -6
  55. package/types/provider.d.ts +7 -1
  56. package/types/run-store.d.ts +11 -0
  57. package/types/runvalues.d.ts +1 -1
  58. package/types/setup.d.ts +27 -0
  59. package/types/summary-words.d.ts +53 -0
  60. package/types/trigger-clock.d.ts +60 -0
  61. package/types/trigger-files.d.ts +90 -0
  62. package/types/trigger-line.d.ts +44 -0
  63. package/types/types.d.ts +4 -0
  64. package/types/version.d.ts +2 -0
package/README.md CHANGED
@@ -62,6 +62,8 @@ standalone.
62
62
 
63
63
  Work in progress. Nothing here is ready to install yet.
64
64
 
65
+ The in-run `impact` tool needs ripgrep (`rg`) on PATH; without it the tool is refused with a message, never a wrong answer.
66
+
65
67
  ## License
66
68
 
67
69
  Apache-2.0. See `LICENSE` and `NOTICE`.
package/bin/fwdloop CHANGED
@@ -18,7 +18,8 @@ import { parseArgs } from 'node:util';
18
18
  import {
19
19
  existsSync, readdirSync, realpathSync, rmdirSync,
20
20
  } from 'node:fs';
21
- import { extname, join, resolve } from 'node:path';
21
+ import { basename, dirname, extname, join, resolve } from 'node:path';
22
+ import { draftHoldUsd } from '../src/draftspend.js';
22
23
  import { pathToFileURL } from 'node:url';
23
24
 
24
25
  import {
@@ -29,6 +30,7 @@ import {
29
30
  runFlow, resumeRun, continueRun, auditSpend, makeParkingAskStep, readAsk, readRunState,
30
31
  } from '../src/runner.js';
31
32
  import { applyRunValues, pickRunValues, dropUnstartedValues } from '../src/runvalues.js';
33
+ import { TRIGGER_RECORD_FILE } from '../src/trigger-line.js';
32
34
  import { makeLiveModelStep } from '../src/model-step.js';
33
35
  import { sendViaPrimitive } from '../src/send.js';
34
36
  import { resolvePrimitives } from '../src/primitives.js';
@@ -351,7 +353,7 @@ async function cmdRun(rest) {
351
353
  if (!runIdCheck.ok) fail(runIdCheck.red);
352
354
  runDir = runIdCheck.runDir;
353
355
  // M4e amendment 5: the panel's Sign & run puts the run's signed values in the folder BEFORE the start; that one file is not "a run".
354
- if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json').length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
356
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE).length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
355
357
  }
356
358
  // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's) is what the monthly hold is for.
357
359
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
@@ -810,7 +812,7 @@ async function cmdDraft(rest) {
810
812
  const { values, positionals } = parseArgs({
811
813
  args: rest,
812
814
  options: {
813
- out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' }, budget: { type: 'string' },
815
+ out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' },
814
816
  // M4e amendment 24 item 4: the redraft after the human's answers never asks (the panel passes this; a plain draft may ask on try 3)
815
817
  'no-questions': { type: 'boolean' },
816
818
  // M4d amendment 6: the model that drafts (and then runs) the job - a line ticked in Settings > Providers; --provider only if two keys tick the same id.
@@ -822,7 +824,7 @@ async function cmdDraft(rest) {
822
824
  const keysLoad = keyedLoad();
823
825
  const { env } = keysLoad;
824
826
  const proseFile = positionals[0];
825
- if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow> [--budget <usd>]');
827
+ if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow>');
826
828
  for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
827
829
 
828
830
  let injected = {};
@@ -846,7 +848,7 @@ async function cmdDraft(rest) {
846
848
  const refusal = draftKeyRefusal(pick.slot, env);
847
849
  if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
848
850
  } else if (values.model !== undefined) pick = { slot: values.provider, model: values.model };
849
- // M4d piece 3: the monthly check — a draft has no signed cap, so it holds one ceiling round, priced from the
851
+ // M4d piece 3: the monthly check — one ceiling round, priced from the
850
852
  // picked model's own Settings prices (an injected test provider carries its own rates). A model that is not
851
853
  // ticked with both prices is refused here by name, at $0, before the monthly hold or any draft folder (M4d amendment 5).
852
854
  let ceiling;
@@ -863,15 +865,16 @@ async function cmdDraft(rest) {
863
865
  if (!(err instanceof ConfigError)) throw err;
864
866
  fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
865
867
  }
868
+ // M4d am19 item 1: the hold is what is left of the cap (cap minus this job's drafting so far), the most the draft may spend, not one round
869
+ const proseRead = readFileInside(dirname(resolve(proseFile)), basename(resolve(proseFile)));
866
870
  takeMonthlyHold({
867
- what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: ceiling,
871
+ what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
868
872
  });
869
873
  const result = await draftToDir({
870
874
  proseFile: resolve(proseFile),
871
875
  dir: resolve(values.out),
872
876
  root: resolve(values.root),
873
877
  name: values.name,
874
- budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
875
878
  noQuestions: values['no-questions'] === true,
876
879
  draftThinking: values.thinking === true ? 'on' : 'off',
877
880
  env,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/authoring.js CHANGED
@@ -30,10 +30,9 @@ import { checkSendDestination } from './runner.js';
30
30
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
31
31
  import { keyValues } from './keysfile.js';
32
32
  import { readModelRecord, writeModelRecord } from './flowmodel.js';
33
- import { writeDraftSpend } from './draftspend.js';
33
+ import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
34
34
  import { writeSetup } from './setup.js';
35
35
 
36
- export const DRAFT_BUDGET_USD = 0.10;
37
36
  export const SPEC_HASH_FILE = 'spec.hash';
38
37
  /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
39
38
  export const PANEL_DRAFTS_DIR = '.drafts';
@@ -248,13 +247,12 @@ export function draftKeyRefusal(slot, env) {
248
247
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
249
248
  */
250
249
  export async function draftToDir({
251
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, budgetUsd = DRAFT_BUDGET_USD, env = process.env, provider, rates, modelId, noQuestions = false,
250
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false,
252
251
  }) {
253
252
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
254
253
  const nameCheck = checkFlowName(name);
255
254
  if (!nameCheck.ok) return refuse([nameCheck.red]);
256
255
  if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
257
- if (!(budgetUsd > 0)) return refuse(['draft: budget must be a positive number']);
258
256
  // An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
259
257
  const realRoot = realpathOfNew(root);
260
258
  const realDir = realpathOfNew(dir);
@@ -305,8 +303,10 @@ export async function draftToDir({
305
303
  // after a call the cost is already in the file as "one call in flight" (a ceiling): the honest direction, so no throw
306
304
  }
307
305
  };
306
+ // M4d am16: a panel draft folder (card.json beside this plan folder) is one job's session: what its earlier plans spent comes off the cap first.
307
+ const priorSpend = sessionPriorSpend(dir);
308
308
  const result = await draft({
309
- proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env, onBook, offerQuestions: !noQuestions, draftThinking,
309
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking,
310
310
  });
311
311
  if (result.stop === 'pre-flight') {
312
312
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
@@ -370,7 +370,7 @@ export async function draftToDir({
370
370
  calls: result.calls,
371
371
  spendComplete: result.spendComplete,
372
372
  stop: result.stop,
373
- budgetUsd,
373
+ budgetUsd: parsed.arbiter.capUsd, // the cap signed in the prose is the draft's limit too (M4d am13)
374
374
  // the draft's own time (amendment 7 item 2: the Draft's total time adds up from these); null when no call was booked
375
375
  startedAt,
376
376
  wallMs: startedAt === null ? null : Math.max(0, Date.now() - Date.parse(startedAt)),
package/src/books.js CHANGED
@@ -22,6 +22,7 @@ import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
24
  import { readFileInside, readdirInside } from './flow.js';
25
+ import { TRIGGER_RECORD_FILE } from './trigger-line.js';
25
26
 
26
27
  function appendLine(filePath, row) {
27
28
  mkdirSync(dirname(filePath), { recursive: true });
@@ -288,7 +289,11 @@ export function readAudit(runDir) {
288
289
  */
289
290
  export function appendHistory(flowDir, row) {
290
291
  checkCostField(row, 'spentUsd', 'appendHistory');
291
- appendLine(join(flowDir, 'history.jsonl'), row);
292
+ // M9 (am2 item 1): a run a trigger started says so in its history row, read from the record the start wrote into the run's own folder
293
+ const rec = typeof row.runId === 'string' && row.trigger === undefined ? readFileInside(join(flowDir, 'runs', row.runId), TRIGGER_RECORD_FILE) : null;
294
+ let trigger;
295
+ if (rec !== null && rec.ok) { try { trigger = JSON.parse(rec.text); } catch { trigger = undefined; } }
296
+ appendLine(join(flowDir, 'history.jsonl'), trigger === undefined ? row : { ...row, trigger });
292
297
  }
293
298
 
294
299
  /**
@@ -14,13 +14,19 @@
14
14
  "verb": "grep", "component": "select", "package": "bare-agent/tools", "symbol": "createShellTools", "tool": "shell_grep", "class": "read", "skill": "core", "desc": "Find lines matching a pattern across files."
15
15
  },
16
16
  {
17
- "verb": "recall", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "recall", "class": "read", "skill": "core", "desc": "Search saved notes by meaning; returns the best matches, not their full text."
17
+ "verb": "recall", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "recall", "class": "read", "skill": "core", "desc": "Search this run's code and markdown files only (its inputs and out folder, .md .js .py .ts); a CSV or Word file is not searched. Returns pointers to the best matches, not their full text."
18
18
  },
19
19
  {
20
- "verb": "get", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "get", "class": "read", "skill": "core", "desc": "Fetch the full text of one saved note or parked item by its id."
20
+ "verb": "get", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "get", "class": "read", "skill": "core", "desc": "Fetch the full text of one parked item by its id, or one part of a file by the pointer recall gave."
21
21
  },
22
22
  {
23
- "verb": "recent", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "recentMemory", "class": "read", "skill": "core", "desc": "List the most recently saved notes, newest first."
23
+ "verb": "recent", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "recentActivity", "class": "read", "skill": "core", "desc": "List the functions most recently changed in this run's code files, newest first. This is not a git repository, so it finds nothing inside a run."
24
+ },
25
+ {
26
+ "verb": "related", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "related", "class": "read", "skill": "core", "desc": "List the files a given code or markdown file imports and the files that import it, in code and markdown files only; a CSV or Word file has none."
27
+ },
28
+ {
29
+ "verb": "impact", "component": "select", "package": "litectx", "symbol": "LiteCtx", "method": "impact", "class": "read", "skill": "core", "desc": "Name the callers and importers of one function or symbol, in code and markdown files only; a CSV or Word file has none, so it finds nothing there."
24
30
  },
25
31
  {
26
32
  "verb": "compress", "component": "compress", "package": "litectx", "symbol": "compress", "class": "read", "skill": "core", "desc": "Shrink source code: keep each function header and its doc comment, drop the body (or reduce it to a name). Code only — prose and markdown come back unchanged."
@@ -0,0 +1,245 @@
1
+ // M7 piece 3 (docs/wiki/the-module-ladder.md, "M7 scope — SIGNED", items 1-3): the
2
+ // in-run tools a step can use only if it is granted: recall, get, recent, related,
3
+ // impact, compress, peek, stash. Each is a litectx call over THIS run's store
4
+ // (src/run-store.js), so nothing carries into the next run.
5
+ //
6
+ // borrowed-from: bareloop src/tools.js@dc06660 (createCtxTools: ctx_recall, ctx_get,
7
+ // ctx_impact, ctx_related, ctx_recent, ctx_compress, ctx_stash, ctx_peek and
8
+ // ISOLATE_MAX_BYTES = 64 KB; the readouts are bareloop's). Adjusted to fwdloop's shape:
9
+ // - named by bare verb, like read/write (src/primitives.js);
10
+ // - the store is per run and opened per call (src/run-store.js), the index root is
11
+ // the run dir, and any path a tool is handed goes through the SAME read gate as
12
+ // `read` first (`gatePath`), so the deny rules apply through every door;
13
+ // - `get` also reads a stashed item by id (the catalogue's words for it);
14
+ // - no spine `emit`: model-step already tallies each tool a step called;
15
+ // - `remember`/`forget` are NOT here: memory lasts one run (PRD: no learning
16
+ // between flows), so they stay refused.
17
+ // - redactSecrets is bareloop's src/validate.js@07215d6 inventory (SECRET_PATTERNS).
18
+
19
+ import path from 'node:path';
20
+ import { createRequire } from 'node:module';
21
+ import { redact } from 'bareguard';
22
+ import { withRunStore } from './run-store.js';
23
+
24
+ const require = createRequire(import.meta.url);
25
+ const { compress: compressNode, StalePointerError } = require('litectx');
26
+
27
+ /** One stashed item holds at most this many bytes (measured after secrets are masked,
28
+ * because that is what enters the store). Bareloop's number, signed in M7 item 3. */
29
+ export const ISOLATE_MAX_BYTES = 65536;
30
+
31
+ const SECRET_PATTERNS = [
32
+ /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
33
+ /(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
34
+ /(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
35
+ /(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
36
+ /(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
37
+ /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
38
+ ];
39
+
40
+ /** Mask known secret shapes. @param {unknown} raw */
41
+ const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
42
+
43
+ const LINE_SPACE = 'Line numbers are 0-based; copy them between recall and get as printed.';
44
+
45
+ /**
46
+ * @param {object} o
47
+ * @param {string} o.runDir
48
+ * @param {(verb: string, rawPath: unknown) => Promise<string>} o.gatePath - the read gate; resolves a model-given path to the absolute path it judged, or throws GateRefusal.
49
+ * @returns {Record<string, {name: string, description: string, parameters: object, execute: (args: any) => Promise<string>}>}
50
+ */
51
+ export function makeCtxTools({ runDir, gatePath }) {
52
+ const root = path.resolve(runDir);
53
+ /** Run `fn(lc)` on this run's store, with the run's indexed text brought up to date first. A store failure is
54
+ * a refusal RESULT naming the cause, never a throw, so it costs one round instead of the run. */
55
+ const indexed = (/** @type {string} */ tool, /** @type {(lc: any) => Promise<string>|string} */ fn) => async () => {
56
+ try {
57
+ return await withRunStore(runDir, async (lc) => { await lc.index(); return fn(lc); });
58
+ } catch (e) {
59
+ return `${tool} failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
60
+ }
61
+ };
62
+ /** A path the gate approved, as litectx spells it: relative to the run dir. @param {string} verb @param {unknown} raw */
63
+ const relOf = async (verb, raw) => {
64
+ const abs = await gatePath(verb, raw);
65
+ return path.relative(root, abs);
66
+ };
67
+
68
+ return {
69
+ recall: {
70
+ name: 'recall',
71
+ description: 'Search this run\'s code and markdown files only (its frozen inputs and its out folder; a CSV or Word file is not searched) for a name or phrase. '
72
+ + `Returns POINTERS (path, symbol, line range), not the text; pass one to get to read that part. ${LINE_SPACE}`,
73
+ parameters: {
74
+ type: 'object',
75
+ properties: {
76
+ query: { type: 'string', description: 'A symbol name or a phrase.' },
77
+ n: { type: 'integer', description: 'Max pointers (default 5, max 20).' },
78
+ },
79
+ required: ['query'],
80
+ },
81
+ execute: async ({ query, n }) => indexed('recall', async (lc) => {
82
+ const cap = Math.min(Math.max(Number(n) || 5, 1), 20);
83
+ const grouped = await lc.recall(String(query), { kind: ['code', 'doc'], n: cap });
84
+ const hits = [...(grouped.code ?? []), ...(grouped.doc ?? [])].slice(0, cap);
85
+ const lines = hits.map((/** @type {any} */ h) => (h.chunk
86
+ ? `${h.path}\t${h.chunk.symbol ?? '(anonymous)'}\t${h.chunk.nodeType}\tlines ${h.chunk.startLine}-${h.chunk.endLine}`
87
+ : `${h.path}\t(whole file — no chunk)`));
88
+ return lines.length ? lines.join('\n') : 'no hits';
89
+ })(),
90
+ },
91
+ get: {
92
+ name: 'get',
93
+ description: 'Read ONE thing back: a stashed item by its id, or one chunk of a file by the path and line range recall gave you '
94
+ + `(code plus its doc-comment, without the rest of the file). A range that is not a chunk boundary is refused. ${LINE_SPACE}`,
95
+ parameters: {
96
+ type: 'object',
97
+ properties: {
98
+ id: { type: 'string', description: 'The key a payload was stashed under.' },
99
+ path: { type: 'string', description: 'Path exactly as recall printed it.' },
100
+ startLine: { type: 'integer', description: 'From recall.' },
101
+ endLine: { type: 'integer', description: 'From recall.' },
102
+ },
103
+ },
104
+ execute: async (args) => {
105
+ if (typeof args?.id === 'string') {
106
+ const key = redactSecrets(args.id);
107
+ return indexed('get', (lc) => (lc.peek(key) ? String(lc.get(key)?.text ?? '') : `nothing stashed under "${key}"`))();
108
+ }
109
+ if (typeof args?.path !== 'string') return 'get: give either an id (a stashed item) or a path with startLine and endLine';
110
+ const rel = await relOf('get', args.path);
111
+ return indexed('get', (lc) => {
112
+ try {
113
+ const item = lc.get(rel, { startLine: Number(args.startLine), endLine: Number(args.endLine) });
114
+ return item?.text || `no chunk at ${args.startLine}-${args.endLine} in "${rel}" — copy a line range from recall, do not compute one`;
115
+ } catch (e) {
116
+ if (e instanceof StalePointerError) return `stale pointer: ${e.message}`;
117
+ throw e;
118
+ }
119
+ })();
120
+ },
121
+ },
122
+ impact: {
123
+ name: 'impact',
124
+ description: 'Before changing a function, see what depends on it: callers, importers and mention sites in code and markdown files only (a CSV or Word file has none). '
125
+ + `${LINE_SPACE}`,
126
+ parameters: {
127
+ type: 'object',
128
+ properties: { symbol: { type: 'string', description: 'A function, class or identifier name.' } },
129
+ required: ['symbol'],
130
+ },
131
+ execute: async ({ symbol }) => indexed('impact', async (lc) => {
132
+ const imp = await lc.impact(String(symbol));
133
+ if (!imp) return `no indexed symbol "${symbol}" — check the spelling with recall first`;
134
+ const lines = [];
135
+ for (const d of imp.defs ?? []) lines.push(`defined\t${d.path}:${d.startLine}`);
136
+ for (const c of imp.callers ?? []) lines.push(`called by\t${c.path}:${c.line}${c.symbol ? ` (in ${c.symbol})` : ''}`);
137
+ for (const c of imp.callees ?? []) lines.push(`calls\t${c}`);
138
+ lines.push(`risk ${imp.risk} — ${imp.confirmed} confirmed caller(s), ${imp.mentions} mention(s)`);
139
+ // the hedges are the other half of the count: "low risk, 0 callers" alone reads as a licence
140
+ for (const h of imp.hedges ?? []) lines.push(`caveat\t${h}`);
141
+ return lines.join('\n');
142
+ })(),
143
+ },
144
+ related: {
145
+ name: 'related',
146
+ description: 'Walk the import links around one code or markdown file: what it imports and what imports it (one hop). Code and markdown files only.',
147
+ parameters: {
148
+ type: 'object',
149
+ properties: { path: { type: 'string', description: 'A path inside this run, e.g. "out/helper.js".' } },
150
+ required: ['path'],
151
+ },
152
+ execute: async ({ path: p }) => {
153
+ const rel = await relOf('related', p);
154
+ return indexed('related', (lc) => {
155
+ const r = lc.related(rel, { dir: 'both', hops: 1 });
156
+ if (!r || !r.items.length) return `no import edges recorded for "${rel}" — the file is isolated or the path is not indexed`;
157
+ return r.items.map((/** @type {any} */ i) => `${i.via === 'in' ? 'imported by' : 'imports'}\t${i.id}`).join('\n');
158
+ })();
159
+ },
160
+ },
161
+ recent: {
162
+ name: 'recent',
163
+ description: 'List recently changed functions among this run\'s code files, most recent first. A run is not a git repository, so it finds nothing inside a run.',
164
+ parameters: { type: 'object', properties: {} },
165
+ execute: async () => indexed('recent', (lc) => {
166
+ const rows = lc.recentActivity() ?? [];
167
+ return rows.length
168
+ ? rows.map((/** @type {any} */ r) => `${r.id ?? r.symbol}\t${r.kind ?? ''}\tedits ${r.edits ?? '?'}`).join('\n')
169
+ : 'no recent edit activity recorded';
170
+ })(),
171
+ },
172
+ compress: {
173
+ name: 'compress',
174
+ description: 'Read a function\'s SIGNATURE: its declaration head plus doc-comment, with the body left out. '
175
+ + 'Far cheaper than the body when you only need what it is. Code only; give the path and the symbol name.',
176
+ parameters: {
177
+ type: 'object',
178
+ properties: {
179
+ path: { type: 'string', description: 'A path inside this run.' },
180
+ symbol: { type: 'string', description: 'The function or class name inside that file.' },
181
+ },
182
+ required: ['path', 'symbol'],
183
+ },
184
+ execute: async ({ path: p, symbol }) => {
185
+ const rel = await relOf('compress', p);
186
+ return indexed('compress', async (lc) => {
187
+ const node = lc.getNode(rel);
188
+ const chunk = node?.chunks.find((/** @type {any} */ c) => c.symbol === String(symbol));
189
+ if (!chunk) return `no symbol "${symbol}" in "${rel}" — recall the name to find where it lives`;
190
+ const file = lc.get(rel);
191
+ if (!file?.text) return `"${rel}" has no readable body in the index`;
192
+ const body = file.text.split('\n').slice(chunk.startLine, chunk.endLine + 1).join('\n');
193
+ return compressNode({ text: body, format: node.format, symbol: String(symbol) }, { level: 'signature' });
194
+ })();
195
+ },
196
+ },
197
+ stash: {
198
+ name: 'stash',
199
+ description: 'Park a bulky payload OUT of your context under a key; it costs nothing per round while parked. Check it later with peek or read it back with get. '
200
+ + `A payload over ${ISOLATE_MAX_BYTES} bytes is refused unparked. It lasts this run only.`,
201
+ parameters: {
202
+ type: 'object',
203
+ properties: {
204
+ id: { type: 'string', description: 'The key to park under.' },
205
+ text: { type: 'string', description: 'The payload.' },
206
+ },
207
+ required: ['id', 'text'],
208
+ },
209
+ execute: async ({ id, text }) => {
210
+ // masked BEFORE anything else touches it, and the cap is measured on the masked
211
+ // body: that is the one that enters the store
212
+ const key = redactSecrets(id);
213
+ const body = redactSecrets(text);
214
+ const size = Buffer.byteLength(body);
215
+ if (size > ISOLATE_MAX_BYTES) {
216
+ return `stash: text is ${size} bytes — the limit is ${ISOLATE_MAX_BYTES} bytes per payload. Nothing was parked. Park the part you need later, or write the bulk to a file and stash its path.`;
217
+ }
218
+ try {
219
+ await withRunStore(runDir, (lc) => lc.stash(key, body));
220
+ } catch (e) {
221
+ return `stash failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
222
+ }
223
+ return `parked ${size} bytes under "${key}"`;
224
+ },
225
+ },
226
+ peek: {
227
+ name: 'peek',
228
+ description: 'Look at the head and tail of a stashed payload WITHOUT loading all of it.',
229
+ parameters: {
230
+ type: 'object',
231
+ properties: { id: { type: 'string', description: 'The key it was stashed under.' } },
232
+ required: ['id'],
233
+ },
234
+ execute: async ({ id }) => {
235
+ const key = redactSecrets(id);
236
+ try {
237
+ const p = await withRunStore(runDir, (lc) => lc.peek(key));
238
+ return p ? `stash "${key}": ${p.bytes} bytes\nhead: ${p.head}\ntail: ${p.tail}` : `nothing stashed under "${key}"`;
239
+ } catch (e) {
240
+ return `peek failed: ${String(/** @type {Error} */ (e)?.message || e)}`;
241
+ }
242
+ },
243
+ },
244
+ };
245
+ }
@@ -1,34 +1,55 @@
1
- // M4d amendment 10: the Chat card's list of what a draft really did. ONE function builds it (here), from the draft's own log.json and its
2
- // declaration; the page only renders it. It sits outside the readout (never signed, never hashed).
1
+ // M4d amendment 15: the Chat card's list of what a draft really did, as PROGRESS only. ONE function builds it (here), from the draft's own log.json and
2
+ // its declaration; the page only renders it. It sits outside the readout (never signed, never hashed).
3
3
  //
4
- // Each entry: { id, label, status: 'done' | 'failed', details: string[], reds?: string[] }. `reds` (plan checks and try lines) are the checker's raw
5
- // refusals: the page turns each into its plain sentence (one function there). A step that didn't happen is not in the list.
6
- // Throws away: the log's per-round tokens, the model's replies and the questions; only the facts named in the amendment are kept.
4
+ // One line per step: { id, label, status: 'done' | 'failed', details: [] } where the label is the step's name with its facts joined by " · ". No detail
5
+ // lines, folds, try lines or raw checker text. A draft that ends red has one plain reason on its plan-checks line and, when the plain words say what
6
+ // to do, one `checks-fix` line (`note: true`: no ✓/✗) under it. The try-by-try history is `triesOf` (the Audit Draft group reads the same function).
7
+ // Throws away: the log's per-round tokens, the model's replies, the questions, and every try but the count of refused ones.
7
8
  // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
8
9
 
10
+ import { plainPlanCheck } from './plain-checks.js';
11
+
9
12
  const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
10
- const TRIES = 3;
11
13
 
12
14
  function money(log) {
13
15
  if (typeof log.costUsd !== 'number') return 'cost unknown';
14
16
  return `${log.spendComplete === false ? 'at least ' : ''}$${log.costUsd.toFixed(4)}`;
15
17
  }
16
18
 
17
- /** Why a round did not give a plan: its validator reds (raw, as `reds`: the page's one translator makes them plain), else its outcome as a detail line. */
18
- function reasonOf(entry) {
19
- if (Array.isArray(entry?.reds) && entry.reds.length > 0) return { details: [], reds: entry.reds.map(String) };
20
- const o = typeof entry?.outcome === 'string' ? entry.outcome : '';
21
- return { details: o === '' ? [] : [o.replace(/^structure: /, '')] };
19
+ /**
20
+ * The tries of a draft, one per round, oldest first. The free retry after a broken reply (a `structure-retry` round) keeps the number of the try it
21
+ * retries: "try N again", never a new number. `reds` are the checker's raw refusals; `outcome` is a non-validator round's plain words, `rawOutcome` its own raw words.
22
+ * @param {any[]} rounds the draft's log.json `log`
23
+ * @returns {Array<{ label: string, passed: boolean, reds: string[], outcome: string, rawOutcome: string, again: boolean }>}
24
+ */
25
+ export function triesOf(rounds) {
26
+ let no = 0;
27
+ return (Array.isArray(rounds) ? rounds : []).map((e, i, all) => {
28
+ const again = e?.kind === 'structure-retry' && i > 0;
29
+ if (!again) no += 1;
30
+ const passed = e?.outcome === 'valid';
31
+ const outcome = typeof e?.outcome === 'string' ? e.outcome.replace(/^structure: /, '') : '';
32
+ const brokenThenRetried = !passed && String(e?.outcome).startsWith('structure: ') && all[i + 1]?.kind === 'structure-retry';
33
+ return {
34
+ label: again ? `try ${no} again` : `try ${no}`,
35
+ passed,
36
+ reds: Array.isArray(e?.reds) ? e.reds.map(String) : [],
37
+ outcome: brokenThenRetried ? 'the reply came back broken; one free retry' : outcome,
38
+ rawOutcome: outcome,
39
+ again,
40
+ };
41
+ });
22
42
  }
23
43
 
24
44
  /**
25
- * @param {{ log: any, declaration: any }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
26
- * @returns {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }> | null}
45
+ * `questionOpen` (am15 item 3): the plan asked a question and the draft has NOT ended: its plan-checks line is not red and has no Fix ("red appears only on a draft that ended red").
46
+ * @param {{ log: any, declaration: any, questionOpen?: boolean }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
47
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
27
48
  */
28
- export function draftStepList({ log, declaration }) {
49
+ export function draftStepList({ log, declaration, questionOpen = false }) {
29
50
  if (log === null || typeof log !== 'object') return null;
30
51
  const rounds = Array.isArray(log.log) ? log.log : [];
31
- /** @type {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }>} */
52
+ /** @type {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }>} */
32
53
  const out = [];
33
54
 
34
55
  const t = log.thinking;
@@ -38,18 +59,18 @@ export function draftStepList({ log, declaration }) {
38
59
  }
39
60
 
40
61
  if (Array.isArray(log.inputs) && log.inputs.length > 0) {
41
- out.push({ id: 'inputs', label: 'inputs', status: 'done', details: log.inputs.map((i) => `${i.role}: ${i.detail}`) });
62
+ out.push({ id: 'inputs', label: ['inputs', ...log.inputs.map((i) => `${i.role}: ${i.detail}`)].join(' · '), status: 'done', details: [] });
42
63
  }
43
64
 
44
65
  // a plan came back (valid or refused by the checker) vs. a round that never gave one (provider red, cut off, budget)
45
66
  const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
46
67
  const n = typeof log.rounds === 'number' ? log.rounds : 0;
47
68
  const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
48
- const drafted = { id: 'drafted', label: `drafted with ${who}`, status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [`${n} round${n === 1 ? '' : 's'} · ${money(log)}`] };
49
- if (!gotPlan) drafted.details.push(...(Array.isArray(log.reds) ? log.reds.map(String) : []));
50
- out.push(drafted);
51
-
52
69
  const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
70
+ const facts = ['drafted', who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
71
+ if (!gotPlan && reds.length > 0) facts.push(reds[0]); // no plan at all (provider red, cut off): its own words, there is no checker text
72
+ out.push({ id: 'drafted', label: facts.join(' · '), status: /** @type {'done'|'failed'} */ (gotPlan ? 'done' : 'failed'), details: [] });
73
+
53
74
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
54
75
  const rubricReds = [];
55
76
  const checkReds = [];
@@ -58,22 +79,60 @@ export function draftStepList({ log, declaration }) {
58
79
  if (m) rubricReds.push(`line ${steps[Number(m[1])]?.fromLine ?? '?'}: ${m[2]}`); else checkReds.push(r);
59
80
  }
60
81
  if (gotPlan) {
61
- out.push(log.ok === true
62
- ? { id: 'checks', label: 'plan checks', status: 'done', details: [] }
63
- : { id: 'checks', label: 'plan checks', status: 'failed', details: [], reds: checkReds });
82
+ if (log.ok === true) {
83
+ // N = the number of the try that passed, minus one (a free retry after a broken reply keeps its try's number)
84
+ const tries = triesOf(rounds);
85
+ const fixedAfter = tries.length > 0 && tries[tries.length - 1].passed ? tries.filter((x) => !x.again).length - 1 : 0;
86
+ out.push({ id: 'checks', label: fixedAfter > 0 ? `plan checks · fixed by the AI after ${fixedAfter} ${fixedAfter === 1 ? 'try' : 'tries'}` : 'plan checks', status: 'done', details: [] });
87
+ } else if (questionOpen) {
88
+ out.push({ id: 'checks', label: 'plan checks · a question for you', status: 'waiting', details: [] });
89
+ } else {
90
+ // one plain reason and its one Fix line (every rule has fix wording): the first refusal
91
+ const pick = checkReds.map(plainPlanCheck)[0];
92
+ out.push({ id: 'checks', label: pick ? `plan checks · ${pick.reason}` : 'plan checks', status: 'failed', details: [] });
93
+ if (pick) out.push({ id: 'checks-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true });
94
+ }
64
95
  }
65
96
 
66
97
  if (log.ok === true) {
67
98
  const soft = steps.filter((s) => s?.close?.class === 'softgreen');
68
- if (soft.length > 0) out.push({ id: 'rubrics', label: 'rubrics', status: 'done', details: soft.map((s) => `line ${s.fromLine}: built`) });
99
+ if (soft.length > 0) out.push({ id: 'rubrics', label: ['rubrics', ...soft.map((s) => `line ${s.fromLine}`)].join(' · '), status: 'done', details: [] });
69
100
  } else if (rubricReds.length > 0) {
70
- out.push({ id: 'rubrics', label: 'rubrics', status: 'failed', details: rubricReds });
101
+ out.push({ id: 'rubrics', label: ['rubrics', ...rubricReds].join(' · '), status: 'failed', details: [] });
71
102
  }
72
103
 
73
- rounds.forEach((e, i) => {
74
- if (i === 0) return;
75
- const no = i + 1;
76
- out.push({ id: `try-${no}`, label: no <= TRIES ? `try ${no} of ${TRIES}` : `try ${no}`, status: e.outcome === 'valid' ? 'done' : 'failed', ...reasonOf(rounds[i - 1]) });
77
- });
78
104
  return out;
79
105
  }
106
+
107
+ /**
108
+ * M4d amendment 15, every line of the list: the line of ONE revise (or the redraft after answers), from that plan folder's own log.json. Same rules as `draftStepList`:
109
+ * one line, `<name> · <model> · <n rounds> · <cost>` and, for a plan that passed after refused tries, `fixed by the AI after N tries`; a red one carries one plain
110
+ * reason (and the Fix line under it), never details, folds or raw checker text. The try-by-try history is `triesOf` (the Audit Draft group). `null` = no log.
111
+ * @param {{ log: any, name: string }} p
112
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
113
+ */
114
+ export function reviseStepList({ log, name }) {
115
+ if (log === null || typeof log !== 'object') return null;
116
+ const rounds = Array.isArray(log.log) ? log.log : [];
117
+ const n = typeof log.rounds === 'number' ? log.rounds : 0;
118
+ const who = typeof log.modelId === 'string' && log.modelId !== '' ? log.modelId : 'the drafter';
119
+ const facts = [name, who, `${n} round${n === 1 ? '' : 's'}`, money(log)];
120
+ const reds = Array.isArray(log.reds) ? log.reds.map(String) : [];
121
+ if (log.ok === true) {
122
+ const tries = triesOf(rounds);
123
+ const fixedAfter = tries.length > 0 && tries[tries.length - 1].passed ? tries.filter((x) => !x.again).length - 1 : 0;
124
+ if (fixedAfter > 0) facts.push(`fixed by the AI after ${fixedAfter} ${fixedAfter === 1 ? 'try' : 'tries'}`);
125
+ return [{ id: 'plan', label: facts.join(' · '), status: 'done', details: [] }];
126
+ }
127
+ const gotPlan = rounds.some((e) => e.outcome === 'valid' || String(e.outcome).startsWith('validator'));
128
+ const checkReds = reds.filter((r) => !REBUILD_RE.test(r));
129
+ if (!gotPlan || checkReds.length === 0) {
130
+ if (reds.length > 0) facts.push(reds[0]);
131
+ return [{ id: 'plan', label: facts.join(' · '), status: 'failed', details: [] }];
132
+ }
133
+ const pick = plainPlanCheck(checkReds[0]);
134
+ return [
135
+ { id: 'plan', label: [name, pick.reason].join(' · '), status: 'failed', details: [] },
136
+ { id: 'plan-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true },
137
+ ];
138
+ }