footprintjs 11.0.1 → 11.1.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/AGENTS.md CHANGED
@@ -1,1131 +1,266 @@
1
- # footprint.js — AI Coding Instructions
2
-
3
- This is the footprint.js library — the flowchart pattern for backend code. Self-explainable systems that AI can reason about.
4
-
5
- > TypeScript blocks in this file that import FootPrint are type-checked in CI with strict settings against the library's current source. CI does not run them: a `// …` comment under a `console.log` shows the output of a real run and may lag behind the code.
6
-
7
- ## Core Principle
8
-
9
- **Collect during traversal, never post-process.** All data collection (narrative, metrics, manifest, topology, in/out boundaries) happens as side effects of the single DFS traversal pass. Never walk the tree again after execution.
10
-
11
- ## Architecture — Library of Libraries
12
-
13
- FootPrint has seven entry points (doors); the record has three more in the separate `foottrace` package. Import from the package that owns the declaration; FootPrint does not re-export record declarations.
14
-
15
- | Import | What it is for |
16
- |---|---|
17
- | `footprintjs` | The main door: `flowChart`, `FlowChartExecutor`, `decide` / `select`, `narrative`, the built-in recorder classes, `interrupt`, and the public types |
18
- | `footprintjs/recorders` | Recorder factories — `narrative()`, `metrics()`, `debug()`, `manifest()`, `adaptive()`, `milestone()`, `windowed()` — and `CompositeRecorder` |
19
- | `footprintjs/trace` | Engine tracing: recorder stores (`KeyedStore`, `SequenceStore`, `BoundaryStateStore`), `walkSubflowSpec`, `topologyRecorder()` / `inOutRecorder()`, control-dependency and quality recorders |
20
- | `foottrace` | Record shapes (`CommitBundle`, `TraceEntry`, `MemoryPatch`), runtime-ID helpers, commit queries, causal/variable slices, `stateAt`, `timeTravel`, `CommitRangeIndex`, `HONESTY_CODES` |
21
- | `foottrace/write` | Writing a record yourself: the record layer the engine writes with — `SharedMemory` (the heap), `EventLog` (the log), `RecordFrame` (one step's frame) and their option types |
22
- | `foottrace/paths` | Record-path encoding/decoding, safe nested access, `setNestedValue` / `updateNestedValue` for diagnostic bags |
23
- | `footprintjs/advanced` | Engine internals (`StageContext`, `FlowchartTraverser`, `ScopeFacade`, scope providers, `SCOPE_METHOD_NAMES`, `ArrayMergeMode`, run policy and `RedactionRule`). No record declarations are exported here. |
24
- | `footprintjs/detach` | Fire-and-forget child charts and their drivers |
25
- | `footprintjs/zod` | Opt-in zod bridge (`defineScopeFromZod`, …) — the core never imports zod |
26
- | `footprintjs/sinks` | NODE ONLY — `fileSink(path)` / `readRecordFile(path)`: the crash-safe record as JSON lines (the executor's `sink` option; read back with foottrace's `readStoredRecord`) |
27
-
28
- The engine module map and layering rule live in this repository's `CLAUDE.md` and `scripts/layering.config.cjs` (on GitHub, not in the npm package), enforced by lint and `npm run check:layering`. The standalone record has its own fence in foottrace. Engine code must use named public foottrace imports, never a private path or a local copy of a record rule.
29
-
30
- ## Key API
31
-
32
- ### TypedScope (Recommended)
1
+ # FootPrint: connected runtime logs for people and AI agents
2
+
3
+ <!-- Generated from ai-instructions/source by scripts/ai-instructions/generate.mjs. Edit the source, then run npm run ai:generate. -->
4
+
5
+ ## What FootPrint is
6
+
7
+ **Connected runtime logs for people and AI agents.**
8
+
9
+ FootPrint runs your logic as a flowchart of named stages. While it runs, it records what each stage read and wrote, which decision was taken and why, and every retry. No model is involved and nothing is rebuilt afterwards. A person or an agent follows a result back through the record instead of guessing from separate log lines.
10
+
11
+ The one law: collect during the run, and never walk the tree afterwards. Evidence that was not collected stays unknown. The record shows what the program did, not whether it was right.
12
+
13
+ ## How a chart runs
14
+
15
+ - **Build:** `flowChart<T>()` starts a chart. `.addFunction()` and the branch methods add stages. `.build()` fixes its shape.
16
+ - **Run:** `FlowChartExecutor` walks the chart once with `run({ input, env })`. A stage's writes are staged, then committed when the stage ends.
17
+ - **Read:** recorders fire during the run. `getSnapshot()` and `getNarrativeEntries()` serve the result. `foottrace` queries the record afterwards.
18
+
19
+ ## Import map
20
+
21
+ Import a name from the door that owns it. FootPrint does not re-export the record, so its readers come straight from `foottrace`. If you import it yourself, add it to your dependencies and keep one installed copy (`npm ls foottrace`).
22
+
23
+ | Import | What it is for | Common names |
24
+ | --- | --- | --- |
25
+ | `footprintjs` | The main door: build, run, decide, retry, pause. | `flowChart`, `FlowChartExecutor`, `decide`, `select`, `narrative`, `attempt`, `exponentialBackoff`, `timeBudget`, `interrupt`, `TypedScope`, `RetryPolicy`, `FlowRecorder`, `CombinedRecorder` |
26
+ | `footprintjs/recorders` | Recorder factories. | `narrative`, `attempts`, `metrics`, `debug`, `manifest`, `adaptive`, `milestone`, `windowed`, `memoryStore`, `CompositeRecorder` |
27
+ | `footprintjs/trace` | Engine recorders, recorder stores and structure walkers. Not the record. | `controlDepRecorder`, `topologyRecorder`, `inOutRecorder`, `QualityRecorder`, `KeyedStore`, `SequenceStore`, `BoundaryStateStore`, `walkSubflowSpec` |
28
+ | `footprintjs/detach` | Fire-and-forget child charts and their drivers. | `microtaskBatchDriver`, `immediateDriver`, `setTimeoutDriver`, `flushAllDetached`, `DetachHandle` |
29
+ | `footprintjs/sinks` | Node only. The crash-safe record as a JSON-lines file. | `fileSink`, `readRecordFile`, `openIndexedRecordFile` |
30
+ | `footprintjs/zod` | Opt-in zod scope helpers. zod is an optional peer. | `defineScopeFromZod`, `defineScopeSchema`, `ZodScopeResolver` |
31
+ | `footprintjs/advanced` | Engine internals. Use them to extend the engine, not to write a chart. | `ArrayMergeMode`, `SubflowMountOptions`, `StageSnapshot`, `ScopeFacade`, `registerScopeRuntime`, `SCOPE_METHOD_NAMES`, `StageContext`, `FlowchartTraverser` |
32
+ | `foottrace` | Read a record: shapes, runtime IDs, commit queries, slices, time travel, stored records. | `findLastWriter`, `findCommit`, `causalChain`, `formatCausalChain`, `sliceForKey`, `stateAt`, `timeTravel`, `readStoredRecord`, `parseRuntimeStageId`, `CommitBundle`, `HONESTY_CODES` |
33
+ | `foottrace/write` | Write a record yourself. | `SharedMemory`, `EventLog`, `RecordFrame`, `memorySink` |
34
+ | `foottrace/paths` | Record-path rules, safe nested access and diagnostic-bag writes. | `setNestedValue`, `updateNestedValue` |
35
+ | `foottrace/cause` | Optional bounded cause, impact and attention queries. | `explain`, `attentionList` |
36
+ | `foottrace/metadata` | Optional value-free queries over path occurrences. | `readTraceMetadata`, `traceMetadata` |
37
+ | `foottrace/prov` | Optional export of one recorded scope as PROV-O, without values. | `exportProv` |
38
+
39
+ ## Find your task
40
+
41
+ Read the first path in the row and stop when you have your answer. For a signature or an option's meaning, read the JSDoc in `node_modules/footprintjs/dist/types/*.d.ts`, or the [generated reference](https://footprintjs.github.io/footPrint/api/).
42
+
43
+ Paths are in the repository, not the npm package, except those under `node_modules`. Open them at `https://github.com/footprintjs/footPrint/blob/main/<path>`.
44
+
45
+ | Task | Use | Read |
46
+ | --- | --- | --- |
47
+ | Write a first chart with typed state | `flowChart<T>()`, `.addFunction()`, `.build()`, `FlowChartExecutor` | `examples/getting-started/quick-start.ts`, `docs/guides/patterns.md#linear` |
48
+ | Read and write state, including dynamic keys | `scope.key`, `$setValue()`, `$update()`, `$batchArray()`, `$getArgs()`, `$getEnv()` | `src/lib/reactive/README.md`, `examples/runtime-features/typed-scope/01-structured-values.ts` |
49
+ | Choose branches and keep the evidence | `decide()`, `.addDeciderFunction()`, `.setDefault()`, `select()`, `.addSelectorFunction()` | `docs/guides/patterns.md#conditional-decider`, `examples/building-blocks/03-decider.ts`, `examples/building-blocks/04-selector.ts` |
50
+ | Run stages in parallel | `.addListOfFunction()`, `failFast` | `docs/guides/patterns.md#parallel-fork`, `examples/building-blocks/02-fork.ts` |
51
+ | Fan out one branch per item | `.addParallelForEach()` | `examples/runtime-features/parallel-for-each/01-fan-out-per-item.ts` |
52
+ | Compose charts | `.addSubFlowChartNext()`, `.addSubFlowChartBranch()`, `inputMapper`, `outputMapper` | `docs/guides/patterns.md#subflow-composition`, `examples/building-blocks/05-subflow.ts` |
53
+ | Loop, or stop early | `.loopTo()`, `scope.$break()`, `run({ maxIterations })` | `examples/building-blocks/06-loops.ts`, `docs/guides/patterns.md#loops` |
54
+ | Stream tokens from a stage | `.addStreamingFunction()` | `docs/guides/patterns.md#streaming-llm`, `examples/runtime-features/streaming/01-linear.ts` |
55
+ | Add a retry to a flaky stage | `.retry()`, `retryOn`, `errorCategory()` | `docs/guides/error-handling.md#declarative-retry`, `examples/runtime-features/retry/01-declare-a-retry.ts` |
56
+ | Choose a wait between tries | `exponentialBackoff()`, `statedWaitFirst()`, `maxBackoffMs` | `docs/guides/error-handling.md#backoff-schedules`, `examples/runtime-features/retry/08-backoff-helpers.ts` |
57
+ | Record calls made inside a stage | `scope.$call()`, `scope.$attempt()`, `attempt()` | `docs/guides/error-handling.md#retries-you-did-not-run`, `examples/runtime-features/retry/05-attempts-inside-a-stage.ts` |
58
+ | Retry a charge or other outside effect | `.touches()`, `idempotencyKey`, `UnknownEffectError` | `docs/guides/error-handling.md#side-effects`, `examples/runtime-features/retry/04-side-effects-and-idempotency.ts` |
59
+ | Check the outside system before resending | `.addRetryLoop()` | `src/lib/builder/README.md#explicit-retries-that-reconcile-an-outside-operation`, `examples/runtime-features/retry/06-explicit-reconciliation.ts` |
60
+ | Bound how long a run or a chart can take | `run({ deadline, timeoutMs, signal })`, `.budget()`, `timeBudget()` | `docs/guides/error-handling.md#time-budget`, `examples/runtime-features/retry/03-deadline-and-timeout.ts`, `examples/build-time-features/budget/01-time-budget.ts` |
61
+ | Handle a failed run | `getSnapshot()`, `getFailureContext()`, `onRunFailed` | `docs/guides/terminal-failure-context.md`, `docs/guides/error-handling.md#what-consumers-can-do-after-failure`, `examples/errors/04-terminal-failure-context.ts` |
62
+ | Pause for a person, then resume | `interrupt()`, `.addPausableFunction()`, `getCheckpoint()`, `resume()` | `docs/guides/execution-model.md#pause--resume--what-a-checkpoint-captures`, `examples/runtime-features/pause-resume/08-interrupt.ts` |
63
+ | Run work without waiting for it | `.addDetachAndForget()`, `.addDetachAndJoinLater()`, `scope.$detachAndForget()` | `examples/runtime-features/detach/README.md` |
64
+ | Get the run as sentences | `enableNarrative()`, `getNarrativeEntries()`, `narrative()` | `docs/guides/flow-recorders.md#quick-start`, `examples/runtime-features/flow-recorder/01-simple-observer.ts` |
65
+ | Keep a long loop's narrative short | `WindowedNarrativeFlowRecorder`, `RLENarrativeFlowRecorder` | `docs/guides/flow-recorders.md#built-in-loop-strategies`, `examples/runtime-features/flow-recorder/09-strategy-comparison.ts` |
66
+ | Write a recorder | `attachCombinedRecorder()`, `attachFlowRecorder()`, `attachScopeRecorder()`, `KeyedStore` | `docs/guides/flow-recorders.md#building-custom-flowrecorders`, `examples/recorders/README.md` |
67
+ | Emit your own events | `scope.$emit()`, `attachEmitRecorder()` | `examples/runtime-features/emit/01-custom-events.ts` |
68
+ | Keep a slow recorder off the run's path | `attachFlowRecorder(r, { delivery: 'deferred' })`, `drainObservers()` | `docs/guides/observers-deferred.md`, `examples/runtime-features/deferred-observers/01-basic.ts` |
69
+ | Measure attempts and latency | `attempts()`, `byTarget()`, `slowest()`, `toOTel()` | `docs/guides/attempt-metrics.md`, `examples/runtime-features/retry/07-attempt-metrics-and-trace.ts` |
70
+ | Show a viewer what needs a look | `StageSnapshot.attention` | `docs/guides/attention.md`, `examples/runtime-features/attention/01-stage-attention.ts` |
71
+ | Track the run's shape while it runs | `topologyRecorder()`, `inOutRecorder()` | `examples/runtime-features/flow-recorder/06-topology.ts`, `examples/runtime-features/flow-recorder/07-inout.ts` |
72
+ | Hide secrets | `setRedactionPolicy()`, `getRedactionReport()`, `getSnapshot({ redact: true })` | `docs/guides/scope.md#redaction-pii-protection`, `examples/runtime-features/redaction/01-linear.ts` |
73
+ | Find what caused a value | `findLastWriter()`, `causalChain()`, `sliceForKey()`, `controlDepRecorder()` | `examples/post-execution/causal-chain/01-linear.ts`, `examples/post-execution/variable-slice/01-why-is-this-value.ts` |
74
+ | Step through a finished run | `timeTravel()`, `stateAt()` | `examples/post-execution/time-travel/01-a-readers-cursor.ts`, `node_modules/foottrace/README.md` |
75
+ | Save a run and survive a crash | `fileSink()`, `readRecordFile()`, `readStoredRecord()` | `docs/guides/error-handling.md#a-crash-safe-record`, `examples/runtime-features/crash-safe-record/01-sink-and-incomplete-run.ts` |
76
+ | Say what a run captured, and save that | `captureCoverage`, `readStoredCapture()` | `docs/guides/capture-coverage.md`, `docs/guides/saved-capture-history.md` |
77
+ | Load one saved scope from a large file | `openIndexedRecordFile()` | `docs/guides/indexed-scope-loading.md`, `examples/runtime-features/crash-safe-record/04-indexed-scope-loading.ts` |
78
+ | Keep evidence of outside calls and their reads | `readSources`, `readAttempts` | `docs/guides/external-evidence.md`, `docs/guides/exact-read-sources.md` |
79
+ | Expose a chart as an API or an MCP tool | `.contract()`, `toOpenAPI()`, `toMCPTool()` | `docs/guides/contracts.md`, `examples/build-time-features/contract/01-zod-schema.ts` |
80
+ | Learn the supported limits | | `docs/guides/execution-model.md#summary--the-envelope-in-one-box`, `docs/guides/performance.md` |
81
+ | Say what the record cannot prove | | `docs/provenance-governance-and-limits.md` |
82
+
83
+ ## Three canonical snippets
84
+
85
+ Each is a real file in `ai-instructions/source/snippets/`. `npm run check:doc-snippets` compiles it. `npm run test:examples` runs it and compares its output with the `// Output:` lines.
86
+
87
+ ### Decide, then explain
33
88
 
34
89
  ```typescript
35
- import { flowChart, FlowChartExecutor } from 'footprintjs';
90
+ // Build a chart, run it, and read why it took a branch.
91
+ import { decide, flowChart, FlowChartExecutor } from 'footprintjs';
36
92
 
37
93
  interface LoanState {
38
- creditTier: string;
39
- amount: number;
40
- customer: { name: string; address: { zip: string } };
41
- tags: string[];
42
- approved?: boolean;
43
- }
44
-
45
- const chart = flowChart<LoanState>('Intake', async (scope) => {
46
- scope.creditTier = 'A'; // typed write
47
- scope.amount = 50000; // typed write
48
- scope.customer = { name: 'Ana', address: { zip: '10001' } };
49
- scope.tags = [];
50
- scope.customer.address.zip = '90210'; // deep write (recorded as an update of `customer`)
51
- scope.tags.push('vip'); // array copy-on-write (single push)
52
- scope.$batchArray('tags', (arr) => { // batch: one clone + one commit however many mutations
53
- arr.push('premium', 'verified');
54
- });
55
- scope.approved = true; // optional field
56
-
57
- // $-prefixed escape hatches
58
- scope.$debug('checkpoint', { step: 1 });
59
- scope.$metric('latency', 42);
60
- const args = scope.$getArgs<{ requestId: string }>();
61
- const env = scope.$getEnv();
62
- console.log(args.requestId, env.traceId);
63
- // req-123 trace-1
64
- scope.$break(); // stop the run
65
- }, 'intake')
66
- .build();
67
-
68
- const executor = new FlowChartExecutor(chart);
69
- executor.enableNarrative();
70
- await executor.run({ input: { requestId: 'req-123' }, env: { traceId: 'trace-1' } });
71
-
72
- console.log(JSON.stringify(executor.getSnapshot().sharedState));
73
- // {"creditTier":"A","amount":50000,"customer":{"name":"Ana","address":{"zip":"90210"}},"tags":["vip","premium","verified"],"approved":true}
74
- // the batch is ONE write; the single push before it is another
75
- console.log(JSON.stringify(executor.getNarrativeEntries().filter((e) => e.text.includes('Write tags')).map((e) => e.text)));
76
- // ["Step 4: Write tags = []","Step 8: Write tags = (1 item)","Step 10: Write tags = (3 items)"]
77
- ```
78
-
79
- ### decide() / select() — Decision Evidence Capture
80
-
81
- ```typescript
82
- import { flowChart, FlowChartExecutor, decide } from 'footprintjs';
83
-
84
- interface RiskState {
85
94
  creditScore: number;
86
- dti: number;
95
+ decision?: string;
87
96
  }
88
97
 
89
- const chart = flowChart<RiskState>('Intake', (scope) => {
90
- scope.creditScore = 750;
91
- scope.dti = 0.35;
92
- }, 'intake')
93
- // Inside a decider function — auto-captures which values led to the decision
94
- .addDeciderFunction('ClassifyRisk', (scope) => {
95
- return decide(scope, [
96
- { when: { creditScore: { gt: 700 }, dti: { lt: 0.43 } }, then: 'approved', label: 'Good credit' },
97
- { when: (s) => s.creditScore > 600, then: 'manual-review', label: 'Marginal' },
98
- ], 'rejected');
99
- }, 'classify-risk')
100
- .addFunctionBranch('approved', 'Approve', () => {})
101
- .addFunctionBranch('manual-review', 'Review', () => {})
102
- .addFunctionBranch('rejected', 'Reject', () => {})
103
- .end()
104
- .build();
105
-
106
- const executor = new FlowChartExecutor(chart);
107
- executor.enableNarrative();
108
- await executor.run();
109
- console.log(executor.getNarrativeEntries().find((e) => e.type === 'condition')?.text);
110
- // [Condition]: It evaluated Rule 0 "Good credit": creditScore 750 gt 700 ✓, dti 0.35 lt 0.43 ✓, and chose Approve.
111
- ```
112
-
113
- Filter operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notIn`. `decide()` returns `{ branch, evidence }`; the narrative names the chosen branch by its **name** (`Approve`), the evidence by its **id** (`approved`).
114
-
115
- `select()` is the multi-pick twin — every matching rule picks its branch (not first-match), and the picked branches run in parallel:
116
-
117
- ```typescript
118
- import { flowChart, FlowChartExecutor, select } from 'footprintjs';
119
-
120
- const chart = flowChart<{ glucose: number; bmi: number }>('Intake', (scope) => {
121
- scope.glucose = 120;
122
- scope.bmi = 31;
98
+ const chart = flowChart<LoanState>('Intake', (scope) => {
99
+ scope.creditScore = scope.$getArgs<{ score: number }>().score; // input is frozen and untracked; state is tracked
123
100
  }, 'intake')
124
- .addSelectorFunction('Screen', (scope) => select(scope, [
125
- { when: { glucose: { gt: 100 } }, then: 'diabetes', label: 'High glucose' },
126
- { when: { bmi: { gt: 30 } }, then: 'obesity', label: 'High BMI' },
127
- ]), 'screen')
128
- .addFunctionBranch('diabetes', 'DiabetesPath', () => {})
129
- .addFunctionBranch('obesity', 'ObesityPath', () => {})
101
+ .addDeciderFunction('Route', (scope) => decide(scope, [
102
+ { when: { creditScore: { gte: 700 } }, then: 'approve', label: 'Good credit' },
103
+ ], { branch: 'review', label: 'No rule fired' }), 'route')
104
+ .addFunctionBranch('approve', 'Approve', (scope) => { scope.decision = 'approved'; })
105
+ .addFunctionBranch('review', 'Review', (scope) => { scope.decision = 'manual review'; })
130
106
  .end()
131
107
  .build();
132
108
 
133
109
  const executor = new FlowChartExecutor(chart);
134
- executor.enableNarrative();
135
- await executor.run();
136
- console.log(executor.getNarrativeEntries().find((e) => e.type === 'fork')?.text);
137
- // [Parallel]: Forking into 2 parallel paths: DiabetesPath, ObesityPath.
138
- ```
139
-
140
- **Naming the default branch.** The default is chosen by no rule, so no
141
- `rules[].label` can describe it — it is the one branch evidence cannot
142
- otherwise name. Declare it beside the rules by passing an object instead of a
143
- string; the label lands on `DecisionEvidence.defaultLabel` and is recorded on
144
- every decision, not just the runs that fell through.
145
-
146
- ```typescript
147
- import { flowChart, FlowChartExecutor, decide } from 'footprintjs';
148
-
149
- for (const creditScore of [750, 100]) {
150
- const chart = flowChart<{ creditScore: number }>('Intake', (scope) => { scope.creditScore = creditScore; }, 'intake')
151
- .addDeciderFunction('ClassifyRisk', (scope) => decide(scope, [
152
- { when: { creditScore: { gt: 700 } }, then: 'approved', label: 'Good credit' },
153
- ], { branch: 'rejected', label: 'No rule fired — application rejected' }), 'classify-risk')
154
- .addFunctionBranch('approved', 'Approve', () => {})
155
- .addFunctionBranch('rejected', 'Reject', () => {})
156
- .end()
157
- .build();
158
- const executor = new FlowChartExecutor(chart);
159
- executor.attachFlowRecorder({
160
- id: 'evidence',
161
- onDecision: (e) => console.log(e.evidence?.chosen, '|', e.evidence?.defaultLabel),
162
- });
163
- await executor.run();
164
- }
165
- // approved | No rule fired — application rejected
166
- // rejected | No rule fired — application rejected
167
- // a bare string default still works: decide(scope, rules, 'rejected') — the evidence then has no `defaultLabel` key
168
- ```
169
-
170
- ### Builder
171
-
172
- ```typescript
173
- import { flowChart } from 'footprintjs';
174
-
175
- const chart = flowChart('Stage1', () => {}, 'stage-1', { description: 'Description' })
176
- .addFunction('Stage2', () => {}, 'stage-2', 'Description')
177
- .addDeciderFunction('Decide', () => 'high', 'decide', 'Route based on risk')
178
- .addFunctionBranch('high', 'Reject', () => {})
179
- .addFunctionBranch('low', 'Approve', () => {})
180
- .setDefault('high')
181
- .end()
182
- .build();
183
- ```
184
-
185
- The first stage is `flowChart(name, fn, id, { description?, structureRecorders? })`; every later stage is `.addFunction(name, fn, id, description?)`.
186
-
187
- Methods (not exhaustive): `start()`, `addFunction()`, `addStreamingFunction()`, `addDeciderFunction()`, `addSelectorFunction()`, `addListOfFunction()`, `addParallelForEach()`, `addPausableFunction()`, `addSubFlowChart()`, `addSubFlowChartNext()`, `addLazySubFlowChart()`, `addDetachAndForget()`, `addDetachAndJoinLater()`, `retry()`, `tag()`, `loopTo()`, `contract()`, `attachStructureRecorder()`, `build()`, `toSpec()`, `toMermaid()`. `toOpenAPI()` and `toMCPTool()` are on the built chart.
188
-
189
- ### ScopeFacade (Internal — use TypedScope for new code)
190
-
191
- `ScopeFacade` (from `footprintjs/advanced`) is the engine's own scope; `TypedScope` wraps it. A stage only receives a `ScopeFacade` when you supply a custom `scopeFactory`. In a TypedScope stage the same operations are `scope.$getValue(key)` / `scope.$setValue(key, value)` / `scope.$getArgs()` / `scope.$getEnv()` — plain `scope.getValue` does not exist there.
192
-
193
- ```typescript
194
- import { flowChart, FlowChartExecutor } from 'footprintjs';
195
- import { ScopeFacade } from 'footprintjs/advanced';
196
-
197
- // TypedScope stage: dynamic keys go through the $ methods
198
- const typed = flowChart<Record<string, unknown>>('Typed', (scope) => {
199
- scope.$setValue('dyn', 41);
200
- scope.$setValue('dyn', (scope.$getValue('dyn') as number) + 1);
201
- }, 'typed').build();
202
- const typedRun = new FlowChartExecutor(typed);
203
- await typedRun.run();
204
- console.log(JSON.stringify(typedRun.getSnapshot().sharedState));
205
- // {"dyn":42}
206
-
207
- // ScopeFacade stage: getValue / setValue / getArgs / getEnv
208
- const facade = flowChart<any>('Facade', (scope: any) => {
209
- const s = scope as ScopeFacade;
210
- s.setValue('key', { v: 1 });
211
- console.log(JSON.stringify([s.getValue('key'), s.getArgs(), s.getEnv()]));
212
- }, 'facade').build();
213
- const facadeRun = new FlowChartExecutor(facade, {
214
- scopeFactory: (ctx, stageName, readOnly, env) => new ScopeFacade(ctx, stageName, readOnly, env),
215
- });
216
- await facadeRun.run({ input: { requestId: 'req-9' }, env: { traceId: 'trace-9' } });
217
- // [{"v":1},{"requestId":"req-9"},{"traceId":"trace-9"}]
218
- ```
219
-
220
- **Three access tiers:**
221
- - `scope.amount = 50000` (ScopeFacade: `getValue`/`setValue`) — mutable shared state, tracked in the narrative
222
- - `$getArgs()` (ScopeFacade: `getArgs()`) — frozen business input from `run({ input })`, NOT tracked. Its keys are read-only for the run: a stage that writes a state key with the same name throws `Cannot write to readonly input key "requestId"`. A subflow's `inputMapper` result is its input and follows the same rule
223
- - `$getEnv()` (ScopeFacade: `getEnv()`) — frozen infrastructure context from `run({ env })`, NOT tracked. Returns `ExecutionEnv { signal?, timeoutMs?, traceId? }`. Auto-inherited by subflows. Closed type
224
-
225
- ### Executor
226
-
227
- Custom factory objects (including standalone scopes passed to `decide`/`select`) must register their infrastructure port with `registerScopeRuntime(scope, { target, handlesAssignments, setBreak? })` from `footprintjs/advanced`. `ScopeFacade`, TypedScope, `attachScopeMethods` and canonical Zod factories register automatically. The engine asks that port, never probes a strict user proxy for lifecycle names. Prefer one backing `ScopeFacade` as `target`; it owns recording, redaction, input protection and commit sealing. A deliberately data-only `{}` port has none of those scope-level hooks. See `docs/guides/scope.md` for the migration example; do not restore property-name guessing.
228
-
229
- ```typescript
230
- import { flowChart, FlowChartExecutor, MetricRecorder, NarrativeFlowRecorder } from 'footprintjs';
231
-
232
- const chart = flowChart<{ n: number }>('One', (scope) => { scope.n = scope.$getArgs<{ x: number }>().x; }, 'one')
233
- .addFunction('Two', (scope) => { scope.n = scope.n + 1; }, 'two')
234
- .build();
235
-
236
- // With options (preferred over positional params): scopeFactory, readTracking, writeTracking, commitValues, …
237
- const executor = new FlowChartExecutor(chart, { readTracking: 'full' });
238
- executor.enableNarrative(); // before run() — the narrative is off by default
239
- executor.attachScopeRecorder(new MetricRecorder()); // plug scope observer
240
- executor.attachFlowRecorder(new NarrativeFlowRecorder()); // plug flow observer
241
- executor.setRedactionPolicy({ keys: ['secret'] }); // PII protection
242
-
243
- await executor.run({ input: { x: 1 }, env: { traceId: 'req-123' } });
244
-
245
- // CombinedNarrativeEntry[] — combined flow + data narrative
246
- console.log(executor.getNarrativeEntries().length);
247
- // 5
248
- // flow-only (no data ops): drop the read/write steps
249
- console.log(JSON.stringify(executor.getNarrativeEntries().filter((e) => e.type !== 'step').map((e) => e.text)));
250
- // ["Stage 1: The process began with One.","Stage 2: Next, it moved on to Two."]
251
- // full memory state (includes recorder snapshots)
252
- console.log(JSON.stringify(Object.keys(executor.getSnapshot())));
253
- // ["sharedState","executionTree","initialState","commitLog","logAddress","commitValues","writeProvenance","runId","correlation","recorders"]
254
-
255
- // Pause/Resume — human-in-the-loop (next section)
256
- // executor.isPaused() // true if last run paused
257
- // executor.getCheckpoint() // JSON-safe checkpoint (store in Redis/Postgres/etc.)
258
- // executor.resume(checkpoint, input) // continue from checkpoint with human's answer
110
+ executor.enableNarrative(); // off until you ask, and must come before run()
111
+ await executor.run({ input: { score: 640 } });
112
+
113
+ console.log(executor.getSnapshot().sharedState.decision);
114
+ for (const entry of executor.getNarrativeEntries()) console.log(' '.repeat(entry.depth) + entry.text);
115
+
116
+ // Output:
117
+ // manual review
118
+ // Stage 1: The process began with Intake.
119
+ // Step 1: Write creditScore = 640
120
+ // Stage 2: Next, it moved on to Route.
121
+ // Step 1: Read creditScore = 640
122
+ // [Condition]: No rules matched, fell back to default "No rule fired": Review.
123
+ // Stage 3: Next, it moved on to Review.
124
+ // Step 1: Write decision = "manual review"
259
125
  ```
260
126
 
261
- `getNarrativeEntries()` returns entries (`type`, `text`, `depth`, `stageName`, `stageId`, …), not strings: `.map((e) => e.text)` for plain lines. One executor runs one execution at a time — create one per concurrent run.
127
+ `decide()` records each rule's values and thresholds as evidence, on the narrative line and on `onDecision`. `select()` is its twin: every matching rule picks a branch, and the picked branches run in parallel.
262
128
 
263
- ### Pause/Resume (Human-in-the-Loop)
129
+ ### Retry, and record each try
264
130
 
265
131
  ```typescript
132
+ // Retry a stage, record a call inside a stage, and bound the time.
266
133
  import { flowChart, FlowChartExecutor } from 'footprintjs';
267
- import type { PausableHandler } from 'footprintjs';
268
-
269
- interface MyState {
270
- amount: number;
271
- approved?: boolean;
272
- done?: boolean;
273
- }
274
-
275
- const handler: PausableHandler<MyState> = {
276
- execute: async (scope) => {
277
- // Return data = pause. Return nothing = continue.
278
- return { question: `Approve $${scope.amount}?` };
279
- },
280
- resume: async (scope, input) => {
281
- scope.approved = (input as { approved: boolean }).approved;
282
- },
283
- };
284
-
285
- // Pausable root stage (single-stage subflows):
286
- const single = flowChart<MyState>('Approve', handler, 'approve').build();
287
-
288
- // Or chained after other stages:
289
- const chart = flowChart<MyState>('Seed', (scope) => { scope.amount = 500; }, 'seed')
290
- .addPausableFunction('Approve', handler, 'approve')
291
- .addFunction('Process', (scope) => { scope.done = scope.approved === true; }, 'process')
292
- .build();
293
-
294
- const executor = new FlowChartExecutor(chart);
295
- executor.enableNarrative();
296
- await executor.run();
297
- console.log(executor.isPaused());
298
- // true
299
-
300
- if (executor.isPaused()) {
301
- const checkpoint = executor.getCheckpoint()!; // JSON-safe, store anywhere
302
- console.log(checkpoint.pausedStageId, JSON.stringify(checkpoint.pauseData));
303
- // approve {"question":"Approve $500?"}
304
- const stored = JSON.stringify(checkpoint);
305
- // Later (hours, different server):
306
- await executor.resume(JSON.parse(stored), { approved: true });
307
- }
308
- console.log(executor.isPaused(), JSON.stringify(executor.getSnapshot().sharedState));
309
- // false {"amount":500,"approved":true,"done":true}
310
- console.log(executor.getNarrativeEntries().filter((e) => e.type === 'pause' || e.type === 'resume').map((e) => e.text));
311
- // [
312
- // 'Execution paused at Approve.',
313
- // 'Execution resumed at Approve with input.'
314
- // ]
315
- void single;
316
- ```
317
-
318
- - `execute` returns data → pauses. Returns void → continues normally (conditional pause).
319
- - Checkpoint is JSON-serializable — no functions, no class instances. A fresh executor resumes it too (`new FlowChartExecutor(chart).resume(JSON.parse(stored), input)`).
320
- - `resume()` on the SAME executor reuses its runtime — narrative, metrics, execution tree all accumulate; a fresh executor seeds a new runtime from `checkpoint.sharedState`.
321
- - A resume re-enters ONCE, then the run is the chart as built: a `loopTo` back to the paused stage runs that stage again (it pauses again — a re-ask), and the next pass through a subflow mount is a fresh entry (its inputMapper runs). A pause several subflows deep does not re-run the outer subflows' earlier stages, and a subflow mounted as a decider/selector branch or a fork child hands back to its parent's continuation (the decider's `next`, the fork's join). (Since 9.28.0.)
322
- - Two parallel siblings that pause in one fan-out are asked IN TURN: the checkpoint asks the first and carries the others in `checkpoint.pendingPauses`; each resume answers one; the join runs after the last. (Since 9.28.0.)
323
- - Not resumable yet: a pause inside a LAZY subflow or an `addParallelForEach` branch — `resume()` rejects (`Cannot resume: stage 'lz/sf-ask' not found in flowchart`). A subflow id mounted twice in one chart — `resume()` refuses a pause inside it (give each mount its own id).
324
- - `FlowRecorder.onPause`/`onResume` and `ScopeRecorder.onPause`/`onResume` fire on both observer systems.
325
-
326
- ### ComposableRunner & Snapshot Navigation
327
-
328
- `ComposableRunner<TIn, TOut>` is the interface for a runner that exposes its internal chart so a parent can mount it as a subflow: `toFlowChart()` and `run(input, options?)`.
329
-
330
- ```typescript
331
- import { flowChart, FlowChartExecutor, getSubtreeSnapshot, listSubflowPaths } from 'footprintjs';
332
- import type { ComposableRunner } from 'footprintjs';
333
134
 
334
- class Doubler implements ComposableRunner<number, number> {
335
- toFlowChart() {
336
- return flowChart<{ out?: number }>('Double', (scope) => { scope.out = scope.$getArgs<{ n: number }>().n * 2; }, 'double').build();
337
- }
338
- async run(input: number): Promise<number> {
339
- const executor = new FlowChartExecutor(this.toFlowChart());
340
- await executor.run({ input: { n: input } });
341
- return (executor.getSnapshot().sharedState as { out: number }).out;
342
- }
135
+ interface QuoteState {
136
+ rate?: number;
137
+ stock?: number;
343
138
  }
344
139
 
345
- const outer = flowChart<{ out?: number }>('Outer', () => {}, 'outer')
346
- .addSubFlowChartNext('sf-doubler', new Doubler().toFlowChart(), 'Doubler', {
347
- inputMapper: () => ({ n: 21 }),
348
- outputMapper: (sub: { out?: number }) => ({ out: sub.out }),
349
- })
350
- .build();
351
- const root = flowChart<{ out?: number }>('Root', () => {}, 'root')
352
- .addSubFlowChartNext('sf-outer', outer, 'OuterMount', { outputMapper: (sub: { out?: number }) => ({ out: sub.out }) })
353
- .build();
354
-
355
- const executor = new FlowChartExecutor(root);
356
- await executor.run();
357
- const snapshot = executor.getSnapshot();
358
-
359
- console.log(await new Doubler().run(4));
360
- // 8
361
- console.log(listSubflowPaths(snapshot));
362
- // [ 'sf-outer/sf-doubler', 'sf-outer' ]
363
- const subtree = getSubtreeSnapshot(snapshot, 'sf-outer/sf-doubler');
364
- console.log(Object.keys(subtree ?? {}), JSON.stringify(subtree?.sharedState));
365
- // [
366
- // 'subflowId',
367
- // 'executionTree',
368
- // 'sharedState',
369
- // 'history',
370
- // 'initialState',
371
- // 'narrativeEntries'
372
- // ] {"n":21,"out":42}
373
- ```
374
-
375
- ## Observer Channels
376
-
377
- Four pluggable observer channels — three fire at runtime (Scope, Flow, Emit) and one fires at build time (Structure). The runtime channels share `{ id, hooks } -> dispatcher -> error isolation -> attach/detach` (the Structure channel has `attachStructureRecorder` only). `attachCombinedRecorder(r)` routes a recorder to channels by runtime duck-typing of its `on*` methods. Intentionally NOT unified into one interface — each channel has a distinct invariant set.
378
-
379
- **Recorder ID contract:**
380
- - `attachScopeRecorder` / `attachFlowRecorder` / `attachEmitRecorder` / `attachCombinedRecorder` are **idempotent by ID** — same ID replaces, different IDs coexist. Prevents accidental double-counting.
381
- - Built-in recorders use auto-increment default IDs (`metrics-1`, `debug-1`, ...) so multiple instances with different configs coexist naturally.
382
- - Frameworks that auto-attach recorders should use a well-known ID (e.g., `new MetricRecorder('metrics')`) so the consumer can override it by passing the same ID, or add a second instance with `new MetricRecorder()` (gets unique ID).
383
-
384
- ```typescript
385
- import { flowChart, FlowChartExecutor, MetricRecorder, DebugRecorder } from 'footprintjs';
386
-
387
- console.log(new MetricRecorder().id, new MetricRecorder().id, new MetricRecorder('metrics').id, new DebugRecorder({ id: 'dbg' }).id);
388
- // metrics-1 metrics-2 metrics dbg
389
-
390
- const executor = new FlowChartExecutor(flowChart<{ a: number }>('One', (scope) => { scope.a = 1; }, 'one').build());
391
- let first = 0;
392
- let second = 0;
393
- executor.attachScopeRecorder({ id: 'same', onWrite: () => { first++; } });
394
- executor.attachScopeRecorder({ id: 'same', onWrite: () => { second++; } }); // same id: replaces the first
395
- await executor.run();
396
- console.log(first, second);
397
- // 0 1
398
- ```
399
-
400
- **Scope Recorder** (data ops — `onStageStart` → `onRead`/`onWrite` DURING the stage function → `onStageEnd` → `onCommit`):
401
- - `onStageStart`, `onRead`, `onWrite`, `onStageEnd`, `onCommit`, `onError`, `onPause`, `onResume`
402
- - Built-in: `MetricRecorder`, `DebugRecorder`
403
-
404
- **FlowRecorder** (control flow — fires AFTER the stage's commit):
405
- - `onStageExecuted` (universal "did this stage run", carries `stageType: 'linear' | 'decider' | 'fork' | 'selector' | 'subflow-mount'`), `onNext`, `onDecision`, `onFork`, `onSelected`, `onSubflowEntry/Exit`, `onSubflowRegistered`, `onLoop`, `onBreak`, `onAttempt` (every attempt of a retried stage, with its record and decision), `onStageRetry`, `onError`, `onPause`/`onResume`, `onRunStart`/`onRunEnd`, `onRunFailed`
406
- - Events carry an optional `traversalContext: TraversalContext` (includes per-run `runId`)
407
- - `onDecision`/`onSelected` carry optional `evidence` from decide()/select()
408
- - Built-in: 9 strategies (Narrative, Adaptive, Windowed, RLE, Milestone, Progressive, Separate, Manifest, Silent)
409
-
410
- **Emit Recorder** (consumer-emitted events — fired by `scope.$emit(name, payload)`):
411
- - `onEmit(EmitEvent)` — see the "Emit Channel" section below.
412
-
413
- **Structure Recorder** (build-time chart shape — fires SYNCHRONOUSLY during builder operations, NOT runtime):
414
- - `onStageAdded`, `onStageTagged`, `onEdgeAdded`, `onLoopEdgeAdded`, `onDeciderComplete`, `onSubflowMounted`
415
- - Attach via options bag — `flowChart('seed', fn, 'seed', { structureRecorders: [rec] })` — or fluent `.attachStructureRecorder(rec)`. MOUNT-ONLY: a builder's recorder sees only that builder's events; subflow internals arrive via the mount event's `subflowSpec` (walk with `walkSubflowSpec` from `footprintjs/trace`). The types are exported from the main `footprintjs` barrel.
416
-
417
- ```typescript
418
- import { flowChart } from 'footprintjs';
419
- import type { StructureRecorder, StructureSubflowMountedEvent } from 'footprintjs';
420
- import { walkSubflowSpec } from 'footprintjs/trace';
421
-
422
- const events: string[] = [];
423
- let mounted: StructureSubflowMountedEvent | undefined;
424
- const recorder: StructureRecorder = {
425
- id: 'structure',
426
- onStageAdded: (e) => { events.push(`stage ${e.spec.id}`); },
427
- onEdgeAdded: (e) => { events.push(`edge ${e.from} -> ${e.to} (${e.kind})`); },
428
- onSubflowMounted: (e) => { events.push(`mounted ${e.subflowId}`); mounted = e; },
140
+ // Local stand-ins for outside services: busy once, then they answer.
141
+ const busyOnce = <T>(value: T) => {
142
+ let calls = 0;
143
+ return async (signal: AbortSignal): Promise<T> => {
144
+ signal.throwIfAborted();
145
+ if (++calls === 1) throw Object.assign(new Error('service busy'), { status: 503 });
146
+ return value;
147
+ };
429
148
  };
430
-
431
- const sub = flowChart<object>('SubA', () => {}, 'sub-a').addFunction('SubB', () => {}, 'sub-b').build();
432
- flowChart<object>('Seed', () => {}, 'seed', { structureRecorders: [recorder] })
433
- .addSubFlowChartNext('sf', sub, 'Sub')
149
+ const fetchRate = busyOnce(1.09);
150
+ const lookupStock = busyOnce(7);
151
+
152
+ const chart = flowChart<QuoteState>('Fetch rate', async (scope) => {
153
+ // Pass the signal on, so a timeout stops the work and not only the wait.
154
+ scope.rate = await fetchRate(scope.$attempt().signal);
155
+ }, 'fetch-rate')
156
+ .retry({ attempts: 3, backoffMs: 10, timeoutMs: 1_000 }) // attempts counts the first run too
157
+ .addFunction('Check stock', async (scope) => {
158
+ // Every attempt of a call is recorded, even with no policy.
159
+ scope.stock = await scope.$call('inventory.lookup', (t) => lookupStock(t.signal), { attempts: 2, backoffMs: 10 });
160
+ }, 'check-stock')
161
+ .budget(5_000) // build() refuses a chart whose declared policies allow longer
434
162
  .build();
435
163
 
436
- console.log(events); // the subflow's own stages (sub-a, sub-b) are NOT reported here
437
- // [ 'stage seed', 'stage sf', 'edge seed -> sf (next)', 'mounted sf' ]
438
- for (const item of walkSubflowSpec(mounted!.subflowSpec!, mounted!.subflowPath ?? mounted!.subflowId)) {
439
- console.log(item.kind);
440
- }
441
- // subflow-start
442
- // stage
443
- // edge
444
- // stage
445
- ```
446
-
447
- **CombinedNarrativeRecorder** implements the Scope + Flow + Emit interfaces. `executor.enableNarrative(options)` configures the executor-owned view (read it with `executor.getNarrativeEntries()`). Attaching any flow recorder also enables that view. `chart.recorder(narrative())` attaches a separate instance for a one-shot run, and `executor.attachCombinedRecorder(narrative())` works too — read its configured view from `recorder.getEntries()`, not the executor getter. Each default instance has a distinct generated ID; detach using `recorder.id`. Same-executor resume preserves narrative history; a fresh executor records only its resumed leg. The class is not exported from the public doors.
448
-
449
- ## Event Ordering
450
-
451
- ```
452
- 0. FlowRecorder.onRunStart — once per executor.run(), before any stage; event.payload = the run input
453
- Per stage, ScopeRecorder events:
454
- 1. Recorder.onStageStart — stage begins
455
- 2. Recorder.onRead/onWrite — DURING execution, before the commit
456
- 3. Recorder.onStageEnd — the stage function returned
457
- 4. Recorder.onCommit — transaction flush
458
- Then FlowRecorder events, by stage kind:
459
- 5. linear stage onStageExecuted → onNext
460
- decider onDecision → onStageExecuted
461
- selector onSelected → onStageExecuted → onFork
462
- fork parent onStageExecuted → onFork → onStageExecuted (stageType 'fork')
463
- subflow mount onNext → onSubflowEntry → onStageExecuted (stageType 'subflow-mount')
464
- → the subflow's own stages → onSubflowExit
465
- 6. FlowRecorder.onRunEnd (clean; event.payload = the chart's return value) or onRunFailed (error; event.structuredError) — once per run, closes the boundary symmetrically
466
- ```
467
-
468
- `CombinedNarrativeRecorder` flushes a stage's buffered reads and writes when that stage's flow event arrives: `onStageExecuted` for LINEAR stages, `onDecision` / `onSelected` / `onFork` / `onSubflowEntry` for the others.
469
-
470
- ## Execution Tracing (record queries from `foottrace`)
471
-
472
- Every stage execution gets a unique `runtimeStageId` — the universal key that links recorder events, commit log entries, and execution tree nodes.
473
-
474
- **When to use:** Debugging (which stage set a value to something unexpected?), audit trails (trace every write to its source stage), custom recorders (correlate events with specific execution steps), quality trace backtracking (walk backwards to find where data quality dropped).
475
-
476
- **Format:** `[subflowPath/]stageId#executionIndex` — the index starts at 0 and counts every stage execution across the run (a loop revisits the same stageId with a higher index):
477
-
478
- ```
479
- seed#0 — root stage, the first execution
480
- tick#6 — the seventh execution
481
- sf-outer/sf-inner/inner-end#5 — a stage inside a nested subflow
482
- tick#9 — same stageId, different execution (loop)
483
- ```
484
-
485
- **The commitLog:** An ordered array of `CommitBundle` — one per stage commit, recording what each stage wrote to shared state. Get it from `executor.getSnapshot().commitLog`. A subflow mount appears twice in the root log under one runtimeStageId; the subflow's own stage commits are in its subtree history (`getSubtreeSnapshot(snapshot, path).history`).
486
-
487
- ```typescript
488
- import { flowChart, FlowChartExecutor, decide, getSubtreeSnapshot } from 'footprintjs';
489
- import { parseRuntimeStageId, buildRuntimeStageId, splitStageId, findLastWriter, findCommit, findCommits, isCommitBundle } from 'foottrace';
490
-
491
- const inner = flowChart<{ v: number; t?: number; out?: number }>('InnerStart', (scope) => { scope.t = scope.v + 1; }, 'inner-start')
492
- .addFunction('InnerEnd', (scope) => { scope.out = (scope.t ?? 0) * 2; }, 'inner-end')
493
- .build();
494
- const outer = flowChart<{ n: number; w?: number; out?: number }>('OuterStart', (scope) => { scope.w = scope.n; }, 'outer-start')
495
- .addSubFlowChartNext('sf-inner', inner, 'Inner', {
496
- inputMapper: (parent: { w?: number }) => ({ v: parent.w }),
497
- outputMapper: (sub: { out?: number }) => ({ out: sub.out }),
498
- })
499
- .build();
500
- const chart = flowChart<{ n: number; count: number }>('Seed', (scope) => { scope.n = 1; scope.count = 0; }, 'seed')
501
- .addSubFlowChartNext('sf-outer', outer, 'Outer', {
502
- inputMapper: (parent: { n: number }) => ({ n: parent.n }),
503
- outputMapper: (sub: { out?: number }) => ({ out: sub.out }),
504
- })
505
- .addFunction('Tick', (scope) => { scope.count = scope.count + 1; }, 'tick')
506
- .addDeciderFunction('Route', (scope) => decide(scope, [
507
- { when: { count: { lt: 2 } }, then: 'again', label: 'under 2' },
508
- ], 'done'), 'route')
509
- .addFunctionBranch('again', 'Again', () => {})
510
- .loopTo('tick')
511
- .addFunctionBranch('done', 'Done', () => {})
512
- .end()
513
- .build();
164
+ console.log('declared worst case', chart.timeBudget().knownMs);
514
165
 
515
166
  const executor = new FlowChartExecutor(chart);
516
- await executor.run();
517
-
518
- // Get the commit log after execution
519
- const snapshot = executor.getSnapshot();
520
- const commitLog = snapshot.commitLog; // CommitBundle[]
521
- console.log(commitLog.map((bundle) => bundle.runtimeStageId).join(' '));
522
- // seed#0 sf-outer#1 sf-outer#1 tick#6 route#7 again#8 tick#9 route#10 done#11
523
-
524
- // A subflow's own stage commits live in its subtree history, not in the root log
525
- const innerHistory = (getSubtreeSnapshot(snapshot, 'sf-outer/sf-inner')?.history ?? []).filter(isCommitBundle);
526
- console.log(innerHistory.map((bundle) => bundle.runtimeStageId).join(' '));
527
- // sf-outer/sf-inner#3 sf-outer/sf-inner/inner-start#4 sf-outer/sf-inner/inner-end#5
528
-
529
- // Parse a runtimeStageId into components
530
- console.log(JSON.stringify(parseRuntimeStageId(innerHistory[1].runtimeStageId)));
531
- // {"stageId":"inner-start","executionIndex":4,"subflowPath":"sf-outer/sf-inner"}
532
- console.log(buildRuntimeStageId('inner-end', 5, 'sf-outer/sf-inner'), JSON.stringify(splitStageId('sf-outer/sf-inner/inner-end')));
533
- // sf-outer/sf-inner/inner-end#5 {"localStageId":"inner-end","subflowPath":"sf-outer/sf-inner"}
534
-
535
- // Backtrack: who last wrote 'count' before commitLog array index 6?
536
- // beforeIdx is the CommitBundle.idx (array position), NOT the executionIndex from runtimeStageId.
537
- const writer = findLastWriter(commitLog, 'count', 6);
538
- console.log(writer?.runtimeStageId, writer?.idx, JSON.stringify(writer?.trace));
539
- // tick#6 3 [{"path":"count","verb":"set"}]
540
- // → CommitBundle | undefined (has .idx, .stage, .stageId, .runtimeStageId, .trace, .overwrite, .updates, .redactedPaths)
541
-
542
- // Find by stageId: use findCommit when you know the stage.
543
- // Use findLastWriter when you know the key but not which stage wrote it.
544
- console.log(findCommit(commitLog, 'tick', 'count')?.runtimeStageId, findCommits(commitLog, 'tick').map((bundle) => bundle.runtimeStageId));
545
- // tick#6 [ 'tick#6', 'tick#9' ]
546
- ```
547
-
548
- **Record queries and engine recorders have different owners.** In the table below, ID helpers, commit queries and `CommitRangeIndex` come from `foottrace`. `walkSubflowSpec`, stores, topology/in-out recorders and control-dependency/quality recorders remain on `footprintjs/trace`. The slice and time-travel contracts now live in the [foottrace repository](https://github.com/footprintjs/foottrace).
549
-
550
- | Export | Returns | Use |
551
- |--------|---------|-----|
552
- | `buildRuntimeStageId(stageId, idx, subflowPath?)` | `string` | Construct an ID from components |
553
- | `parseRuntimeStageId(id)` | `{ stageId, executionIndex, subflowPath }` (`subflowPath` is `undefined` at top level) | Decompose an ID |
554
- | `findCommit(commitLog, stageId, key?)` | `CommitBundle \| undefined` | Find the first commit by stageId (that wrote `key`, if given) |
555
- | `findCommits(commitLog, stageId)` | `CommitBundle[]` | Find all commits by stageId |
556
- | `findLastWriter(commitLog, key, beforeIdx?)` | `CommitBundle \| undefined` | Search backwards for who wrote a key |
557
- | `splitStageId(prefixedId)` | `{ localStageId, subflowPath }` | Decompose a bare prefixed id (`spec.id`, `CommitBundle.stageId`) |
558
- | `walkSubflowSpec(spec, subflowPath, opts?)` | `Generator<WalkerItem>` | Walk a subflow spec from `StructureSubflowMountedEvent.subflowSpec` |
559
- | `KeyedStore<T>` | class (since 5.0.0) | Storage shelf for 1:1 Map keyed by runtimeStageId (`set`/`get`/`aggregate`/`accumulate`/`filterByKeys`) |
560
- | `SequenceStore<T>` | class (since 5.0.0) | Storage shelf for 1:N ordered entries (`push`/`getByKey`/`getEntryRanges()` for O(1) time-travel/`getEntriesUpTo`) |
561
- | `BoundaryStateStore<TState>` | class (since 5.0.0) | Storage shelf for transient bracket-scoped state — live state DURING a `[start, stop]` interval; clears on stop. O(1) reads via `get` / `hasActive` / `activeCount`; lifecycle via `start` / `update` / `stop`. |
562
- | `KeyedRecorder<T>` / `SequenceRecorder<T>` / `BoundaryStateTracker<TState>` | abstract bases — **REMOVED in 7.0.0** | Gone — no inheritance path remains. Superseded by the `*Store` classes above: own a store as a field and implement the channel interface yourself. |
563
- | `CommitRangeIndex<TLabel>` | class | Interval index over commit indices (`open`/`close`/`enclosing`/`overlapping`) |
564
- | `topologyRecorder()` / `TopologyRecorder` | factory / class | Live composition graph for streaming consumers (subflow nodes + control-flow edges) |
565
- | `inOutRecorder()` / `InOutRecorder` | factory / class | Chart in/out stream — `entry`/`exit` pairs at every chart boundary (top-level run + every subflow) |
566
-
567
- ### TopologyRecorder — Composition Graph for Streaming Consumers
568
-
569
- **One-liner:** reconstructs a live, queryable mini-flowchart of what your run actually traced, built from FlowRecorder events (`onSubflowEntry`/`onSubflowExit`, `onFork`, `onDecision`, `onLoop`) during traversal.
570
-
571
- **Mental model:**
572
-
573
- ```
574
- flowChart() builder → STATIC flowchart (design-time definition)
575
- │
576
- ▼ executor runs it
577
- Traversal emits FlowRecorder events
578
- │
579
- ▼ TopologyRecorder listens
580
- DYNAMIC flowchart (runtime shape):
581
- Nodes = composition points
582
- (subflow / fork-branch / decision-branch)
583
- Edges = transitions
584
- (next / fork-branch / decision-branch / loop-iteration)
585
- Queryable any moment — during or after run
586
- ```
587
-
588
- **What it IS:**
589
- - Live composition graph derived from flow events
590
- - Each node = one composition-significant moment (subflow entered, fork child, decision chosen)
591
- - Each edge = a control-flow transition, stamped with the `runtimeStageId` it happened at (`edge.at`)
592
- - Works identically during or after a run
593
-
594
- **What it ISN'T:**
595
- - Not a full execution tree — that's `StageContext` / `executor.getSnapshot()`
596
- - Not per-stage data — that's `MetricRecorder` / a custom recorder composing `KeyedStore<T>`
597
- - Not agent-specific — agentfootprint composes it; footprintjs owns it
598
-
599
- **Why live consumers need it:** The executor already has the topology internally (execution tree in `StageContext`). But streaming consumers can't access that tree mid-run — they only see events. `TopologyRecorder` = "the tree, reconstructed from events, live-queryable."
600
-
601
- Fills the gap between "post-run snapshot (full tree available)" and "live event stream (only point observations)." Attach once; query `getTopology()` anytime during or after a run.
602
-
603
- ```typescript
604
- import { flowChart, FlowChartExecutor, decide } from 'footprintjs';
605
- import { topologyRecorder } from 'footprintjs/trace';
606
-
607
- const agent = flowChart<{ count: number }>('Start', (scope) => { scope.count = 0; }, 'start')
608
- .addFunction('Tick', (scope) => { scope.count = scope.count + 1; }, 'tick')
609
- .addDeciderFunction('Check', (scope) => decide(scope, [
610
- { when: { count: { lt: 2 } }, then: 'again', label: 'under 2' },
611
- ], 'done'), 'check')
612
- .addFunctionBranch('again', 'Again', () => {})
613
- .loopTo('tick')
614
- .addFunctionBranch('done', 'Done', () => {})
615
- .end()
616
- .build();
617
- const fanOut = flowChart<object>('Host', () => {}, 'host')
618
- .addListOfFunction([
619
- { id: 'x', name: 'X', fn: () => {} },
620
- { id: 'y', name: 'Y', fn: () => {} },
621
- ])
622
- .build();
623
- const chart = flowChart<object>('Seed', () => {}, 'seed')
624
- .addSubFlowChartNext('sf-agent', agent, 'Agent')
625
- .addSubFlowChartNext('sf-fanout', fanOut, 'FanOut')
626
- .build();
627
-
628
- const executor = new FlowChartExecutor(chart);
629
- const topo = topologyRecorder();
630
- executor.attachCombinedRecorder(topo); // auto-routes to FlowRecorder channel
631
-
632
- await executor.run();
633
-
634
- const { nodes, edges, activeNodeId, rootId } = topo.getTopology();
635
- console.log(nodes.map((node) => `${node.kind} ${node.id}`));
636
- // [
637
- // 'subflow sf-agent',
638
- // 'decision-branch decision-sf-agent/check#4-sf-agent/Again',
639
- // 'decision-branch decision-sf-agent/check#7-sf-agent/Done',
640
- // 'subflow sf-fanout',
641
- // 'fork-branch fork-sf-fanout/host#10-0-sf-fanout/X',
642
- // 'fork-branch fork-sf-fanout/host#10-1-sf-fanout/Y'
643
- // ]
644
- console.log(edges.map((edge) => `${edge.kind}: ${edge.from} -> ${edge.to}`));
645
- // [
646
- // 'decision-branch: sf-agent -> decision-sf-agent/check#4-sf-agent/Again',
647
- // 'loop-iteration: sf-agent -> sf-agent',
648
- // 'decision-branch: sf-agent -> decision-sf-agent/check#7-sf-agent/Done',
649
- // 'next: sf-agent -> sf-fanout',
650
- // 'fork-branch: sf-fanout -> fork-sf-fanout/host#10-0-sf-fanout/X',
651
- // 'fork-branch: sf-fanout -> fork-sf-fanout/host#10-1-sf-fanout/Y'
652
- // ]
653
- console.log(activeNodeId, rootId);
654
- // null sf-agent
655
- console.log(topo.getSubflowNodes().map((node) => node.id)); // agent-centric view
656
- // [ 'sf-agent', 'sf-fanout' ]
657
- console.log(topo.getByKind('fork-branch').map((node) => node.name)); // all parallel branches
658
- // [ 'sf-fanout/X', 'sf-fanout/Y' ]
659
- // topo.getParallelSiblings(id) — siblings of a parallel branch; topo.getChildren(id) — direct children
660
- ```
661
-
662
- **Three node kinds — complete composition coverage:**
663
-
664
- | Kind | Fires on | Represents |
665
- |---|---|---|
666
- | `subflow` | `onSubflowEntry` | Mounted subflow boundary (with stable `subflowId`) |
667
- | `fork-branch` | `onFork` (synthesized one per child) | One branch of a parallel split — works for plain stages AND subflows |
668
- | `decision-branch` | `onDecision` (synthesized for chosen) | The chosen branch of a conditional |
669
-
670
- When a fork-branch or decision-branch target is also a subflow, the subsequent `onSubflowEntry` creates a subflow CHILD of the synthetic node (verified for a fork/decider at the top level of a run; inside another subflow the branch names carry the subflow path prefix and the subflow node attaches to the enclosing subflow instead). Layered shape preserves both "who branched" and "what the branch ran."
671
-
672
- **Edges:** `edge.kind ∈ 'next' | 'fork-branch' | 'decision-branch' | 'loop-iteration'`. Each carries `at: runtimeStageId` for time correlation. Fork, decision and loop edges are recorded only while a subflow is active — a fork or decision at the top level of the run still creates its nodes, but no edge — and a `loopTo` outside any subflow adds nothing.
673
-
674
- **Correlation rules:**
675
- - `onFork({ parent, children })` → N `fork-branch` nodes synthesized up-front; subsequent matching `onSubflowEntry` nests under the right fork-branch
676
- - `onDecision({ chosen })` → `decision-branch` node synthesized up-front; matching `onSubflowEntry` nests under it
677
- - A pending decision clears on `onSubflowExit` so it can't match an unrelated subflow later; pending fork-sibling entries survive scope exits (a sibling's inner subflow may exit before the next sibling enters) and clear on the next `onFork` or on a match
678
- - `onLoop` → self-edge on the currently-active subflow (synthetic nodes don't participate)
679
- - Re-entry of same `subflowId` (loop body) disambiguates via `id#n` suffix (`sf-body`, `sf-body#1`)
680
-
681
- **What it does NOT track:** plain sequential stages. Use `MetricRecorder` / `StageContext` for per-stage data. Topology is a graph of control-flow branching, not a full execution tree.
682
-
683
- **For downstream libraries:** compose, don't duplicate. An agent-shaped recorder should wrap a `topologyRecorder()` internally and translate topology nodes into agent semantics — not re-implement subflow-stack + fork + decision tracking.
684
-
685
- Example: [examples/runtime-features/flow-recorder/06-topology.ts](examples/runtime-features/flow-recorder/06-topology.ts)
686
-
687
- ### InOutRecorder — Chart In/Out Stream (every chart boundary, root + subflows)
688
-
689
- **One-liner:** captures every chart execution (top-level run AND every subflow) as an `entry`/`exit` boundary pair, with the `inputMapper`/`outputMapper` payloads attached. Combined with `TopologyRecorder` (composition shape) this gives downstream layers the universal "step" primitive — `runtimeStageId` binds them.
690
-
691
- **Mental model:**
692
-
693
- ```
694
- user input ─►┌───────────────── run ─────────────────┐ ◄─ user output
695
- │ __root__#0 onRunStart / onRunEnd │
696
- │ │
697
- │ inputMapper outputMapper │
698
- │ │ │ │
699
- │ parent ──►┤ subflow ├──► parent │
700
- │ │ │ │
701
- │ └── runtimeStageId ───┘ │
702
- │ │
703
- └────────────────────────────────────────┘
704
- ```
705
-
706
- Each chart execution → 2 boundaries:
707
- - **Root** — `onRunStart` / `onRunEnd` fire ONCE per `executor.run()`. `subflowId: '__root__'`, `depth: 0`, `isRoot: true`.
708
- - **Subflow** — `onSubflowEntry` / `onSubflowExit` fire once per mounted subflow. Nested under root in the path tree (`['__root__', 'sf-x']`, depth 1+).
709
-
710
- Loop re-entry produces distinct pairs because the parent stage's executionIndex increments (`sf-body#2`, `sf-body#7`).
711
-
712
- **What it IS:**
713
- - composes `SequenceStore<InOutEntry>` — flat ordered list + per-`runtimeStageId` index
714
- - Captures the **payloads** at every chart boundary (what flowed IN and OUT)
715
- - Path-aware: `subflowPath` is decomposed from the engine's path-prefixed `subflowId` and rooted under `__root__`
716
- - Domain-agnostic — knows nothing about LLMs, tools, agents
717
-
718
- **What it ISN'T:**
719
- - Not a composition graph — that's `TopologyRecorder` (shape) vs this (data crossing each boundary)
720
- - Not a full execution tree — that's `StageContext`
721
- - Not agent-specific — domain libraries (e.g. agentfootprint) compose it; footprintjs owns it
722
-
723
- ```typescript
724
- import { flowChart, FlowChartExecutor } from 'footprintjs';
725
- import { inOutRecorder, ROOT_SUBFLOW_ID } from 'footprintjs/trace';
726
-
727
- const sub = flowChart<{ q: number; r?: number }>('Double', (scope) => { scope.r = scope.q * 2; }, 'double').build();
728
- const chart = flowChart<{ n: number; out?: number }>('Seed', (scope) => { scope.n = 21; }, 'seed')
729
- .addSubFlowChartNext('sf-double', sub, 'Doubler', {
730
- inputMapper: (parent: { n: number }) => ({ q: parent.n }),
731
- outputMapper: (out: { r?: number }) => ({ out: out.r }),
732
- })
733
- .build();
734
-
735
- const executor = new FlowChartExecutor(chart);
736
- const inOut = inOutRecorder();
737
- executor.attachCombinedRecorder(inOut);
738
-
739
- await executor.run({ input: { start: true } });
740
-
741
- console.log(inOut.getSteps().map((step) => step.runtimeStageId), ROOT_SUBFLOW_ID); // entry boundaries (timeline; root is first step)
742
- // [ '__root__#0', 'sf-double#1' ] __root__
743
- const { entry, exit } = inOut.getBoundary('sf-double#1')!; // { entry, exit } pair for one execution
744
- console.log(JSON.stringify(entry?.payload), JSON.stringify(exit?.payload));
745
- // {"q":21} {"q":21,"r":42}
746
- const rootBoundary = inOut.getRootBoundary(); // { entry, exit } for the top-level run
747
- console.log(JSON.stringify(rootBoundary?.entry?.payload), rootBoundary?.exit?.payload);
748
- // {"start":true} undefined
749
- // inOut.getBoundaries() — flat list (entry+exit interleaved)
750
- // inOut.getEntryRanges() — O(1) per-step range index for time-travel
167
+ executor.attachFlowRecorder({
168
+ id: 'attempts',
169
+ onAttempt: ({ stageId, record }) =>
170
+ console.log(stageId, record.kind, record.target ?? '-', `${record.attempt}/${record.of}`, record.outcome, record.reason),
171
+ });
172
+ await executor.run({ timeoutMs: 5_000 }); // one deadline for the whole run
173
+
174
+ // Output:
175
+ // declared worst case 3020
176
+ // fetch-rate stage - 1/3 failed retryable
177
+ // fetch-rate stage - 2/3 ok answered
178
+ // check-stock call inventory.lookup 1/2 failed retryable
179
+ // check-stock call inventory.lookup 2/2 ok answered
180
+ // check-stock stage - 1/1 ok answered
751
181
  ```
752
182
 
753
- **`InOutEntry` shape:**
183
+ `knownMs` counts only what declares a timeout. `Check stock` declares none, so it adds 0 and `worstCaseMs` is `null`. `timeBudget()` names every stage it cannot bound.
754
184
 
755
- | Field | Description |
756
- |---|---|
757
- | `runtimeStageId` | Same value for the entry/exit pair of one execution. Top-level run uses `'__root__#0'`. |
758
- | `subflowId` | Path-prefixed engine id. Top-level → `'__root__'`. Subflow → `'sf-outer'` or `'sf-outer/sf-inner'`. |
759
- | `localSubflowId` | Last segment of `subflowId` |
760
- | `subflowName` | Human-readable display name (`'Run'` for the top-level run) |
761
- | `description` | Build-time description (carries taxonomy markers like `'Agent: ReAct loop'`). Undefined for root. |
762
- | `subflowPath` | Decomposition of `subflowId` rooted under `__root__`: `['__root__']` for root, `['__root__', 'sf-x']` for top-level subflow |
763
- | `depth` | Root → 0. First-level subflow → 1. |
764
- | `phase` | `'entry'` or `'exit'` |
765
- | `payload` | `entry`: `inputMapper` result (subflow) or `run({input})` (root); `exit`: shared state at exit (subflow) or chart return value (root) |
766
- | `isRoot` | True only for the synthetic root pair from `onRunStart` / `onRunEnd` |
767
-
768
- **Pause semantics:** when a stage pauses inside a subflow, the engine re-throws without firing `onSubflowExit` (or `onRunEnd`). The chart has an `entry` with no matching `exit`: `getBoundary()` returns `{ entry, exit: undefined }`. Resuming on the same executor appends a second root pair and a fresh pair for the re-entered subflow (new runtimeStageId) — the first leg's dangling `entry` stays as recorded.
769
-
770
- **Engine events:** `FlowRecorder.onRunStart(event)` and `onRunEnd(event)` carry `event.payload` (the run's input or output). Fire ONCE per top-level `executor.run()` — not for subflow traversers (those fire `onSubflowEntry`/`onSubflowExit` instead). Available on the `IControlFlowNarrative` interface and the `FlowRecorderDispatcher`.
771
-
772
- **For downstream libraries:** compose, don't duplicate. A domain-flavored step graph (e.g., agentfootprint's `StepGraph`) should consume `InOutRecorder` output and label each entry by inspecting the payload through domain semantics — not re-walk subflow events.
773
-
774
- Example: [examples/runtime-features/flow-recorder/07-inout.ts](examples/runtime-features/flow-recorder/07-inout.ts)
775
-
776
- **Three recorder STORAGE PRIMITIVES (since 5.0.0)** — "one purpose per recorder": a store is storage ONLY. You own one as a field and implement the channel interface (`ScopeRecorder` / `FlowRecorder` / `EmitRecorder` / `CombinedRecorder`) yourself, delegating storage to the store. The abstract base classes (`KeyedRecorder` / `SequenceRecorder` / `BoundaryStateTracker`) were REMOVED in 7.0.0 — composition is the only model. Choose a store by data shape and durability:
777
-
778
- | Store | Relationship | Time scope | Use When |
779
- |------------|-------------|------------|----------|
780
- | `KeyedStore<T>` | 1:1 Map | durable | Each step produces one record (token totals per step) |
781
- | `SequenceStore<T>` | 1:N sequence + Map | durable | Multiple records per step, ordering matters (narrative, audit) |
782
- | `BoundaryStateStore<TState>` | Map\<key, TState\> active bracket | transient — clears on stop | Live state DURING a `[start, stop]` bracket (LLM stream partial, tool args streaming) |
185
+ ### Follow a value back
783
186
 
784
187
  ```typescript
785
- import { flowChart, FlowChartExecutor } from 'footprintjs';
786
- import type { FlowRecorder, EmitRecorder, EmitEvent, FlowStageEvent, FlowDecisionEvent } from 'footprintjs';
787
- import { KeyedStore, SequenceStore, BoundaryStateStore } from 'footprintjs/trace';
788
-
789
- // KeyedStore: one entry per step. Own the store; implement the channel.
790
- class TokenRecorder implements FlowRecorder {
791
- readonly id = 'tokens';
792
- private store = new KeyedStore<{ tokens: number }>();
793
- onStageExecuted(e: FlowStageEvent) {
794
- const rid = e.traversalContext?.runtimeStageId;
795
- if (rid) this.store.set(rid, { tokens: 10 });
796
- }
797
- byStep(rid: string) { return this.store.get(rid); } // Translate: per-step value
798
- total() { return this.store.aggregate((sum, e) => sum + e.tokens, 0); } // Aggregate: grand total
799
- upTo(keys: ReadonlySet<string>) { // Accumulate: up to slider
800
- return this.store.accumulate((sum, e) => sum + e.tokens, 0, keys);
801
- }
802
- }
803
-
804
- // SequenceStore: multiple entries per step, ordered.
805
- class AuditRecorder implements FlowRecorder {
806
- readonly id = 'audit';
807
- private store = new SequenceStore<{ runtimeStageId: string; type: string }>();
808
- onDecision(e: FlowDecisionEvent) {
809
- this.store.push({ runtimeStageId: e.traversalContext?.runtimeStageId ?? '', type: 'decision' });
810
- }
811
- forStep(rid: string) { return this.store.getByKey(rid); } // Translate: per-step entries
812
- upTo(keys: ReadonlySet<string>) { return this.store.getEntriesUpTo(keys); } // Progressive: up to slider
813
- ranges() { return this.store.getEntryRanges(); } // Range index: O(1) slider sync
814
- }
815
-
816
- // BoundaryStateStore: transient state DURING a bracket; clears on stop.
817
- class LiveLLMTracker implements EmitRecorder {
818
- readonly id = 'live-llm';
819
- private store = new BoundaryStateStore<{ partial: string; tokens: number }>();
820
- onEmit(e: EmitEvent) {
821
- const payload = e.payload as { content?: string };
822
- if (e.name === 'llm.start') this.store.start(e.runtimeStageId, { partial: '', tokens: 0 });
823
- if (e.name === 'llm.token') this.store.update(e.runtimeStageId, (s) => ({ partial: s.partial + (payload.content ?? ''), tokens: s.tokens + 1 }));
824
- if (e.name === 'llm.end') this.store.stop(e.runtimeStageId);
825
- }
826
- isInFlight() { return this.store.hasActive; } // O(1) — live read
827
- getPartial(rid: string) { return this.store.get(rid)?.partial ?? ''; } // O(1) — current state of one boundary
828
- concurrent() { return this.store.activeCount; } // O(1) — how many concurrent boundaries
188
+ // Follow a value back to the decision and the data that produced it.
189
+ import { decide, flowChart, FlowChartExecutor } from 'footprintjs';
190
+ import { controlDepRecorder } from 'footprintjs/trace';
191
+ import { causalChain, findLastWriter, formatCausalChain, keysReadFromExecutionTree } from 'foottrace';
192
+
193
+ interface ExportState {
194
+ width: number;
195
+ status?: string;
829
196
  }
830
- // Lifecycle: call store.clear() between runs; dev-mode warns on leaked-stop bugs.
831
197
 
832
- const tokens = new TokenRecorder();
833
- const audit = new AuditRecorder();
834
- const live = new LiveLLMTracker();
835
-
836
- const chart = flowChart<object>('Ask', (scope) => {
837
- scope.$emit('llm.start', {});
838
- scope.$emit('llm.token', { content: 'Hel' });
839
- scope.$emit('llm.token', { content: 'lo' });
840
- console.log(live.isInFlight(), live.concurrent(), live.getPartial('ask#0')); // mid-bracket
841
- scope.$emit('llm.end', {});
842
- }, 'ask')
843
- .addDeciderFunction('Check', () => 'ok', 'check')
844
- .addFunctionBranch('ok', 'Ok', () => {})
198
+ const chart = flowChart<ExportState>('LoadImage', (scope) => { scope.width = 640; }, 'load-image')
199
+ .addDeciderFunction('CheckResolution', (scope) => decide(scope, [
200
+ { when: { width: { gte: 1280 } }, then: 'export', label: 'Wide enough' },
201
+ ], 'reject'), 'check-resolution')
202
+ .addFunctionBranch('export', 'ExportImage', (scope) => { scope.status = 'exported'; })
203
+ .addFunctionBranch('reject', 'RejectExport', (scope) => { scope.status = 'rejected'; })
845
204
  .end()
846
205
  .build();
847
206
 
848
207
  const executor = new FlowChartExecutor(chart);
849
- executor.attachFlowRecorder(tokens);
850
- executor.attachFlowRecorder(audit);
851
- executor.attachEmitRecorder(live);
208
+ const control = controlDepRecorder(); // connects a branch to the decision that chose it
209
+ executor.setReadTracking('full'); // data edges need the recorded reads; set both before run()
210
+ executor.attachCombinedRecorder(control);
852
211
  await executor.run();
853
212
 
854
- console.log(tokens.total(), tokens.byStep('ask#0'), tokens.upTo(new Set(['ask#0'])));
855
- console.log(live.isInFlight(), live.concurrent(), JSON.stringify(audit.forStep('check#1')), audit.ranges().size);
856
- // true 1 Hello
857
- // 30 { tokens: 10 } 10
858
- // false 0 [{"runtimeStageId":"check#1","type":"decision"}] 1
859
- ```
860
-
861
- **`getEntryRanges()`** returns a precomputed `Map<runtimeStageId, {firstIdx, endIdx}>` maintained during `push()`. Use for O(1) per-step range lookups during time-travel scrubbing. Same shape as `buildEntryRangeIndex()` in `footprint-explainable-ui`.
862
-
863
- **`CombinedNarrativeEntry.direction`** — subflow entries carry `direction: 'entry' | 'exit'` (and `subflowId`). Use for programmatic subflow boundary detection instead of text scanning (which breaks with a custom `NarrativeFormatter`).
864
-
865
- **`footprint-explainable-ui` narrative utilities** (read from that package's source, 0.38.0) — for consumers building custom shells without `ExplainableShell`:
866
- - `buildEntryRangeIndex(entries)` — build range index from flat array (when no recorder access)
867
- - `computeRevealedEntryCount(entries, snapshots, idx, rangeIndex?)` — slider position → entry count
868
- - `extractSubflowNarrative(entries, subflowId)` — three-tier subflow entry extraction
869
-
870
- **How runtimeStageId is generated:** A counter starts at 0 and increments by 1 for each stage execution across the entire run, including subflow stages. Subflow child traversers share the parent counter so indices are globally unique. Stages inside subflows have stageIds already prefixed by the builder (e.g., `sf-tools/execute-tool-calls`), so the engine's `buildRuntimeStageId(prefixedId, idx)` just appends `#index`.
213
+ const { commitLog, executionTree } = executor.getSnapshot();
214
+ const writer = findLastWriter(commitLog, 'status');
215
+ const reads = keysReadFromExecutionTree(executionTree);
216
+ const chain = writer && causalChain(commitLog, writer.runtimeStageId, reads.lookup, { controlDeps: control.asLookup() });
217
+ if (chain) console.log(formatCausalChain(chain));
871
218
 
872
- ## Dev Mode
873
-
874
- One global flag (`enableDevMode()` / `disableDevMode()` / `isDevMode()`) controls every developer-only diagnostic across the library. OFF by default — the diagnostics below run only when it is on.
875
-
876
- ```typescript
877
- import { flowChart, FlowChartExecutor, enableDevMode, disableDevMode, isDevMode } from 'footprintjs';
878
-
879
- console.log(isDevMode());
880
- // false
881
- enableDevMode(); // in a real app: if (process.env.NODE_ENV !== 'production') enableDevMode();
882
-
883
- const warnings: string[] = [];
884
- console.warn = (message: string) => { warnings.push(message.split(' — ')[0]); };
885
-
886
- const executor = new FlowChartExecutor(flowChart<{ n: number }>('Seed', (scope) => { scope.n = 1; }, 'seed').build());
887
- executor.attachCombinedRecorder({ id: 'empty' }); // no on* handler: warns
888
- await executor.run();
889
- console.log(warnings);
890
- // [
891
- // "[footprintjs] attachCombinedRecorder: recorder 'empty' has no observer event methods"
892
- // ]
893
- console.log(Object.isFrozen(executor.getSnapshot().sharedState)); // dev mode: a deep-frozen clone, not the live state
894
- // true
895
- disableDevMode();
896
- ```
897
-
898
- Gated diagnostics (not exhaustive; each is gated on `isDevMode()` in the source):
899
- - **Circular-ref detection** in scope writes (`ScopeFacade.setValue()`) — O(n) WeakSet traversal per write
900
- - **Empty-recorder warning** in `attachCombinedRecorder(r)` — catches `r` with no `on*` handler
901
- - **`decide()` / `select()` rules** that throw while evaluating, or filter ops that are not one of `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `notIn` (the rule counts as not matched)
902
- - **Snapshot integrity** in `getSubtreeSnapshot()`
903
- - **Recorder hook errors** — a recorder hook that throws is isolated and, in dev mode, warned about; it does not abort the run — except `onResume`, which the executor calls unguarded (a throw rejects `resume()`), and, in dev mode, a hook that throws a value that cannot be stringified (a null-prototype object rejects `run()`).
904
- - **`getSnapshot().sharedState`** becomes a deep-frozen clone, so a mutation throws instead of corrupting engine state
905
- - **A subflow id mounted twice** — warned at build time (a pause inside it could not be resumed)
906
-
907
- Convention: when adding a new dev-only check, gate on `isDevMode()` (from `lib/devMode.ts`). Do NOT use `process.env.NODE_ENV` inline — consumers control dev tooling centrally via `enableDevMode()`/`disableDevMode()`, and inline env checks break that contract.
908
-
909
- ## Break + Propagation
910
-
911
- `scope.$break(reason?)` takes an optional free-form reason string that surfaces on `FlowBreakEvent.reason`. Recorders and narrative consumers see it.
912
-
913
- By default, an inner subflow's `$break` stops ONLY the subflow; the parent continues. Opt into propagation via `SubflowMountOptions.propagateBreak: true`:
914
-
915
- ```typescript
916
- import { flowChart, FlowChartExecutor } from 'footprintjs';
917
-
918
- const escalateChart = flowChart<{ partial?: string; later?: boolean }>('Escalate', (scope) => {
919
- scope.partial = 'from-subflow';
920
- scope.$break('policy violation');
921
- }, 'escalate')
922
- .addFunction('NeverRuns', (scope) => { scope.later = true; }, 'never-runs')
923
- .build();
924
-
925
- for (const propagateBreak of [false, true]) {
926
- const chart = flowChart<{ seed?: boolean; got?: string; after?: boolean }>('Seed', (scope) => { scope.seed = true; }, 'seed')
927
- .addSubFlowChartNext('sf-escalate', escalateChart, 'Escalate', {
928
- outputMapper: (sub: { partial?: string }) => ({ got: sub.partial }),
929
- propagateBreak, // ← inner $break → parent $break, with reason
930
- })
931
- .addFunction('After', (scope) => { scope.after = true; }, 'after')
932
- .build();
933
- const executor = new FlowChartExecutor(chart);
934
- const breaks: string[] = [];
935
- executor.attachFlowRecorder({
936
- id: 'breaks',
937
- onBreak: (e) => { breaks.push(`${e.stageName}: ${e.reason}${e.propagatedFromSubflow ? ` (from ${e.propagatedFromSubflow})` : ''}`); },
938
- });
939
- await executor.run();
940
- console.log(propagateBreak, JSON.stringify(executor.getSnapshot().sharedState), breaks);
941
- }
942
- // false {"seed":true,"got":"from-subflow","after":true} [ 'sf-escalate/Escalate: policy violation' ]
943
- // true {"seed":true,"got":"from-subflow"} [
944
- // 'sf-escalate/Escalate: policy violation',
945
- // 'Escalate: policy violation (from sf-escalate)'
946
- // ]
219
+ // Output:
220
+ // RejectExport (reject#2) [wrote: status]
221
+ // CheckResolution (check-resolution#1) ← [control]
222
+ // LoadImage (load-image#0) ← via width [wrote: width]
947
223
  ```
948
224
 
949
- Semantics:
950
- - **Linear chain:** inner `$break(reason)` → parent's `breakFlag` flips → next parent stage does NOT run → `FlowBreakEvent` fires at parent-mount level with `propagatedFromSubflow` + reason.
951
- - **Nested chain:** propagates through every hop that opted in (a hop that did not opt in stops the propagation there). Reason survives.
952
- - **outputMapper still runs** before propagation — subflow's partial state lands in parent before the break (`got` above). Escape hatch: early-return `{}` from outputMapper when the break state is set.
953
- - **Parallel/fan-out:** a `$break` in a fork child stops that child; the parent continues after the fork even when EVERY child broke (the "all children broke" rule in `ChildrenExecutor` is not wired). `propagateBreak: true` does not change that.
954
-
955
- Example: [examples/runtime-features/break/04-subflow-propagate.ts](examples/runtime-features/break/04-subflow-propagate.ts).
956
-
957
- ## Emit Channel (Phase 3)
958
-
959
- Third observer channel alongside `ScopeRecorder` (data-flow) and `FlowRecorder` (control-flow). Consumer stage code emits structured events; `EmitRecorder.onEmit(event)` fires synchronously with auto-enriched context.
960
-
961
- ```typescript
962
- import { flowChart, FlowChartExecutor } from 'footprintjs';
963
- import type { EmitRecorder, EmitEvent } from 'footprintjs';
964
-
965
- const tallies: unknown[] = [];
966
- const rec: EmitRecorder = {
967
- id: 'token-meter',
968
- onEmit: (e) => { if (e.name === 'myapp.llm.tokens') tallies.push(e.payload); },
969
- };
970
-
971
- const sub = flowChart<object>('SubStage', (scope) => { scope.$emit('myapp.sub.event', { in: 'sub' }); }, 'sub-stage').build();
972
- const chart = flowChart<object>('Meter', (scope) => {
973
- // Inside a stage:
974
- scope.$emit('myapp.llm.tokens', { input: 100, output: 50 });
975
- scope.$emit('myapp.auth.check', { secret: 'x' }); // matched by emitPatterns below
976
- scope.$debug('k', 1); scope.$error('e', 2); scope.$metric('m', 3); scope.$eval('ev', 4); scope.$log('hello');
977
- }, 'meter')
978
- .addSubFlowChartNext('sf', sub, 'Sub')
979
- .build();
980
-
981
- const executor = new FlowChartExecutor(chart);
982
- executor.enableNarrative({
983
- renderer: {
984
- renderEmit: (ctx) => (ctx.name === 'myapp.llm.tokens' ? `Tokens: ${JSON.stringify(ctx.payload)}` : undefined),
985
- },
986
- });
987
- executor.setRedactionPolicy({ emitPatterns: [/\.auth\./] });
988
- executor.attachEmitRecorder(rec); // Recorder observes
989
- const seen: EmitEvent[] = [];
990
- executor.attachEmitRecorder({ id: 'all', onEmit: (e) => { seen.push(e); } });
991
- await executor.run();
992
-
993
- console.log(JSON.stringify(tallies));
994
- // [{"input":100,"output":50}]
995
- console.log(seen.map((e) => e.name));
996
- // [
997
- // 'myapp.llm.tokens',
998
- // 'myapp.auth.check',
999
- // 'log.debug.k',
1000
- // 'log.error.e',
1001
- // 'metric.m',
1002
- // 'eval.ev',
1003
- // 'log.debug.messages',
1004
- // 'myapp.sub.event'
1005
- // ]
1006
- const { timestamp, ...enriched } = seen[seen.length - 1];
1007
- console.log(JSON.stringify(enriched), typeof timestamp);
1008
- // {"name":"myapp.sub.event","payload":{"in":"sub"},"stageName":"sf/SubStage","runtimeStageId":"sf/sub-stage#2","subflowPath":["sf"],"pipelineId":"","sourcePosition":{"runId":"…","logRunId":"…","drillPath":["sf#1"],"committedThroughIdx":-1}} number
1009
- console.log(JSON.stringify(seen[1].payload));
1010
- // "[REDACTED]"
1011
- console.log(executor.getNarrativeEntries().filter((e) => e.type === 'emit').map((e) => e.text).slice(0, 3));
1012
- // [
1013
- // 'Tokens: {"input":100,"output":50}',
1014
- // '[emit] myapp.auth.check: "[REDACTED]"',
1015
- // '[emit] log.debug.k: {key, value, level}'
1016
- // ]
1017
- ```
1018
-
1019
- ### Semantics
1020
- - **Pass-through.** Delivered synchronously, in call order. `ScopeFacade.emitEvent` returns immediately when no recorder is attached.
1021
- - **Auto-enriched.** Events carry `stageName`, `runtimeStageId`, `subflowPath`, `pipelineId`, `timestamp` — in a subflow, the stage name and runtimeStageId carry the path prefix and `subflowPath` lists it.
1022
- - **Error-isolated.** A throwing `onEmit` doesn't propagate; errors route to `onError` on other recorders.
1023
- - **Redactable.** `RedactionPolicy.emitPatterns: RegExp[]` matches `event.name`; matched payloads become `'[REDACTED]'` before dispatch.
1024
- - **Buffered in narrative.** `CombinedNarrativeRecorder.onEmit` buffers alongside reads/writes; flushed in `flushOps` so emit entries appear AFTER the stage header in ordered narrative.
1025
-
1026
- ### Naming convention
1027
- Hierarchical dotted names — `<namespace>.<category>.<event>` (a convention: any name is accepted). Examples:
1028
- - `'agentfootprint.llm.tokens'`, `'agentfootprint.llm.request'`
1029
- - `'myapp.billing.spend'`, `'myapp.auth.check'`
1030
-
1031
- ### Legacy primitives route through this channel
1032
- `$debug`, `$metric`, `$error`, `$eval`, `$log` also dispatch on the emit channel (in addition to their existing `DiagnosticCollector` side-bag writes for snapshot inclusion):
1033
-
1034
- ```
1035
- $debug(key, value) → emits 'log.debug.${key}'
1036
- $error(key, value) → emits 'log.error.${key}'
1037
- $metric(name, value) → emits 'metric.${name}'
1038
- $eval (name, value) → emits 'eval.${name}'
1039
- $log(value) → emits 'log.debug.messages'
1040
- ```
1041
-
1042
- So `$metric` / `$debug` are observable by recorders in real time; the side bags still populate for consumers that inspect snapshots directly.
1043
-
1044
- A redaction policy's state selectors also select a diagnostic entry by its NAME (`keys: ['token']` masks `$debug('token', …)`, `$error`, `$metric` and a `token` nested in a logged record). `RedactionPolicy.diagnostics` adds diagnostic-only selectors (`logs`, `errors`, `metrics`, `evals` and flow-message text, which has no name of its own). The collector decides before storage; the facade emits the same retained incoming value, then applies any `emitPatterns` whole-wrapper mask. Do not re-scrub at recorders or snapshot export. Entries and flow metadata remain; the checkpoint's operational state stays real. See `docs/guides/scope.md` → "The one law" and "Explicit diagnostic redaction".
1045
-
1046
- A policy also covers what a stage's own code puts in a record. A `decide()` / `select()` threshold can be a hole: `threshold: '[REDACTED]'` with `thresholdRedacted: true`. Read the marker, because `'[REDACTED]'` can be a real threshold; `redacted` speaks only for the actual value. `matchError` and a `$break` reason can read as the placeholder too. A rule's `label` is author text and is served as written, so do not build one from a selected value. See `docs/guides/scope.md` → "Decision evidence and break reasons".
1047
-
1048
- ### Customizing narrative rendering
1049
- `NarrativeFormatter.renderEmit?(ctx)` hook (passed as `enableNarrative({ renderer })`) renders an emit event into a narrative line. Return `string` to use, `null` to exclude, `undefined` to fall back to the default `[emit] name: payloadSummary` (above: the first line is the custom one, the rest are defaults).
1050
-
1051
- Example: [examples/runtime-features/emit/01-custom-events.ts](examples/runtime-features/emit/01-custom-events.ts).
1052
-
1053
- ## Combined Recorder
1054
-
1055
- A `CombinedRecorder` is an observer that hooks into multiple event streams (scope data-flow, control-flow, AND emit — all three channels). One object, one `id`, one `attachCombinedRecorder()` call — the library routes to the right channels via runtime method-shape detection.
1056
-
1057
- ```typescript
1058
- import { flowChart, FlowChartExecutor, isFlowEvent } from 'footprintjs';
1059
- import type { CombinedRecorder } from 'footprintjs';
1060
-
1061
- const log = (...parts: unknown[]) => console.log(...parts);
1062
-
1063
- const audit: CombinedRecorder = {
1064
- id: 'audit',
1065
- onWrite: (e) => log('scope write', e.key), // Recorder stream
1066
- onDecision: (e) => log('routed to', e.chosen), // FlowRecorder stream
1067
- onError: (e) => {
1068
- // Shared method — union payload. Discriminate with isFlowEvent():
1069
- if (isFlowEvent(e)) log('flow error in', e.stageName);
1070
- else log('scope error during', e.operation);
1071
- },
1072
- };
1073
-
1074
- const chart = flowChart<{ n: number }>('Seed', (scope) => { scope.n = 1; }, 'seed')
1075
- .addFunction('Boom', () => { throw new Error('kaput'); }, 'boom')
1076
- .build();
1077
-
1078
- const executor = new FlowChartExecutor(chart);
1079
- executor.attachCombinedRecorder(audit);
1080
- await executor.run().catch(() => undefined);
1081
- // scope write n
1082
- // flow error in Boom
1083
- ```
1084
-
1085
- Built on `CombinedRecorder`: `CombinedNarrativeRecorder` (the `executor.enableNarrative()` default). Consumers implement ONLY the events they care about — `Partial<ScopeRecorder> & Partial<FlowRecorder> & Partial<EmitRecorder>` under the hood.
1086
-
1087
- **Detection rule:** a handler counts when it is an OWN property OR a method on the recorder's class prototype chain — class instances work. Only handlers inherited from `Object.prototype` are ignored (prevents accidental `Object.prototype` pollution from attaching handlers).
1088
-
1089
- ## Anti-Patterns
1090
-
1091
- - Never post-process the tree — use recorders (or the `foottrace` queries over the recorded log)
1092
- - Don't use `getValue()`/`setValue()` for keys you know in TypedScope stages — use typed property access (`$getValue`/`$setValue` are for dynamic keys; plain `scope.getValue` does not exist there)
1093
- - Don't give a state key the name of a `$` method (`scope.$break = 1` throws "conflicts with a reserved TypedScope method") — the reserved names are `SCOPE_METHOD_NAMES` in `footprintjs/advanced`; avoid `$`-prefixed state keys altogether
1094
- - Don't write a state key that is also a `run({ input })` key — input keys are read-only for the run
1095
- - `CombinedNarrativeBuilder` is gone (removed in v1.0) — the narrative comes from `CombinedNarrativeRecorder` via `executor.enableNarrative()` or the `narrative()` factory
1096
- - Don't extract a shared base for scope and flow recorders — built-ins compose a store (`KeyedStore` / `SequenceStore`) as a field
1097
- - Don't use `getArgs()` for tracked data — use typed scope properties
1098
- - Don't put infrastructure data in `getArgs()` — use `getEnv()` via `run({ env })`
1099
- - Don't hand-roll a recorder to get the narrative — `executor.enableNarrative()` (or `chart.recorder(narrative())`) is the whole setup, and it is off until called
1100
- - Don't end a loop with `return` — `.loopTo(id)` is unconditional; exit through a decider branch or `scope.$break()`
1101
- - Don't return full arrays from `outputMapper` without `arrayMerge: ArrayMergeMode.Replace` — default `applyOutputMapping` **concatenates** arrays (`[...parent, ...subflow]`). Either return only the **delta** (new items), or set `arrayMerge: ArrayMergeMode.Replace` on `SubflowMountOptions` to overwrite instead of concatenate. Scalars are always replaced regardless. `ArrayMergeMode` is exported from `footprintjs/advanced` (not the main door).
1102
-
1103
- ```typescript
1104
- import { flowChart, FlowChartExecutor } from 'footprintjs';
1105
- import { ArrayMergeMode } from 'footprintjs/advanced';
1106
-
1107
- const sub = flowChart<{ items?: string[] }>('Sub', (scope) => { scope.items = ['a', 'b']; }, 'sub').build();
1108
- for (const arrayMerge of [ArrayMergeMode.Concat, ArrayMergeMode.Replace]) {
1109
- const chart = flowChart<{ items: string[] }>('Seed', (scope) => { scope.items = ['a']; }, 'seed')
1110
- .addSubFlowChartNext('sf', sub, 'Sub', { outputMapper: (out: { items?: string[] }) => ({ items: out.items }), arrayMerge })
1111
- .build();
1112
- const executor = new FlowChartExecutor(chart);
1113
- await executor.run();
1114
- console.log(arrayMerge, JSON.stringify(executor.getSnapshot().sharedState.items));
1115
- }
1116
- // concat ["a","a","b"]
1117
- // replace ["a","b"]
1118
- ```
1119
-
1120
- ## Build & Test
225
+ The rejecting stage reads nothing, so data edges alone would miss the decision. `controlDepRecorder()` supplies that edge. The chain shows the recorded path, not whether 1280 is the right rule.
226
+
227
+ ## Anti-patterns
228
+
229
+ - **Don't walk the tree after a run.** Use a recorder during the run, or a `foottrace` query over the record.
230
+ - **Don't write a retry loop inside a stage.** The record shows one stage and hides the failed tries. Declare `.retry()` or use `scope.$call()`.
231
+ - **Don't leave an SDK retrying unseen.** Turn its retries off and run one loop under `scope.$call()`, or report each try with `scope.$attempt().observed()`.
232
+ - **Don't retry an outside effect without a key.** `build()` refuses `.touches()` plus a retry with no `idempotencyKey`. An unknown final effect fails the run with `UnknownEffectError`. Reconcile by the key, or use `.addRetryLoop()`.
233
+ - **Don't use `$getValue()` or `$setValue()` for keys you know.** Write `scope.amount = 1`. Those two are for dynamic keys.
234
+ - **Don't start a state key with `$`.** `scope.$break = 1` throws. `SCOPE_METHOD_NAMES` lists the reserved names.
235
+ - **Don't write a state key that is also an input key.** `run({ input })` keys are read-only for the run, and an `inputMapper`'s keys inside its subflow. The write throws.
236
+ - **Don't use `$getArgs()` for tracked data or `$getEnv()` for business data.** Both are frozen and untracked. Env is for signals, deadlines and trace IDs.
237
+ - **Don't edit a raw value in place.** What `$getValue()`, `$read()`, `$toRaw()`, `find()` or `for…of` hands back can be the committed object. Editing it changes past state with no row in the record. Assign a copy.
238
+ - **Don't store what `structuredClone` cannot copy.** A function or a foreign proxy fails the stage at commit, and none of that stage's writes land.
239
+ - **Don't expect a failed stage to roll back.** Its writes commit before `run()` rejects. `getSnapshot()` shows them.
240
+ - **Don't end a loop with `return`.** `.loopTo()` is unconditional, and after `.end()` every branch loops. Chain it on one decider branch, or exit with `scope.$break()`. With no exit the run rejects at `maxIterations`, default 1000.
241
+ - **Don't leave a decider without a way out.** An id that matches no branch throws unless `.setDefault()` names a fallback.
242
+ - **Don't read a parallel child's write as `scope.key`.** It lands under `runs/<childId>/`. Use `scope.$read('runs.<childId>.key')`, or make the child a subflow with an `outputMapper`.
243
+ - **Don't expect a subflow to see its parent.** With no `inputMapper` it starts empty. An inner `$break()` stops only the subflow unless the mount sets `propagateBreak: true`.
244
+ - **Don't return a whole array from `outputMapper`.** Arrays concatenate by default. Return the new items, or set `arrayMerge: ArrayMergeMode.Replace`.
245
+ - **Don't look for `.recorder()` on the executor.** It and `.redact()` are on the built chart. The executor has `enableNarrative()` and the `attach*Recorder()` methods.
246
+ - **Don't treat narrative entries as strings.** `getNarrativeEntries()` returns objects, and `[]` unless `enableNarrative()` ran before `run()`. Use `entry.text`.
247
+ - **Don't share an executor between concurrent runs.** A second `run()` rejects with `RunInFlightError`.
248
+ - **Don't do what cannot run twice before `interrupt()`.** Resume re-runs the stage from its top. A pause inside a lazy subflow or an `.addParallelForEach()` branch cannot resume.
249
+ - **Don't re-scrub in a recorder.** `setRedactionPolicy()` covers what the library keeps or serves, never live state or the checkpoint. `getSnapshot().sharedState` holds real values; `getSnapshot({ redact: true })` is the scrubbed copy.
250
+ - **Don't expect a policy to search text.** It selects by name, never by content. With `keys: ['token']`, `$debug('token', scope.token)` is masked; `$log('token=' + scope.token)` is not. Keep selected values out of free text
251
+ - **Don't read `threshold: '[REDACTED]'` as a value.** Under a policy it can be a hole, and `thresholdRedacted: true` says so. `matchError` and a `$break` reason can be masked too. A rule's `label` is author text: never build one from a selected value
252
+ - **Don't reach for `footprintjs/advanced` in app code.** It holds engine internals. Of its names, ordinary charts usually need only `ArrayMergeMode`.
253
+
254
+ ## Working on this library
255
+
256
+ Read `CLAUDE.md` for the module map and `CONTRIBUTING.md` for the workflow. Neither ships in the npm package. This file is generated: edit `ai-instructions/source/`, then run `npm run ai:generate`.
1121
257
 
1122
258
  ```bash
1123
- npm run build # tsc (CJS) + tsc -p tsconfig.esm.json (ESM) + scripts/postbuild-esm.mjs
1124
- npm test # full suite (vitest)
1125
- npm run test:examples # type-check examples/, build, then run the fork example guard
259
+ npm run build
260
+ npm test
261
+ npm run test:examples
1126
262
  npm run lint
1127
- npm run check:layering # the layering rule and the closed record, from scripts/layering.config.cjs
1128
- npm run check:doc-snippets # strict, isolated import-bearing TS fences; see scripts/doc-snippets/README.md
263
+ npm run check:layering
264
+ npm run check:doc-snippets
265
+ npm run check:ai-instructions
1129
266
  ```
1130
-
1131
- Dual output: CommonJS (`dist/`) + ESM (`dist/esm/`) + types (`dist/types/`)