fwdloop 0.4.0 → 0.5.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/src/send.js ADDED
@@ -0,0 +1,44 @@
1
+ // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED"): the live `sendStep(target, filename, content)` `src/runner.js`'s
3
+ // `runFlow` expects. `checkSendDestination` — the containment check
4
+ // (lexical AND realpath, write-time re-check) — is owned by `src/runner.js`
5
+ // (piece 1 already wrote it); this module imports it rather than growing a
6
+ // second writer of the same rule.
7
+ //
8
+ // borrowed-from: fwdloop poc/m0/runner.mjs@76a3607 (`sendViaPrimitive`: a
9
+ // real `shell_write` call, never a bespoke `writeFileSync` standing in for
10
+ // it, and the "happened" re-read of the bytes ACTUALLY on disk — never the
11
+ // in-memory content handed in — so a write that silently truncates to 0
12
+ // bytes reds here, not upstream).
13
+
14
+ import { readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { createShellTools } from 'bare-agent/tools';
17
+
18
+ import { checkSendDestination } from './runner.js';
19
+
20
+ const { tools: SHELL_TOOLS } = createShellTools();
21
+ const FOUND_WRITE_TOOL = SHELL_TOOLS.find((t) => t.name === 'shell_write');
22
+ if (!FOUND_WRITE_TOOL) throw new Error('send: bare-agent/tools does not export a "shell_write" tool');
23
+ const WRITE_TOOL = FOUND_WRITE_TOOL;
24
+
25
+ /**
26
+ * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
27
+ * @param {string} filename
28
+ * @param {unknown} content - JSON-serialised before writing.
29
+ * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
30
+ */
31
+ export async function sendViaPrimitive(target, filename, content) {
32
+ const destination = checkSendDestination(target);
33
+ if (!destination.ok) return { ok: false, red: destination.red };
34
+
35
+ const path = join(destination.dir, filename);
36
+ const serialised = JSON.stringify(content ?? null, null, 2);
37
+ await WRITE_TOOL.execute({ path, content: serialised });
38
+
39
+ const bytes = readFileSync(path);
40
+ if (bytes.byteLength === 0) {
41
+ return { ok: false, red: `send: "${path}" wrote 0 bytes` };
42
+ }
43
+ return { ok: true, path, bytes: bytes.byteLength };
44
+ }
package/src/types.js CHANGED
@@ -230,4 +230,75 @@
230
230
 
231
231
  /** @typedef {ReadFlowOk | ReadFlowRed} ReadFlowResult */
232
232
 
233
+ /**
234
+ * M2 piece 1 — a step's fresh executor context: "goal in, gap back". No
235
+ * other field may ever appear here (src/runner.js's construction test
236
+ * proves it) — in particular never the step's close, its shape, the cap, or
237
+ * the strike count.
238
+ * @typedef {object} ExecutorContext
239
+ * @property {string} goal
240
+ * @property {string[]} primitives
241
+ * @property {Record<string, any>} reads
242
+ * @property {string|null} gap
243
+ */
244
+
245
+ /**
246
+ * A green-class field value: `value` is the number/ISO-date/text claimed;
247
+ * `cite` resolves it (src/closers.js's own grammar).
248
+ * @typedef {object} GreenField
249
+ * @property {string|number} value
250
+ * @property {string} cite
251
+ */
252
+
253
+ /** @typedef {{ fields: Record<string, GreenField> }} GreenArtifact */
254
+ /** @typedef {{ text: string, lines?: string[] }} SoftgreenArtifact */
255
+
256
+ /**
257
+ * The result of any of src/closers.js's close functions.
258
+ * @typedef {object} CloseVerdict
259
+ * @property {'green'|'red'|'hitl'|'unparseable'|'crash'} verdict
260
+ * @property {string|null} [red]
261
+ * @property {string[]} [reds]
262
+ */
263
+
264
+ /**
265
+ * One row appended to `runs/<run-id>/audit.jsonl` (M2 scope item 9).
266
+ * @typedef {object} AuditRow
267
+ * @property {string|null} step
268
+ * @property {number} attempt
269
+ * @property {string|null} class
270
+ * @property {string} verdict
271
+ * @property {string|null} gap
272
+ * @property {number|null} usd
273
+ * @property {boolean} spendComplete
274
+ * @property {number} wallMs
275
+ * @property {string|null} model
276
+ * @property {boolean|null} modelMatch
277
+ * @property {boolean} strike
278
+ */
279
+
280
+ /**
281
+ * One row appended to `flows/<name>/history.jsonl` (M2 scope item 9).
282
+ * @typedef {object} HistoryRow
283
+ * @property {string} runId
284
+ * @property {string} at
285
+ * @property {string} outcome
286
+ * @property {number|null} spentUsd
287
+ * @property {boolean} spendComplete
288
+ * @property {number|null} capUsd
289
+ * @property {number} wallMs
290
+ * @property {string|null} signatureHash
291
+ */
292
+
293
+ /**
294
+ * @typedef {object} RunFlowResult
295
+ * @property {string} outcome
296
+ * @property {string} [red]
297
+ * @property {string[]} [reds]
298
+ * @property {string} [runDir]
299
+ * @property {Record<string, any>} [artifacts]
300
+ * @property {number} [spentUsd]
301
+ * @property {AuditRow[]} [auditRows]
302
+ */
303
+
233
304
  export {};
package/types/ask.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
3
+ * @returns {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:string, reason?:string}>}
4
+ */
5
+ export function makeFileAskStep({ timeoutMs, pollMs, clock, writeLine, }?: {
6
+ timeoutMs?: number;
7
+ pollMs?: number;
8
+ clock?: () => string;
9
+ writeLine?: (line: string) => void;
10
+ }): (opts: {
11
+ question: string;
12
+ evidence: unknown;
13
+ runDir: string;
14
+ }) => Promise<{
15
+ decision: string;
16
+ reason?: string;
17
+ }>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * One row per attempt (also used for one row per ask and one row per send —
3
+ * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
4
+ * spendComplete, wallMs, model, modelMatch, strike }`. Append-only, one
5
+ * writer.
6
+ *
7
+ * @param {string} runDir
8
+ * @param {Record<string, any>} row
9
+ */
10
+ export function appendAudit(runDir: string, row: Record<string, any>): void;
11
+ /**
12
+ * One row per run. `row` shape: `{ runId, at, outcome, spentUsd,
13
+ * spendComplete, capUsd, wallMs, signatureHash }`. Append-only, one writer.
14
+ *
15
+ * @param {string} flowDir
16
+ * @param {Record<string, any>} row
17
+ */
18
+ export function appendHistory(flowDir: string, row: Record<string, any>): void;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `green` close: every field in `artifact.fields`, in declared order,
3
+ * resolves and matches its cite. First red wins.
4
+ *
5
+ * @param {any} artifact
6
+ * @param {{ reads: Record<string, any>, businessDate: string }} ctx
7
+ * @returns {CloseVerdict}
8
+ */
9
+ export function closeGreen(artifact: any, ctx: {
10
+ reads: Record<string, any>;
11
+ businessDate: string;
12
+ }): CloseVerdict;
13
+ /**
14
+ * The declared-shape word-cap + ordered-sections check, F38 version (every
15
+ * failing check reported, not just the first). Identical rules to
16
+ * poc/m0/shape.mjs's own `closeWordsAndSections`.
17
+ *
18
+ * @param {unknown} text
19
+ * @param {{ maxWords: number, sections: string[] }} declared
20
+ * @returns {CloseVerdict}
21
+ */
22
+ export function closeWordsAndSections(text: unknown, { maxWords, sections }: {
23
+ maxWords: number;
24
+ sections: string[];
25
+ }): CloseVerdict;
26
+ /**
27
+ * `linesPerInvoice`/`mustCarry`: group `text`'s own non-empty lines into
28
+ * blocks of `linesPerInvoice` lines; every `mustCarry` string must appear
29
+ * (case-insensitive substring) somewhere in each block. Returns an array of
30
+ * red strings (empty when clean) — the caller folds these into its own
31
+ * `reds` list alongside `closeWordsAndSections`'s.
32
+ */
33
+ export function closeLinesAndCarry(text: any, { linesPerInvoice, mustCarry }: {
34
+ linesPerInvoice: any;
35
+ mustCarry: any;
36
+ }): string[];
37
+ /**
38
+ * `softgreen` close: dispatches to `closeWordsAndSections` (when the shape
39
+ * declares `maxWords`/`sections`) and/or `closeLinesAndCarry` (when it
40
+ * declares `linesPerInvoice`/`mustCarry`) and reports every failing check
41
+ * from both, one sentence each (F38's rule, never widened to first-red-only).
42
+ *
43
+ * @param {any} artifact
44
+ * @param {{ maxWords?: number, sections?: string[], linesPerInvoice?: number, mustCarry?: string[] }} shape
45
+ * @returns {CloseVerdict}
46
+ */
47
+ export function closeSoftgreen(artifact: any, shape: {
48
+ maxWords?: number;
49
+ sections?: string[];
50
+ linesPerInvoice?: number;
51
+ mustCarry?: string[];
52
+ }): CloseVerdict;
53
+ /**
54
+ * The one dispatcher — `close by declared class` (M2 scope item 4).
55
+ *
56
+ * @param {{ close?: { class?: string, shape?: Record<string, any> } }} step
57
+ * @param {unknown} artifact
58
+ * @param {{ reads: Record<string, any>, businessDate: string }} ctx
59
+ * @returns {CloseVerdict}
60
+ */
61
+ export function closeByClass(step: {
62
+ close?: {
63
+ class?: string;
64
+ shape?: Record<string, any>;
65
+ };
66
+ }, artifact: unknown, ctx: {
67
+ reads: Record<string, any>;
68
+ businessDate: string;
69
+ }): CloseVerdict;
70
+ export type CloseVerdict = import("./types.js").CloseVerdict;
package/types/csv.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /** Column letter for a 0-based column index: 0 -> 'A', 1 -> 'B', ... */
2
+ export function colLetter(i: any): string;
3
+ /** Column index (0-based) for a column letter: 'A' -> 0, 'B' -> 1, ... */
4
+ export function colIndex(letter: any): number;
5
+ /** Parse a cell ref like "E2" into { col: 'E', row: 2 }. */
6
+ export function parseCellRef(cell: any): {
7
+ col: string;
8
+ row: number;
9
+ };
10
+ /**
11
+ * Parse CSV text with no quoted fields into { header, rows }.
12
+ * `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' } }`
13
+ * where `rowNumber` is the 1-based sheet row (header is row 1, first data row is row 2).
14
+ */
15
+ export function parseCsv(text: any): {
16
+ header: any;
17
+ rows: {
18
+ rowNumber: number;
19
+ cells: {};
20
+ byName: {};
21
+ }[];
22
+ };
@@ -1,3 +1,24 @@
1
+ /**
2
+ * A small, pure walker over `declaration.steps` for callers that only want
3
+ * the shape-key verdict (e.g. poc/m1/slot-batch.mjs's `shape` column) —
4
+ * never a substitute for `validateDeclaration`, which is still the one
5
+ * check that decides pass/fail for a real declaration. Reuses the same
6
+ * `checkShapeKeys` `validateDeclaration` calls, so the two can never drift
7
+ * apart on what counts as a known shape key.
8
+ *
9
+ * A non-array `declaration.steps` (or a non-object `declaration` at all)
10
+ * reds `'no steps array'` rather than throwing. `shapedSteps` counts every
11
+ * step whose `close` carries a `shape` key at all — a step that TRIED to
12
+ * carry a shape, known-key or not, plain-object or not. A `shape` that
13
+ * isn't a plain object (array, string, number, null) reds
14
+ * `"... .close.shape must be an object"`, matching `validateDeclaration`'s
15
+ * own red for the same malformed input.
16
+ */
17
+ export function checkShapes(declaration: any): {
18
+ verdict: string;
19
+ reds: any[];
20
+ shapedSteps: number;
21
+ };
1
22
  /**
2
23
  * Validate a drafter declaration against the M1 closed schema. `arbiter`
3
24
  * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
@@ -22,6 +43,10 @@ export function validateDeclaration(declaration: unknown, context?: {
22
43
  * kept in sync with the checks below so a mutation suite can assert it
23
44
  * tested every one of them (same trick as ARBITER_FIELDS/SIGNATURE_FIELDS). */
24
45
  export const DECLARATION_FIELDS: readonly string[];
46
+ /** The typed `close.shape` vocabulary, signed by hamr 2026-09-23 (v1):
47
+ * exactly these four top-level keys. Anything else inside `shape` reds by
48
+ * name. */
49
+ export const SHAPE_KEYS: readonly string[];
25
50
  export type Arbiter = import("./types.js").Arbiter;
26
51
  export type SignedLine = import("./types.js").SignedLine;
27
52
  export type CatalogueEntry = import("./types.js").CatalogueEntry;
@@ -0,0 +1,10 @@
1
+ /** @param {string} path @returns {{ok:true,text:string,paragraphs:number}|{ok:false,red:string}} */
2
+ export function readDocxText(path: string): {
3
+ ok: true;
4
+ text: string;
5
+ paragraphs: number;
6
+ } | {
7
+ ok: false;
8
+ red: string;
9
+ };
10
+ export const DOCX_MAX_UNCOMPRESSED_BYTES: number;
package/types/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ export { closeByClass } from "./closers.js";
1
2
  export { parseSignedText, ARBITER_FIELDS } from "./signed-text.js";
2
3
  export { signFlow, verifyFlow, canonicalBytes, SIGNATURE_FIELDS } from "./signature.js";
3
4
  export { validateDeclaration, DECLARATION_FIELDS } from "./declaration.js";
4
5
  export { parseCatalogue, loadCatalogue, menu, primitiveFor, resolveEntry, CATALOGUE_FIELDS } from "./catalogue.js";
5
6
  export { checkFlowName, writeFlow, readFlow, FLOW_FILES } from "./flow.js";
7
+ export { runFlow, STRIKE_LIMIT, MAX_ATTEMPTS } from "./runner.js";
@@ -0,0 +1,112 @@
1
+ /**
2
+ * True for a transport-layer fault (a request that never reached or never
3
+ * heard back from the provider) — never true for an application-level
4
+ * failure (an HTTP status the provider server actually sent, a wall-clock
5
+ * deadline). `EDEADLINE` (bare-agent's BA-19 total wall-clock ceiling) is
6
+ * explicitly excluded: M2 scope item 8 says a wall-clock timeout is NEVER
7
+ * retried, so it must never be classified as the retryable `transport`
8
+ * shape however similar its symptom looks.
9
+ *
10
+ * @param {any} err
11
+ */
12
+ export function isTransportFailure(err: any): boolean;
13
+ /**
14
+ * Build the `emit_artifact` tool schema from a step's declared close CLASS
15
+ * only. `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`.
16
+ */
17
+ export function buildEmitArtifactSchema(stepClass: any): Readonly<{
18
+ type: "object";
19
+ properties: {
20
+ done: {
21
+ type: string;
22
+ description: string;
23
+ };
24
+ blocker: {
25
+ type: string[];
26
+ description: string;
27
+ };
28
+ fields: {
29
+ type: string;
30
+ additionalProperties: {
31
+ type: string;
32
+ properties: {
33
+ value: {};
34
+ cite: {
35
+ type: string;
36
+ };
37
+ };
38
+ required: string[];
39
+ };
40
+ };
41
+ };
42
+ required: string[];
43
+ }> | Readonly<{
44
+ type: "object";
45
+ properties: {
46
+ done: {
47
+ type: string;
48
+ description: string;
49
+ };
50
+ blocker: {
51
+ type: string[];
52
+ description: string;
53
+ };
54
+ text: {
55
+ type: string;
56
+ };
57
+ lines: {
58
+ type: string;
59
+ items: {
60
+ type: string;
61
+ };
62
+ };
63
+ };
64
+ required: string[];
65
+ }> | Readonly<{
66
+ type: "object";
67
+ properties: {
68
+ done: {
69
+ type: string;
70
+ description: string;
71
+ };
72
+ blocker: {
73
+ type: string[];
74
+ description: string;
75
+ };
76
+ text: {
77
+ type: string;
78
+ };
79
+ cells: {
80
+ type: string;
81
+ };
82
+ };
83
+ required: string[];
84
+ additionalProperties: true;
85
+ }>;
86
+ /**
87
+ * @param {object} opts
88
+ * @param {string} [opts.slot] - a `src/provider.js` PROVIDER_SLOTS name; required when `provider` isn't injected.
89
+ * @param {string} [opts.model] - overrides the slot's default model.
90
+ * @param {string} opts.spendPath - the run's spend.jsonl (never a second ledger).
91
+ * @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
92
+ * @param {{in:number,out:number}} [opts.rates]
93
+ * @param {string} [opts.modelId]
94
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}) => Promise<any>}
95
+ */
96
+ export function makeLiveModelStep({ slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, }: {
97
+ slot?: string | undefined;
98
+ model?: string | undefined;
99
+ spendPath: string;
100
+ provider?: any;
101
+ rates?: {
102
+ in: number;
103
+ out: number;
104
+ } | undefined;
105
+ modelId?: string | undefined;
106
+ }): (executorContext: object, grantedTools: Record<string, any>, stepMeta?: {
107
+ class?: string;
108
+ }) => Promise<any>;
109
+ export const LIVE_PROVIDER_OPTIONS: Readonly<{
110
+ timeoutMs: 300000;
111
+ deadlineMs: 240000;
112
+ }>;
@@ -0,0 +1,26 @@
1
+ /** Which primitive owns a frozen input's text, by extension of its frozen path —
2
+ * `.md`/`.txt` are read/grep's own text roles, `.docx` belongs to `readDocx`,
3
+ * `.csv` belongs to `addressCells`, anything else has no text primitive.
4
+ * Pure and exported so tests can hit the four cases directly (F41 item 3). */
5
+ export function rolePrimitiveFor(frozenPath: any): "read" | "readDocx" | "addressCells" | null;
6
+ /**
7
+ * Resolve the granted tools for one step's model call. Never throws —
8
+ * a verb absent from the catalogue, or present but unimplemented here, is
9
+ * reported in `reds` and simply absent from `tools` (menu-is-inventory:
10
+ * absence, not a stub).
11
+ *
12
+ * @param {import('./types.js').CatalogueEntry[]} catalogue - `loadCatalogue().primitives` (or an injected test catalogue).
13
+ * @param {string[]} grantedVerbs - `step.primitives`.
14
+ * @param {{ runDir: string, inputs?: Array<{id:string, frozen:string}> }} ctx
15
+ * @returns {{ tools: Record<string, any>, reds: string[] }}
16
+ */
17
+ export function resolvePrimitives(catalogue: import("./types.js").CatalogueEntry[], grantedVerbs: string[], ctx: {
18
+ runDir: string;
19
+ inputs?: Array<{
20
+ id: string;
21
+ frozen: string;
22
+ }>;
23
+ }): {
24
+ tools: Record<string, any>;
25
+ reds: string[];
26
+ };