pi-todo-ledger 0.9.0 → 0.11.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/CONTRACT.md CHANGED
@@ -76,6 +76,8 @@ The file contains the snapshot `data` itself, not the surrounding session entry.
76
76
  Import requires an empty list (even a tombstone counts as a task), unique task ids, a task for every `blockedBy` id, and a `nextId` greater than every task id.
77
77
  New snapshots carry the writer's `sessionId`. Import uses it to set each task's `origin.session`, replacing any previous source. If the snapshot lacks `sessionId`, import leaves `origin` untouched. All other task fields, including historical evidence timestamps, and the supplied `nextId` are preserved.
78
78
 
79
+ Since 0.11.0 the `flow` tool appends through the same import path to a list that need not be empty; see [Flow templates](#5-flow-templates).
80
+
79
81
  ### Migration from rpiv-todo
80
82
 
81
83
  When a branch has no `todo/v1` entry, the extension restores the list from rpiv-todo's records, newest first by kind:
@@ -183,7 +185,7 @@ A match issues a normal guarded `update`: `owner` becomes the full `details.name
183
185
  `pane` is the acknowledged `details.worktree.paneId` and is absent for ordinary launches.
184
186
  The top-level fields always describe the latest assignment. An old pane id does not carry forward. For example, after a reviewer joins a worker on the same task, `owner` and `metadata.herdr.id` identify the reviewer.
185
187
 
186
- New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
188
+ New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent?, also? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. `also` lists the session files the run ended on besides its own ([Run spend](#run-spend-metadataherdrspend)); a resume of any of them binds as one of `session` does. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
187
189
 
188
190
  A successful `subagent_resume` appends its new run id when its acknowledged `sessionPath` matches a retained session path on exactly one non-deleted task in the calling session. An unknown or ambiguous path binds nothing.
189
191
  Other metadata stays intact; a refusal leaves the launch successful but adds the reason to its response.
@@ -195,6 +197,42 @@ For names longer than 24 UTF-16 units, Straw Boss displays just the first 23 uni
195
197
  Resolve the live pane at read time rather than targeting that cosmetic label or a saved pane id.
196
198
  This namespace needs no new status, schema field, or contract version.
197
199
 
200
+ ### Run spend (`metadata.herdr.spend`)
201
+
202
+ Since 0.10.0, when a bound run ends, the ledger records what it spent on its task.
203
+ A run's end arrives two ways:
204
+
205
+ - the host's event `subagent:run-end` on `pi.events`, `{ v: 1, id, kind, name?, item?, sessionFile?, elapsed?, attempts? }`: `id` is the run id the launch acknowledged (`details.id`), `kind` is `"result"` or `"ping"`, `elapsed` the run's wall time in seconds, and `attempts` every spawned attempt of the run in order, `{ model?, sessionFile?, elapsed }`, a fallback's failed ones included. Only `v`, `id`, and `kind` are required: a run that failed before it wrote a session file ends without `sessionFile` and counts its time, and the ledger never reads `name` or an attempt's `model`. The host sends it as it delivers the end, so an end still counts when its message never reaches the model (a steer cleared before the turn);
206
+ - the custom message in the calling session: `subagent_result` when the run finished or `subagent_ping` when it stopped to ask. Its `details` carry the same `id`, `item`, `sessionFile`, `elapsed`, and `attempts` when the host supplies them (Maestro since `sb-host-a5a9c43`).
207
+
208
+ The ledger finds the task as the launch bound it: the non-deleted task whose `metadata.herdr.runs` hold the run id, else one of the end's session files, else, by `item`, the task with that uid.
209
+ A bare `<session8>#<id>` is never looked up by its number at the end: after `clear` or a branch switch the number names another task, and the launch's binding is what proves the identity.
210
+ No match, several matches, or a deleted task leave the list unchanged.
211
+
212
+ It reads each session file the end names (each attempt's, else `sessionFile`) and sums the `usage` of every assistant turn in it (every branch: all of it was spent), except the turns a fork copied from the launcher: a turn older than the file's `session` header, or one whose entry id the calling session holds.
213
+ Then it writes `metadata.herdr.spend` as an `update` of that task, keeping every other `metadata` key:
214
+
215
+ ```json
216
+ {
217
+ "input": 1500, "output": 300, "cacheRead": 3000, "cacheWrite": 0, "tokens": 4800, "cost": 0.75,
218
+ "ms": 125000, "runs": 1, "models": ["anthropic/claude-opus-5-5"], "ended": [{ "id": "0accb6d1-4380-4d51-a6d7-81dd0408d82f", "by": "event", "proc": "5f0c…" }],
219
+ "sessions": [{ "session": "/path/child.jsonl", "input": 1500, "output": 300, "cacheRead": 3000, "cacheWrite": 0, "tokens": 4800, "cost": 0.75, "models": ["anthropic/claude-opus-5-5"] }]
220
+ }
221
+ ```
222
+
223
+ The top-level figures are the task's totals over all its runs: `tokens` is pi's `totalTokens`, `cost` its `cost.total` in US dollars, `ms` the sum of the ends' wall time (an end with `attempts` adds its attempts' `elapsed`, else its own), `runs` the number of ended runs (results and pings), and `models` the `provider/model` ids seen, first seen first, at most eight.
224
+ `ended` holds a proof for each run counted by one half of its end (`by`: `"event"` or `"message"`) while the other half may still come, so the event and the message of one run count once however many other runs end in between. Both halves belong to the pi process that sent them (`proc`): the host emits the event as it sends the message, and a queued message is lost with its process. A proof leaves at the task's next write once its other half came, or when it was left by another process; a message cleared before the model read it leaves its proof until its process ends.
225
+ When an end tied to its launch by its run id names a final session file other than the launch's (a fallback's last attempt), the ledger adds that file to the bound run's `also` in `metadata.herdr.runs` (at most four), so a `subagent_resume` of it binds to the same task and its spend is counted there.
226
+ A resume continues the same session file, so the ledger replaces that session's figures with the file's new total instead of adding them again; `sessions` keeps up to twelve, newest last, and an older one stays in the totals but is no longer told apart.
227
+ A file that cannot be read adds the run and its time, not tokens.
228
+ A later launch keeps `spend` when it rebinds `metadata.herdr`.
229
+
230
+ The write is synchronous: in one tick it reads the list from the branch pi is on (its newest `todo/v1` snapshot, not the in-memory list, which a `session_tree` replay still to run may hold from the branch before), reads the files, and appends the snapshot.
231
+ No branch switch, replay, or shutdown can come between the read and the append, so the write lands on the branch pi is on, with that branch's tasks: a branch that does not hold the bound task records nothing.
232
+ A `todo` call of the session that is running or queued holds the list while its guards run; the write then waits its turn in the session's queue and does the same there, and one queued before `session_shutdown` is dropped.
233
+ Namespace validators judge the write as any `update`; change guards (see [Change guards](#4-change-guards)) are not asked: they are awaited, and the write records a run that already happened (the boss's decision, 2026-11-28: 「不經過關卡」). A guard such as Straw Boss's train guard therefore never sees or refuses a spend write, which changes only `metadata.herdr`. A validator's refusal leaves the list unchanged and appends `Todo spend: <reason>` to the message.
234
+ The figures are an estimate from what pi wrote in the child's transcript, bookkeeping rather than a bill. `get` shows them on a `spend:` line.
235
+
198
236
  ## 4. Change guards
199
237
 
200
238
  A namespace validator judges one task's value.
@@ -215,12 +253,13 @@ const register = () =>
215
253
 
216
254
  A later registration of the same `id` replaces the earlier one; the extension ignores, with a console warning, a payload whose `v` is not 1, whose `id` is empty, or whose `check` is not a function.
217
255
 
218
- The extension calls `check(change)` for every call that would change the list: `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
256
+ The extension calls `check(change)` for every call that would change the list (the ledger's own [run spend](#run-spend-metadataherdrspend) record does not reach them): `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
219
257
  On import, namespace validators see each relevant task as a `create`.
220
258
  Guard registration accepts an optional `imports: true` field within v1.
221
259
  If any registered guard has not opted in, the tool returns `Error: guard <id> refused: guard does not accept imports` without calling the guards or committing the list.
222
260
  Otherwise each guard sees one `op: "create"` with `params.action: "import"`, the original `path` or `session`, an empty `before`, and the full imported list in `after`.
223
261
  A guard that accepts imports must judge the tasks in `change.after`, not `change.params`: the arguments name the snapshot file but do not contain its tasks.
262
+ A [flow append](#5-flow-templates) is an import too, with `params.flow` set: `before` holds the current list and `after` adds the appended tasks; a guard finds them as the tasks of `after` whose ids are not in `before`.
224
263
  A valid `update` that changes nothing, such as setting `in_progress` on a task already in progress after `/reload`, reaches the guards too, flagged `noop: true`: it is how an agent restates a task's state, and a guard may track it.
225
264
  `change` matches `$defs/change` in the schema and is a copy:
226
265
 
@@ -255,7 +294,111 @@ The same holds along a chain of guards: when session A's guard calls `todo` for
255
294
  Calling `todo` for a session whose guard is not running further up the chain is allowed.
256
295
  A call aborted (through the tool's abort signal) while it waits for an earlier call or while its guards run commits nothing and returns `Error: call aborted; nothing changed`, a `noop` update included.
257
296
 
297
+ ## 5. Flow templates
298
+
299
+ Since 0.11.0 the `flow` tool expands a template, a YAML file that describes a fixed procedure, into todos appended to the session's list in one write.
300
+ The template describes only the shape of the procedure. Once expanded, the todos are the only record of its progress, and the file is not read again: editing a template changes the next expansion, never the todos already in a list.
301
+
302
+ ### Where templates live
303
+
304
+ | Level | Files | Read when |
305
+ | --- | --- | --- |
306
+ | user | `<agent dir>/flows/*.yaml`, the agent dir being `PI_CODING_AGENT_DIR` or `~/.pi/agent` | always |
307
+ | project | `<repository>/.pi/flows/*.yaml`, the repository being the nearest directory from the session's cwd up that holds `.git` (else the cwd) | when `ctx.isProjectTrusted()` returns `true`; a host without that method gets no project templates |
308
+
309
+ The file `<name>.yaml` defines the flow `<name>`, and its `flow` field must say the same.
310
+ Links are followed, and one file reached through two links counts once.
311
+ A name that two files define is refused with both paths, never resolved by level.
312
+ A file that is no valid template, or whose `flow` differs from its file name, is listed with its errors and refuses only the name of its file; every other flow stays usable.
313
+
314
+ ### Format
315
+
316
+ ```yaml
317
+ flow: release-pin-install # lowercase letters, digits, -
318
+ rev: 1 # whole number from 1
319
+ summary: Release a pi package, pin it, install it when idle
320
+ auth: required # or none (the default)
321
+ key: "{{pkg}}@{{version}}" # names one run of the flow
322
+ params:
323
+ pkg: { doc: package name, pattern: "^pi-[a-z0-9-]+$" }
324
+ version: { pattern: "[0-9]+\\.[0-9]+\\.[0-9]+" }
325
+ root: { pattern: "[~A-Za-z0-9._/-]+", default: "~/projects/agent-root" }
326
+ steps:
327
+ - id: release
328
+ subject: Release {{pkg}} {{version}}
329
+ do: Check tags and npm, bump the version, tag, wait for Publish.
330
+ anchor: '`test "$(npm view {{pkg}} version)" = {{version}}`'
331
+ - id: install
332
+ after: [release]
333
+ subject: Install when no train runs
334
+ run: "{{root}}/scripts/install-when-idle.sh"
335
+ monitor: true
336
+ waits: no train in progress
337
+ anchor: '`grep -qF "npm:{{pkg}}@{{version}}" ~/.pi/agent/settings.json`'
338
+ - id: prod
339
+ after: [install]
340
+ subject: Deploy {{pkg}} to production
341
+ approve: Deploy {{pkg}} {{version}} to production?
342
+ ```
343
+
344
+ | Field | Meaning |
345
+ | --- | --- |
346
+ | `flow`, `rev`, `summary` | Required. The template's name, revision, and one line about it. |
347
+ | `auth` | `required`: the call must quote the user's words that authorize the run. `none` or absent: it may. |
348
+ | `key` | Required. Identifies one run of the flow; it may hold placeholders. |
349
+ | `params.<name>` | `doc` (optional), `pattern` (optional, default `[A-Za-z0-9._@/+-]+`), `default` (optional; a param without one is required). A value must match the whole pattern: the tool wraps it in `^(?:…)$`. A default must be a quoted string that matches it; YAML would read `0.10` as the number 0.1. |
350
+ | `steps[].id`, `after` | Required id (letters, digits, `_`, `-`), and the ids of the steps it follows. |
351
+ | `steps[].subject` | Required. The todo's subject. |
352
+ | `steps[].do` | How to do the step; the first line of the todo's `description`. |
353
+ | `steps[].anchor` | Required except on an `approve` step: the check that shows the step is done. Keep side effects out of it, since a check is run again; put them in `run`. |
354
+ | `steps[].run`, `monitor` | A command to run, and `monitor: true` to run it under MonitorCreate; written into the `description`. |
355
+ | `steps[].waits` | What the step waits on once it runs; written into the `description`. The agent sets `waitsOn` when the wait starts, so a step not yet reached is not shown as held up. |
356
+ | `steps[].approve` | A question for the user. The subject gets the prefix `Needs approval: `, the anchor becomes `The user approves, quoted: <question>`, and the description asks the agent to stop until the user answers. An approve step takes no `anchor`. |
357
+
358
+ `{{name}}` in `key`, `subject`, `do`, `anchor`, `run`, `waits`, and `approve` is replaced by the param's value. Spaces inside the braces are allowed. Text such as `{{.State}}`, whose name does not start with a letter or `_`, is no placeholder and is left as written.
359
+ Any other field is unknown and refused.
360
+
361
+ ### The `flow` tool
362
+
363
+ ```ts
364
+ flow({ name?: string, params?: Record<string, string>, auth?: string, dryRun?: boolean })
365
+ ```
366
+
367
+ Without `name`, it lists the templates in reach with their params, steps, and files, then the files that are no valid template; `params`, `auth`, or `dryRun` without `name` is refused.
368
+ With `name`, it checks everything below before it writes anything. Any problem refuses the whole call with an error result (`isError: true`, text `Error: <reason>`; a template's reason lists all its problems):
369
+
370
+ - the template: an unknown name, a name in two files, a `flow` that differs from the file name, an unknown field, a placeholder naming no declared param, a duplicate step id, an `after` naming no step, a cycle, a step without an anchor, a malformed value;
371
+ - the call: an undeclared param, a required param left out, a value that does not match its pattern, a `key` that renders blank, `auth: required` without `auth`;
372
+ - the list: an open (`pending` or `in_progress`) todo whose `metadata.flow` has the same `name` and `key`. Once those todos are completed or deleted, the same key can be expanded again.
373
+
374
+ With `dryRun: true` it returns the todos it would append, with the ids they would get, and writes nothing. Their uids are drawn again on the real write.
375
+
376
+ Otherwise it appends the steps after the existing tasks, in an order where each step follows the steps it names in `after`, else as written:
377
+
378
+ - ids run from the list's `nextId`, each `after` becomes `blockedBy` with those ids, and each todo gets a fresh uid;
379
+ - each todo is `pending` with its `subject`, `anchor`, and a `description` made of `do`, the approval request, `run`, and `waits`;
380
+ - `metadata.flow` records where it came from (below).
381
+
382
+ The write is the guarded import write of the `todo` tool (§1, §3, §4), and the session's calls run one at a time as in §4.
383
+ Namespace validators see each appended task as a `create`, and the existing tasks are not judged again.
384
+ Guards see one `op: "create"` with `params` `{ action: "import", flow, rev, key, params, auth? }`, `params.params` holding every value with the defaults filled in; a guard that has not opted in to imports refuses it.
385
+ On success one `todo/v1` entry is written and `todo:changed` fires once.
386
+
387
+ ### `metadata.flow`
388
+
389
+ | Key | Type | Meaning |
390
+ | --- | --- | --- |
391
+ | `name` | non-empty string | The template's `flow`. |
392
+ | `rev` | integer ≥ 1 | Its `rev` when it was expanded. |
393
+ | `step` | non-empty string | The step's `id`. |
394
+ | `key` | non-empty string | The rendered `key` of the run. |
395
+ | `auth` | non-empty string, optional | The words the call quoted in `auth`. |
396
+
397
+ The ledger owns this namespace: it checks the shape on every create, update, and delete that carries the key, refuses any other property, and ignores a `todo:namespace` registration of `flow`.
398
+ `metadata: { flow: null }` removes it, and the todo then no longer counts toward its run's key.
399
+ It records provenance, not progress: the todo's `status`, `evidence`, and wait marks say how the run is going.
400
+
258
401
  ## Coexistence
259
402
 
260
- This package registers the tool name `todo`, as rpiv-todo does.
403
+ This package registers the tool name `todo`, as rpiv-todo does, and since 0.11.0 the tool name `flow`.
261
404
  Install one of the two: with both installed, the tool names clash.
package/README.md CHANGED
@@ -46,6 +46,7 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
46
46
  Pass that value as a Herdr `subagent`'s `item` (or use `<session8>#<id>` from the same session).
47
47
  Once the launch is acknowledged, the ledger sets `owner` to the child's full name and records its run id in [`metadata.herdr`](CONTRACT.md#optional-herdr-launch-identity-metadataherdr).
48
48
  Use `metadata.herdr.id` to resolve or message the worker by its run key.
49
+ When a bound run ends, the ledger adds its tokens, cost, wall time, and models to [`metadata.herdr.spend`](CONTRACT.md#run-spend-metadataherdrspend), summed over the todo's runs; `get` shows them. The figures are an estimate from the child's transcript, not a bill.
49
50
  Use a name with `/boss send` only if it matches the name Straw Boss shows; a launch named `API worker` may appear there as `api-worker`.
50
51
  You can still set `owner` by hand.
51
52
 
@@ -92,6 +93,19 @@ A snapshot file works too: save the `data` from a `todo/v1` entry as JSON and im
92
93
  A relative path starts in the new session's working directory.
93
94
  Import keeps the task ids, dependencies, evidence, tombstones, and next id; it never merges with or replaces an existing list.
94
95
 
96
+ ### Flow templates
97
+
98
+ A fixed procedure, such as a release followed by a pin and an install, can be written once as a YAML template and expanded into chained todos with one `flow` call.
99
+ Put templates in `~/.pi/agent/flows/<name>.yaml`, or in `<repo>/.pi/flows/<name>.yaml` for one project (read only when pi trusts the project); the file name is the flow's name.
100
+
101
+ ```text
102
+ flow({}) // list the templates and their params
103
+ flow({ name: "release-pin-install", params: { pkg: "pi-todo-ledger", version: "0.11.0", panes: "w1:p1" }, auth: "<the user's words>", dryRun: true })
104
+ ```
105
+
106
+ The tool checks the template, the params, and the list before it writes anything, then appends every step as a pending todo in one write: ids continue the list, each step's `after` becomes `blockedBy`, and each todo keeps its anchor.
107
+ After that the todos are the only record of the run. The format and the checks are in [CONTRACT.md](CONTRACT.md#5-flow-templates).
108
+
95
109
  ## Reading the list from another extension
96
110
 
97
111
  Listen for the event, or read the newest snapshot on the branch:
@@ -4,6 +4,9 @@ Complete parameter schema, status machine, response envelope, and error strings
4
4
  for the `todo` tool registered by pi-todo-ledger. The actions and parameters are
5
5
  rpiv-todo's, plus snapshot import and the bookkeeping fields `points`, `anchor`, and `evidence`.
6
6
 
7
+ The `flow` tool, which appends the todos of a flow template, is described in
8
+ [CONTRACT.md](../CONTRACT.md#5-flow-templates).
9
+
7
10
  ## Actions
8
11
 
9
12
  | Action | Required params | What it does |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,5 +57,8 @@
57
57
  "@types/node": "26.6.6",
58
58
  "typebox": "1.4.7",
59
59
  "typescript": "7.0.2"
60
+ },
61
+ "dependencies": {
62
+ "yaml": "2.9.1"
60
63
  }
61
64
  }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Where flow templates live and which are in reach of a session: `<agent dir>/flows/*.yaml` (user level) and
3
+ * `<repository root>/.pi/flows/*.yaml` (project level, only when pi says it trusts the project). `<name>.yaml` defines flow `<name>`.
4
+ * Files are read on every call, so an edited
5
+ * template applies to the next expansion and never to todos already in a list.
6
+ */
7
+
8
+ import { existsSync } from "node:fs";
9
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
10
+ import { basename, dirname, join, resolve } from "node:path";
11
+ import { type BrokenTemplate, type FlowTemplate, parseTemplate } from "./template.ts";
12
+
13
+ export type FlowLevel = "user" | "project";
14
+
15
+ export interface FlowDir {
16
+ level: FlowLevel;
17
+ dir: string;
18
+ /** Why the directory is not read: a project pi does not trust. */
19
+ skipped?: string;
20
+ }
21
+
22
+ export interface FlowCatalog {
23
+ dirs: FlowDir[];
24
+ /** Valid templates by name; a name with more than one file is refused by `find`. */
25
+ templates: Map<string, FlowTemplate[]>;
26
+ broken: BrokenTemplate[];
27
+ }
28
+
29
+ /** The nearest directory from `cwd` up that holds `.git`, else `cwd` itself. */
30
+ export function repositoryRoot(cwd: string): string {
31
+ const start = resolve(cwd);
32
+ for (let dir = start; ; dir = dirname(dir)) {
33
+ if (existsSync(join(dir, ".git"))) return dir;
34
+ if (dirname(dir) === dir) return start;
35
+ }
36
+ }
37
+
38
+ async function agentDir(): Promise<string> {
39
+ const { getAgentDir } = await import("@earendil-works/pi-coding-agent");
40
+ return getAgentDir();
41
+ }
42
+
43
+ /** The template directories of a session, user level first. */
44
+ export async function flowDirs(cwd: string, projectTrusted: boolean): Promise<FlowDir[]> {
45
+ const project = join(repositoryRoot(cwd), ".pi", "flows");
46
+ return [
47
+ { level: "user", dir: join(await agentDir(), "flows") },
48
+ { level: "project", dir: project, ...(projectTrusted ? {} : { skipped: "pi does not trust this project" }) },
49
+ ];
50
+ }
51
+
52
+ /** `*.yaml` files of `dir` (links followed), sorted; a missing directory has none. */
53
+ async function yamlFiles(dir: string): Promise<string[]> {
54
+ let names: string[];
55
+ try {
56
+ names = await readdir(dir);
57
+ } catch {
58
+ return [];
59
+ }
60
+ const files: string[] = [];
61
+ for (const name of names.filter((n) => n.endsWith(".yaml")).sort()) {
62
+ const path = join(dir, name);
63
+ try {
64
+ if ((await stat(path)).isFile()) files.push(path);
65
+ } catch {
66
+ // A dangling link is no template.
67
+ }
68
+ }
69
+ return files;
70
+ }
71
+
72
+ export async function loadCatalog(dirs: FlowDir[]): Promise<FlowCatalog> {
73
+ const templates = new Map<string, FlowTemplate[]>();
74
+ const broken: BrokenTemplate[] = [];
75
+ // One file linked into both levels (or reached by two links) is one template, not a duplicate.
76
+ const seen = new Set<string>();
77
+ for (const { dir, skipped } of dirs) {
78
+ if (skipped) continue;
79
+ for (const file of await yamlFiles(dir)) {
80
+ const real = await realpath(file).catch(() => file);
81
+ if (seen.has(real)) continue;
82
+ seen.add(real);
83
+ let text: string;
84
+ try {
85
+ text = await readFile(file, "utf8");
86
+ } catch (error) {
87
+ broken.push({ file, errors: [`cannot read: ${(error as Error).message}`] });
88
+ continue;
89
+ }
90
+ // The file name names the flow, so a broken file blocks only its own name.
91
+ const name = basename(file, ".yaml");
92
+ const parsed = parseTemplate(text, file);
93
+ if (!parsed.ok) broken.push({ ...parsed.broken, flow: name });
94
+ else if (parsed.template.flow !== name) {
95
+ broken.push({ file, flow: name, errors: [`flow ${parsed.template.flow} does not match the file name; name the file ${parsed.template.flow}.yaml or the flow ${name}`] });
96
+ } else templates.set(name, [...(templates.get(name) ?? []), parsed.template]);
97
+ }
98
+ }
99
+ return { dirs, templates, broken };
100
+ }
101
+
102
+ /** The one valid template named `name`, or why the call cannot use it. */
103
+ export function findTemplate(catalog: FlowCatalog, name: string): { template: FlowTemplate } | { error: string } {
104
+ const valid = catalog.templates.get(name) ?? [];
105
+ const invalid = catalog.broken.filter((b) => b.flow === name);
106
+ const files = [...valid.map((t) => t.file), ...invalid.map((b) => b.file)];
107
+ if (files.length > 1) return { error: `flow ${name} is defined in more than one file; keep one:\n${files.map((f) => ` ${f}`).join("\n")}` };
108
+ if (invalid.length) return { error: `flow ${name} in ${invalid[0]!.file} is not a valid template:\n${invalid[0]!.errors.map((e) => ` - ${e}`).join("\n")}` };
109
+ if (valid.length === 1) return { template: valid[0]! };
110
+ const known = [...catalog.templates.keys()].sort();
111
+ const skipped = catalog.dirs.filter((d) => d.skipped).map((d) => ` (${d.dir} not read: ${d.skipped})`);
112
+ return { error: `unknown flow ${name}; known: ${known.length ? known.join(", ") : "none"}${skipped.join("")}` };
113
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Expansion: a checked template and a call's params and authorization become the todos to append, or the one reason the call is
3
+ * refused. Pure: it reads the list only to refuse a second open expansion of the same run, and writes nothing.
4
+ */
5
+
6
+ import type { AppendItem } from "../ledger/import-snapshot.ts";
7
+ import type { Task } from "../tool/types.ts";
8
+ import { FLOW_NAMESPACE, type FlowMetadata, flowOf } from "./metadata.ts";
9
+ import { type FlowStep, type FlowTemplate, render } from "./template.ts";
10
+
11
+ export const APPROVAL_PREFIX = "Needs approval: ";
12
+
13
+ export interface FlowInput {
14
+ params?: unknown;
15
+ auth?: unknown;
16
+ }
17
+
18
+ export interface Expansion {
19
+ key: string;
20
+ /** Every param's value, defaults filled in, in declaration order. */
21
+ values: Map<string, string>;
22
+ items: AppendItem[];
23
+ }
24
+
25
+ function isRecord(value: unknown): value is Record<string, unknown> {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+
29
+ const nonblank = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
30
+
31
+ const isOpen = (task: Task) => task.status === "pending" || task.status === "in_progress";
32
+
33
+ function paramValues(template: FlowTemplate, given: unknown): Map<string, string> | string {
34
+ if (given !== undefined && !isRecord(given)) return "params must be an object of name to string value";
35
+ const input = given ?? {};
36
+ const declared = [...template.params.keys()];
37
+ const undeclared = Object.keys(input).filter((name) => !template.params.has(name));
38
+ if (undeclared.length) {
39
+ return `flow ${template.flow} declares no param ${undeclared.join(", ")} (declared: ${declared.length ? declared.join(", ") : "none"})`;
40
+ }
41
+ const values = new Map<string, string>();
42
+ const missing: string[] = [];
43
+ for (const [name, param] of template.params) {
44
+ const value = input[name];
45
+ if (value === undefined) {
46
+ if (param.default === undefined) missing.push(name);
47
+ else values.set(name, param.default);
48
+ continue;
49
+ }
50
+ if (typeof value !== "string") return `param ${name} must be a string`;
51
+ if (!param.matcher.test(value)) return `param ${name} ${JSON.stringify(value)} does not match ${param.pattern}`;
52
+ values.set(name, value);
53
+ }
54
+ if (missing.length) return `flow ${template.flow} needs param ${missing.join(", ")}`;
55
+ return values;
56
+ }
57
+
58
+ function description(step: FlowStep, values: ReadonlyMap<string, string>): string | undefined {
59
+ const lines: string[] = [];
60
+ if (step.do) lines.push(render(step.do, values));
61
+ if (step.approve) {
62
+ lines.push(`Approval: ask the user "${render(step.approve, values)}" and stop until they answer; quote their words in this todo's evidence.`);
63
+ }
64
+ if (step.run) lines.push(`${step.monitor ? "Run under MonitorCreate" : "Run"}: ${render(step.run, values)}`);
65
+ if (step.waits) lines.push(`Waits on: ${render(step.waits, values)} (set waitsOn when the wait starts)`);
66
+ return lines.length ? lines.join("\n") : undefined;
67
+ }
68
+
69
+ /** The todos `template` expands into for this call, or why it is refused. */
70
+ export function expandTemplate(template: FlowTemplate, input: FlowInput, tasks: readonly Task[]): { expansion: Expansion } | { error: string } {
71
+ const values = paramValues(template, input.params);
72
+ if (typeof values === "string") return { error: values };
73
+ if (input.auth !== undefined && typeof input.auth !== "string") return { error: "auth must be a string" };
74
+ const auth = nonblank(input.auth) ? input.auth : undefined;
75
+ if (template.auth === "required" && !auth) {
76
+ return { error: `flow ${template.flow} needs auth: quote the user's own words that authorize this run` };
77
+ }
78
+ const key = render(template.key, values);
79
+ if (!key.trim()) return { error: `flow ${template.flow} key ${JSON.stringify(template.key)} renders blank with these params; give values that name the run` };
80
+ const open = tasks.filter((t) => {
81
+ const flow = flowOf(t);
82
+ return isOpen(t) && flow?.name === template.flow && flow.key === key;
83
+ });
84
+ if (open.length) {
85
+ return {
86
+ error: `flow ${template.flow} key ${key} already has open todos ${open.map((t) => `#${t.id}`).join(", ")}; finish or delete them before expanding it again`,
87
+ };
88
+ }
89
+ const position = new Map(template.steps.map((step, i) => [step.id, i + 1]));
90
+ const items = template.steps.map((step): AppendItem => {
91
+ const flow: FlowMetadata = { name: template.flow, rev: template.rev, step: step.id, key, ...(auth ? { auth } : {}) };
92
+ const text = description(step, values);
93
+ const subject = render(step.subject, values);
94
+ return {
95
+ subject: step.approve ? `${APPROVAL_PREFIX}${subject}` : subject,
96
+ ...(text ? { description: text } : {}),
97
+ anchor: step.approve ? `The user approves, quoted: ${render(step.approve, values)}` : render(step.anchor!, values),
98
+ blockedBy: step.after.map((id) => position.get(id)!),
99
+ metadata: { [FLOW_NAMESPACE]: flow },
100
+ };
101
+ });
102
+ return { expansion: { key, values, items } };
103
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `metadata.flow`: which template, revision, step, and run (`key`) a todo was expanded from, and the authorization quoted when it
3
+ * was. The ledger owns this namespace and checks its shape on every change; it records provenance, never progress.
4
+ */
5
+
6
+ import type { NamespaceValidator } from "../ledger/contract.ts";
7
+ import type { Task } from "../tool/types.ts";
8
+
9
+ export const FLOW_NAMESPACE = "flow";
10
+
11
+ export interface FlowMetadata {
12
+ name: string;
13
+ rev: number;
14
+ step: string;
15
+ key: string;
16
+ /** The user's words that authorized the expansion; present when the call quoted them. */
17
+ auth?: string;
18
+ }
19
+
20
+ const FIELDS = ["name", "rev", "step", "key", "auth"];
21
+
22
+ function isRecord(value: unknown): value is Record<string, unknown> {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+
26
+ const nonblank = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
27
+
28
+ /** Why `value` is no `metadata.flow`, or `undefined` when it is one. */
29
+ export function flowMetadataError(value: unknown): string | undefined {
30
+ if (!isRecord(value)) return "must be an object { name, rev, step, key, auth? }";
31
+ const extra = Object.keys(value).filter((k) => !FIELDS.includes(k));
32
+ if (extra.length) return `unknown field ${extra.map((k) => `"${k}"`).join(", ")} (known: ${FIELDS.join(", ")})`;
33
+ if (!nonblank(value.name)) return "name must be a non-empty string";
34
+ if (!Number.isSafeInteger(value.rev) || (value.rev as number) < 1) return "rev must be a whole number from 1";
35
+ if (!nonblank(value.step)) return "step must be a non-empty string";
36
+ if (!nonblank(value.key)) return "key must be a non-empty string";
37
+ if (value.auth !== undefined && !nonblank(value.auth)) return "auth must be a non-empty string when present";
38
+ return undefined;
39
+ }
40
+
41
+ /** Accepts a valid value, and the removal of the key (`metadata: { flow: null }`). */
42
+ export const validateFlowMetadata: NamespaceValidator = (value) => (value === undefined ? undefined : flowMetadataError(value));
43
+
44
+ export function flowOf(task: Task): FlowMetadata | undefined {
45
+ const value = task.metadata?.[FLOW_NAMESPACE];
46
+ return flowMetadataError(value) === undefined ? (value as FlowMetadata) : undefined;
47
+ }