fwdloop 0.16.0 → 0.17.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/README.md +2 -0
- package/bin/fwdloop +8 -6
- package/package.json +1 -1
- package/src/authoring.js +6 -6
- package/src/catalogue.json +9 -3
- package/src/ctx-tools.js +245 -0
- package/src/draft-steps.js +89 -30
- package/src/drafter.js +28 -4
- package/src/draftspend.js +109 -3
- package/src/liveness.js +34 -10
- package/src/panel/author.js +101 -33
- package/src/panel/authorcard.js +13 -9
- package/src/panel/authorflows.js +3 -3
- package/src/panel/authorresume.js +5 -4
- package/src/panel/authorvalues.js +5 -3
- package/src/panel/data.js +17 -5
- package/src/panel/index.html +74 -42
- package/src/panel/server.js +10 -5
- package/src/panel/settings.js +2 -2
- package/src/plain-checks.js +51 -0
- package/src/primitives.js +34 -3
- package/src/provider.js +17 -8
- package/src/run-store.js +47 -0
- package/src/runner.js +2 -0
- package/src/setup.js +3 -0
- package/src/version.js +13 -0
- package/types/authoring.d.ts +1 -3
- package/types/ctx-tools.d.ts +18 -0
- package/types/draft-steps.d.ts +38 -5
- package/types/drafter.d.ts +3 -3
- package/types/draftspend.d.ts +56 -0
- package/types/liveness.d.ts +7 -1
- package/types/panel/author.d.ts +5 -5
- package/types/panel/authorcard.d.ts +12 -2
- package/types/panel/authorflows.d.ts +3 -3
- package/types/panel/authorvalues.d.ts +3 -1
- package/types/panel/server.d.ts +4 -2
- package/types/plain-checks.d.ts +22 -0
- package/types/primitives.d.ts +0 -6
- package/types/provider.d.ts +7 -1
- package/types/run-store.d.ts +11 -0
- package/types/setup.d.ts +8 -0
- 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 {
|
|
@@ -810,7 +811,7 @@ async function cmdDraft(rest) {
|
|
|
810
811
|
const { values, positionals } = parseArgs({
|
|
811
812
|
args: rest,
|
|
812
813
|
options: {
|
|
813
|
-
out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' },
|
|
814
|
+
out: { type: 'string' }, root: { type: 'string' }, name: { type: 'string' },
|
|
814
815
|
// 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
816
|
'no-questions': { type: 'boolean' },
|
|
816
817
|
// 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 +823,7 @@ async function cmdDraft(rest) {
|
|
|
822
823
|
const keysLoad = keyedLoad();
|
|
823
824
|
const { env } = keysLoad;
|
|
824
825
|
const proseFile = positionals[0];
|
|
825
|
-
if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow>
|
|
826
|
+
if (!proseFile) fail('draft: a prose file is required — fwdloop draft <prose.txt> --out <draftDir> --root <flowsDir> --name <flow>');
|
|
826
827
|
for (const req of ['out', 'root', 'name']) if (!values[req]) fail(`draft: --${req} is required`);
|
|
827
828
|
|
|
828
829
|
let injected = {};
|
|
@@ -846,7 +847,7 @@ async function cmdDraft(rest) {
|
|
|
846
847
|
const refusal = draftKeyRefusal(pick.slot, env);
|
|
847
848
|
if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
|
|
848
849
|
} else if (values.model !== undefined) pick = { slot: values.provider, model: values.model };
|
|
849
|
-
// M4d piece 3: the monthly check —
|
|
850
|
+
// M4d piece 3: the monthly check — one ceiling round, priced from the
|
|
850
851
|
// picked model's own Settings prices (an injected test provider carries its own rates). A model that is not
|
|
851
852
|
// ticked with both prices is refused here by name, at $0, before the monthly hold or any draft folder (M4d amendment 5).
|
|
852
853
|
let ceiling;
|
|
@@ -863,15 +864,16 @@ async function cmdDraft(rest) {
|
|
|
863
864
|
if (!(err instanceof ConfigError)) throw err;
|
|
864
865
|
fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
|
|
865
866
|
}
|
|
867
|
+
// 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
|
|
868
|
+
const proseRead = readFileInside(dirname(resolve(proseFile)), basename(resolve(proseFile)));
|
|
866
869
|
takeMonthlyHold({
|
|
867
|
-
what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: ceiling,
|
|
870
|
+
what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
|
|
868
871
|
});
|
|
869
872
|
const result = await draftToDir({
|
|
870
873
|
proseFile: resolve(proseFile),
|
|
871
874
|
dir: resolve(values.out),
|
|
872
875
|
root: resolve(values.root),
|
|
873
876
|
name: values.name,
|
|
874
|
-
budgetUsd: values.budget === undefined ? undefined : Number(values.budget),
|
|
875
877
|
noQuestions: values['no-questions'] === true,
|
|
876
878
|
draftThinking: values.thinking === true ? 'on' : 'off',
|
|
877
879
|
env,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fwdloop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.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,
|
|
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,
|
|
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/catalogue.json
CHANGED
|
@@ -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
|
|
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
|
|
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": "
|
|
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."
|
package/src/ctx-tools.js
ADDED
|
@@ -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
|
+
}
|
package/src/draft-steps.js
CHANGED
|
@@ -1,34 +1,55 @@
|
|
|
1
|
-
// M4d amendment
|
|
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
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
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
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
*
|
|
26
|
-
* @
|
|
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[],
|
|
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',
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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',
|
|
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:
|
|
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
|
+
}
|