pi-todo-ledger 0.10.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:
@@ -257,6 +259,7 @@ Guard registration accepts an optional `imports: true` field within v1.
257
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.
258
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`.
259
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`.
260
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.
261
264
  `change` matches `$defs/change` in the schema and is a copy:
262
265
 
@@ -291,7 +294,111 @@ The same holds along a chain of guards: when session A's guard calls `todo` for
291
294
  Calling `todo` for a session whose guard is not running further up the chain is allowed.
292
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.
293
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
+
294
401
  ## Coexistence
295
402
 
296
- 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`.
297
404
  Install one of the two: with both installed, the tool names clash.
package/README.md CHANGED
@@ -93,6 +93,19 @@ A snapshot file works too: save the `data` from a `todo/v1` entry as JSON and im
93
93
  A relative path starts in the new session's working directory.
94
94
  Import keeps the task ids, dependencies, evidence, tombstones, and next id; it never merges with or replaces an existing list.
95
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
+
96
109
  ## Reading the list from another extension
97
110
 
98
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.10.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
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Flow templates: a YAML file that describes a fixed sequence of todos, each with its anchor, which the `flow` tool expands into
3
+ * the list in one write (CONTRACT.md, "Flow templates"). This module reads one file into a checked template, or into the reasons it
4
+ * cannot; it touches no list. A template only describes a shape: once expanded, the todos are the record and the file is not read again.
5
+ */
6
+
7
+ import { parseDocument } from "yaml";
8
+
9
+ /** What a value matches when its param names no `pattern`: letters, digits, and `._@/+-`. */
10
+ export const DEFAULT_PARAM_PATTERN = "[A-Za-z0-9._@/+-]+";
11
+
12
+ const FLOW_NAME = /^[a-z0-9][a-z0-9-]*$/;
13
+ const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
+ const STEP_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
15
+ /** `{{name}}`, spaces allowed inside the braces. Text such as `{{.State}}` is no placeholder and stays as written. */
16
+ const PLACEHOLDER = /\{\{\s*([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/g;
17
+
18
+ const TOP_FIELDS = ["flow", "rev", "summary", "auth", "key", "params", "steps"] as const;
19
+ const PARAM_FIELDS = ["doc", "pattern", "default"] as const;
20
+ const STEP_FIELDS = ["id", "after", "subject", "do", "anchor", "run", "monitor", "waits", "approve"] as const;
21
+ /** Step fields that may hold placeholders, with the template's `key`. */
22
+ const RENDERED_STEP_FIELDS = ["subject", "do", "anchor", "run", "waits", "approve"] as const;
23
+
24
+ export type FlowAuth = "required" | "none";
25
+
26
+ export interface FlowParam {
27
+ doc?: string;
28
+ /** The pattern as written, or the default one. */
29
+ pattern: string;
30
+ /** Matches a whole value: the pattern is wrapped in `^(?:…)$`. */
31
+ matcher: RegExp;
32
+ /** A param without a default is required. */
33
+ default?: string;
34
+ }
35
+
36
+ export interface FlowStep {
37
+ id: string;
38
+ after: string[];
39
+ subject: string;
40
+ do?: string;
41
+ /** Absent only on an `approve` step, whose anchor is the approval. */
42
+ anchor?: string;
43
+ run?: string;
44
+ monitor: boolean;
45
+ waits?: string;
46
+ approve?: string;
47
+ }
48
+
49
+ export interface FlowTemplate {
50
+ flow: string;
51
+ rev: number;
52
+ summary: string;
53
+ auth: FlowAuth;
54
+ key: string;
55
+ params: Map<string, FlowParam>;
56
+ /** In an order where every step comes after the steps it names in `after`, else as written. */
57
+ steps: FlowStep[];
58
+ file: string;
59
+ }
60
+
61
+ /** A file that is not a valid template; `flow` is the name it was read for, its file name in a catalog. */
62
+ export interface BrokenTemplate {
63
+ file: string;
64
+ flow?: string;
65
+ errors: string[];
66
+ }
67
+
68
+ export type ParsedTemplate = { ok: true; template: FlowTemplate } | { ok: false; broken: BrokenTemplate };
69
+
70
+ function isRecord(value: unknown): value is Record<string, unknown> {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value);
72
+ }
73
+
74
+ const nonblank = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
75
+
76
+ /** The placeholder names in `text`, in order of first use. */
77
+ export function placeholders(text: string): string[] {
78
+ return [...new Set(Array.from(text.matchAll(PLACEHOLDER), (m) => m[1]!))];
79
+ }
80
+
81
+ /** `text` with every placeholder replaced by its value; the caller has checked that each is declared. */
82
+ export function render(text: string, values: ReadonlyMap<string, string>): string {
83
+ return text.replace(PLACEHOLDER, (_whole, name: string) => values.get(name) ?? "");
84
+ }
85
+
86
+ function unknownFields(where: string, value: Record<string, unknown>, known: readonly string[]): string[] {
87
+ return Object.keys(value)
88
+ .filter((k) => !known.includes(k))
89
+ .map((k) => `${where}: unknown field "${k}" (known: ${known.join(", ")})`);
90
+ }
91
+
92
+ function parseParams(raw: unknown, errors: string[]): Map<string, FlowParam> {
93
+ const params = new Map<string, FlowParam>();
94
+ if (raw === undefined) return params;
95
+ if (!isRecord(raw)) {
96
+ errors.push("params must be a mapping of name to { doc, pattern, default }");
97
+ return params;
98
+ }
99
+ for (const [name, spec] of Object.entries(raw)) {
100
+ const where = `params.${name}`;
101
+ if (!PARAM_NAME.test(name)) errors.push(`${where}: a param name is letters, digits and _, not starting with a digit`);
102
+ if (!isRecord(spec)) {
103
+ errors.push(`${where} must be a mapping with doc, pattern, and default`);
104
+ continue;
105
+ }
106
+ errors.push(...unknownFields(where, spec, PARAM_FIELDS));
107
+ if (spec.doc !== undefined && typeof spec.doc !== "string") errors.push(`${where}.doc must be a string`);
108
+ if (spec.pattern !== undefined && !nonblank(spec.pattern)) errors.push(`${where}.pattern must be a non-empty string`);
109
+ const pattern = typeof spec.pattern === "string" && spec.pattern.trim() ? spec.pattern : DEFAULT_PARAM_PATTERN;
110
+ let matcher: RegExp;
111
+ try {
112
+ matcher = new RegExp(`^(?:${pattern})$`, "u");
113
+ } catch (error) {
114
+ errors.push(`${where}.pattern is not a valid regular expression: ${(error as Error).message}`);
115
+ continue;
116
+ }
117
+ // YAML reads `0.10` as the number 0.1 and `yes` as a string; a default is taken only as a quoted string.
118
+ if (spec.default !== undefined && typeof spec.default !== "string") {
119
+ errors.push(`${where}.default must be a string; quote it (YAML read ${JSON.stringify(spec.default)})`);
120
+ continue;
121
+ }
122
+ if (typeof spec.default === "string" && !matcher.test(spec.default)) {
123
+ errors.push(`${where}.default ${JSON.stringify(spec.default)} does not match its pattern ${pattern}`);
124
+ }
125
+ params.set(name, {
126
+ ...(typeof spec.doc === "string" ? { doc: spec.doc } : {}),
127
+ pattern,
128
+ matcher,
129
+ ...(typeof spec.default === "string" ? { default: spec.default } : {}),
130
+ });
131
+ }
132
+ return params;
133
+ }
134
+
135
+ function parseStep(raw: unknown, index: number, errors: string[]): FlowStep | undefined {
136
+ const where = `steps[${index}]`;
137
+ if (!isRecord(raw)) {
138
+ errors.push(`${where} must be a mapping`);
139
+ return undefined;
140
+ }
141
+ const at = nonblank(raw.id) ? `step ${raw.id}` : where;
142
+ const before = errors.length;
143
+ errors.push(...unknownFields(at, raw, STEP_FIELDS));
144
+ if (!nonblank(raw.id) || !STEP_ID.test(raw.id)) errors.push(`${at}: id must be letters, digits, _ and -, starting with a letter or digit`);
145
+ if (!nonblank(raw.subject)) errors.push(`${at}: subject must be a non-empty string`);
146
+ for (const field of ["do", "anchor", "run", "waits", "approve"] as const) {
147
+ if (raw[field] !== undefined && !nonblank(raw[field])) errors.push(`${at}: ${field} must be a non-empty string`);
148
+ }
149
+ const after = raw.after ?? [];
150
+ if (!Array.isArray(after) || !after.every(nonblank)) errors.push(`${at}: after must be a list of step ids`);
151
+ if (raw.monitor !== undefined && typeof raw.monitor !== "boolean") errors.push(`${at}: monitor must be true or false`);
152
+ if (raw.monitor === true && raw.run === undefined) errors.push(`${at}: monitor needs run, the command to watch`);
153
+ if (raw.approve !== undefined && raw.anchor !== undefined) {
154
+ errors.push(`${at}: an approve step takes no anchor; the user's approval is its anchor`);
155
+ }
156
+ if (raw.approve === undefined && raw.anchor === undefined) errors.push(`${at}: anchor is required (how this step counts as done)`);
157
+ if (errors.length > before) return undefined;
158
+ return {
159
+ id: raw.id as string,
160
+ after: [...(after as string[])],
161
+ subject: raw.subject as string,
162
+ ...(raw.do !== undefined ? { do: raw.do as string } : {}),
163
+ ...(raw.anchor !== undefined ? { anchor: raw.anchor as string } : {}),
164
+ ...(raw.run !== undefined ? { run: raw.run as string } : {}),
165
+ monitor: raw.monitor === true,
166
+ ...(raw.waits !== undefined ? { waits: raw.waits as string } : {}),
167
+ ...(raw.approve !== undefined ? { approve: raw.approve as string } : {}),
168
+ };
169
+ }
170
+
171
+ /**
172
+ * The steps in dependency order, stable by position: a step comes right after the last step it waits on, unless an earlier-written
173
+ * step is also ready. Reports a duplicate id, an `after` naming no step or the step itself, and a cycle.
174
+ */
175
+ function orderSteps(steps: FlowStep[], errors: string[]): FlowStep[] {
176
+ const byId = new Map<string, FlowStep>();
177
+ for (const step of steps) {
178
+ if (byId.has(step.id)) errors.push(`step ${step.id}: duplicate step id`);
179
+ byId.set(step.id, step);
180
+ }
181
+ for (const step of steps) {
182
+ for (const dep of step.after) {
183
+ if (dep === step.id) errors.push(`step ${step.id}: after names the step itself`);
184
+ else if (!byId.has(dep)) errors.push(`step ${step.id}: after names ${dep}, which is no step of this flow`);
185
+ }
186
+ }
187
+ if (errors.length) return steps;
188
+ const placed = new Set<string>();
189
+ const ordered: FlowStep[] = [];
190
+ while (ordered.length < steps.length) {
191
+ const next = steps.find((s) => !placed.has(s.id) && s.after.every((dep) => placed.has(dep)));
192
+ if (!next) {
193
+ const stuck = steps.filter((s) => !placed.has(s.id)).map((s) => s.id);
194
+ errors.push(`steps ${stuck.join(", ")} wait on each other in a cycle`);
195
+ return steps;
196
+ }
197
+ placed.add(next.id);
198
+ ordered.push(next);
199
+ }
200
+ return ordered;
201
+ }
202
+
203
+ /** Read one template file's text. Every problem in it is reported, not only the first. */
204
+ export function parseTemplate(text: string, file: string): ParsedTemplate {
205
+ const doc = parseDocument(text, { uniqueKeys: true, prettyErrors: false, merge: false, schema: "core", strict: true });
206
+ if (doc.errors.length) return { ok: false, broken: { file, errors: doc.errors.map((e) => `YAML: ${e.message}`) } };
207
+ let raw: unknown;
208
+ try {
209
+ raw = doc.toJS({ maxAliasCount: 50 });
210
+ } catch (error) {
211
+ return { ok: false, broken: { file, errors: [`YAML: ${(error as Error).message}`] } };
212
+ }
213
+ if (!isRecord(raw)) return { ok: false, broken: { file, errors: ["a template is a YAML mapping with flow, rev, summary, key, params, steps"] } };
214
+ const errors: string[] = unknownFields("template", raw, TOP_FIELDS);
215
+ const name = nonblank(raw.flow) ? raw.flow : undefined;
216
+ if (!name || !FLOW_NAME.test(name)) errors.push("flow must be a name of lowercase letters, digits and -");
217
+ if (!Number.isSafeInteger(raw.rev) || (raw.rev as number) < 1) errors.push("rev must be a whole number from 1");
218
+ if (!nonblank(raw.summary)) errors.push("summary must be a non-empty string");
219
+ if (raw.auth !== undefined && raw.auth !== "required" && raw.auth !== "none") errors.push('auth must be "required" or "none"');
220
+ if (!nonblank(raw.key)) errors.push("key must be a non-empty string naming one run of the flow, such as \"{{pkg}}@{{version}}\"");
221
+ const params = parseParams(raw.params, errors);
222
+ let steps: FlowStep[] = [];
223
+ if (!Array.isArray(raw.steps) || raw.steps.length === 0) errors.push("steps must be a non-empty list");
224
+ else {
225
+ const parsed = raw.steps.map((step, i) => parseStep(step, i, errors));
226
+ if (parsed.every((s): s is FlowStep => s !== undefined)) steps = orderSteps(parsed, errors);
227
+ }
228
+ const undeclared = (where: string, value: string | undefined) => {
229
+ for (const p of placeholders(value ?? "")) {
230
+ if (!params.has(p)) errors.push(`${where}: placeholder {{${p}}} names no declared param`);
231
+ }
232
+ };
233
+ if (typeof raw.key === "string") undeclared("key", raw.key);
234
+ for (const step of steps) for (const field of RENDERED_STEP_FIELDS) undeclared(`step ${step.id}.${field}`, step[field]);
235
+ if (errors.length) return { ok: false, broken: { file, ...(name ? { flow: name } : {}), errors } };
236
+ return {
237
+ ok: true,
238
+ template: {
239
+ flow: name!,
240
+ rev: raw.rev as number,
241
+ summary: raw.summary as string,
242
+ auth: raw.auth === "required" ? "required" : "none",
243
+ key: raw.key as string,
244
+ params,
245
+ steps,
246
+ file,
247
+ },
248
+ };
249
+ }
250
+
251
+ export { RENDERED_STEP_FIELDS };
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The `flow` tool: list the flow templates in reach, or expand one into chained todos appended to the session's list in one guarded
3
+ * write (CONTRACT.md, "Flow templates"). Every check runs before anything is written; a refusal leaves the list as it was.
4
+ */
5
+
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import { type Static, Type } from "typebox";
8
+ import { ABORTED, type FinishCall } from "../ledger/finish-call.ts";
9
+ import { runningGuard } from "../ledger/guards.ts";
10
+ import { prepareAppend } from "../ledger/import-snapshot.ts";
11
+ import { withSessionLock } from "../state/session-lock.ts";
12
+ import { getState, sid } from "../state/store.ts";
13
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
14
+ import type { Task } from "../tool/types.ts";
15
+ import { type FlowCatalog, findTemplate, flowDirs, loadCatalog } from "./catalog.ts";
16
+ import { expandTemplate } from "./expand.ts";
17
+ import type { FlowTemplate } from "./template.ts";
18
+
19
+ export const FLOW_TOOL_NAME = "flow";
20
+
21
+ export const FlowParamsSchema = Type.Object({
22
+ name: Type.Optional(Type.String({ description: "Template to expand. Omit to list the templates and their params." })),
23
+ params: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Param values by name; params with a default may be left out." })),
24
+ auth: Type.Optional(Type.String({ description: "The user's own words authorizing this run, quoted. Required by templates with auth: required." })),
25
+ dryRun: Type.Optional(Type.Boolean({ description: "Return the todos the expansion would append, without writing them." })),
26
+ });
27
+
28
+ export type FlowParams = Static<typeof FlowParamsSchema>;
29
+
30
+ export const FLOW_DESCRIPTION =
31
+ "Expand a flow template (~/.pi/agent/flows/*.yaml or <repo>/.pi/flows/*.yaml) into chained todos appended to the list in one write, each with its anchor. Without name, lists the templates and their params. dryRun previews without writing.";
32
+
33
+ export const FLOW_PROMPT_GUIDELINES: string[] = [
34
+ "Use flow when a fixed multi-step procedure has a template: call it without arguments to see the templates, then with name, params and, when the template requires it, auth quoting the user's words. Preview with dryRun when unsure.",
35
+ "After expanding, work the todos like any other: start the first unblocked one, record evidence, complete it. A Needs approval step waits for the user's answer.",
36
+ ];
37
+
38
+ interface FlowResult {
39
+ content: Array<{ type: "text"; text: string }>;
40
+ details: object;
41
+ isError?: boolean;
42
+ }
43
+
44
+ const clean = (text: string) => sanitizeTerminalText(text);
45
+
46
+ function flowError(message: string): FlowResult {
47
+ return { content: [{ type: "text", text: `Error: ${message}` }], details: { error: message }, isError: true };
48
+ }
49
+
50
+ function describeTemplate(t: FlowTemplate) {
51
+ return {
52
+ name: t.flow,
53
+ rev: t.rev,
54
+ summary: t.summary,
55
+ auth: t.auth,
56
+ key: t.key,
57
+ file: t.file,
58
+ params: [...t.params].map(([name, p]) => ({
59
+ name,
60
+ ...(p.doc !== undefined ? { doc: p.doc } : {}),
61
+ pattern: p.pattern,
62
+ ...(p.default !== undefined ? { default: p.default } : {}),
63
+ required: p.default === undefined,
64
+ })),
65
+ steps: t.steps.map((s) => s.id),
66
+ };
67
+ }
68
+
69
+ function listResult(catalog: FlowCatalog): FlowResult {
70
+ const templates = [...catalog.templates.values()].flat().sort((a, b) => a.flow.localeCompare(b.flow) || a.file.localeCompare(b.file));
71
+ const lines = [`Flow templates in ${catalog.dirs.map((d) => `${d.level} ${d.dir}${d.skipped ? ` (not read: ${d.skipped})` : ""}`).join(", ")}:`];
72
+ if (!templates.length) lines.push(" none");
73
+ for (const t of templates) {
74
+ lines.push(`${clean(t.flow)} rev ${t.rev}${t.auth === "required" ? " (auth required)" : ""}: ${clean(t.summary)}`);
75
+ lines.push(` file: ${clean(t.file)}`);
76
+ lines.push(` key: ${clean(t.key)}`);
77
+ for (const [name, p] of t.params) {
78
+ const value = p.default === undefined ? "required" : `default ${JSON.stringify(p.default)}`;
79
+ lines.push(` param ${name}: ${value}, pattern ${clean(p.pattern)}${p.doc ? ` — ${clean(p.doc)}` : ""}`);
80
+ }
81
+ lines.push(` steps: ${t.steps.map((s) => clean(s.id)).join(" → ")}`);
82
+ }
83
+ if (catalog.broken.length) {
84
+ lines.push("Not valid templates:");
85
+ for (const b of catalog.broken) lines.push(` ${clean(b.file)}${b.flow ? ` (${clean(b.flow)})` : ""}: ${b.errors.map(clean).join("; ")}`);
86
+ }
87
+ return {
88
+ content: [{ type: "text", text: lines.join("\n") }],
89
+ details: { dirs: catalog.dirs, templates: templates.map(describeTemplate), broken: catalog.broken },
90
+ };
91
+ }
92
+
93
+ function range(ids: readonly number[]): string {
94
+ return ids.length === 1 ? `#${ids[0]}` : `#${ids[0]}–#${ids.at(-1)}`;
95
+ }
96
+
97
+ function previewLines(tasks: readonly Task[]): string[] {
98
+ const lines: string[] = [];
99
+ for (const t of tasks) {
100
+ lines.push(`#${t.id} ${clean(t.subject)}`);
101
+ if (t.blockedBy?.length) lines.push(` blockedBy: ${t.blockedBy.map((id) => `#${id}`).join(", ")}`);
102
+ if (t.anchor) lines.push(` anchor: ${clean(t.anchor)}`);
103
+ for (const line of t.description?.split("\n") ?? []) lines.push(` | ${clean(line)}`);
104
+ }
105
+ return lines;
106
+ }
107
+
108
+ export function registerFlowTool(pi: ExtensionAPI, finish: FinishCall): void {
109
+ pi.registerTool({
110
+ name: FLOW_TOOL_NAME,
111
+ label: "Flow",
112
+ description: FLOW_DESCRIPTION,
113
+ promptSnippet: "Expand a flow template into chained todos with anchors",
114
+ promptGuidelines: FLOW_PROMPT_GUIDELINES,
115
+ parameters: FlowParamsSchema,
116
+
117
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
118
+ const sessionId = sid(ctx);
119
+ const guardId = runningGuard(sessionId);
120
+ if (guardId !== undefined) return flowError(`flow called from inside guard ${guardId}`);
121
+ // Fail closed: a host that cannot say it trusts the project gets no project templates.
122
+ const trusted = typeof ctx.isProjectTrusted === "function" && ctx.isProjectTrusted() === true;
123
+ const catalog = await loadCatalog(await flowDirs(ctx.cwd, trusted));
124
+ if (params.name === undefined) {
125
+ if (params.params !== undefined || params.auth !== undefined || params.dryRun !== undefined) {
126
+ return flowError("params, auth and dryRun need a name; call flow without arguments to list the templates");
127
+ }
128
+ return listResult(catalog);
129
+ }
130
+ const found = findTemplate(catalog, params.name);
131
+ if ("error" in found) return flowError(found.error);
132
+ const template = found.template;
133
+ return withSessionLock(sessionId, async (): Promise<FlowResult> => {
134
+ if (signal?.aborted) return flowError(ABORTED);
135
+ const before = getState(sessionId);
136
+ const expanded = expandTemplate(template, params, before.tasks);
137
+ if ("error" in expanded) return flowError(expanded.error);
138
+ const { key, values, items } = expanded.expansion;
139
+ let prepared: ReturnType<typeof prepareAppend>;
140
+ try {
141
+ prepared = prepareAppend(before, items);
142
+ } catch (error) {
143
+ return flowError((error as Error).message);
144
+ }
145
+ const added = prepared.state.tasks.slice(before.tasks.length);
146
+ const head = `flow ${clean(template.flow)} rev ${template.rev}, key ${clean(key)}`;
147
+ if (params.dryRun) {
148
+ return {
149
+ content: [{ type: "text", text: [`Dry run, nothing written: ${head} would append ${range(prepared.taskIds)}`, ...previewLines(added)].join("\n") }],
150
+ details: { dryRun: true, flow: template.flow, rev: template.rev, key, tasks: added },
151
+ };
152
+ }
153
+ // Guards see an import: they opted in to judging tasks they did not see created one by one.
154
+ const input = {
155
+ action: "import",
156
+ flow: template.flow,
157
+ rev: template.rev,
158
+ key,
159
+ params: Object.fromEntries(values),
160
+ ...(typeof params.auth === "string" && params.auth.trim() ? { auth: params.auth } : {}),
161
+ };
162
+ const result: FlowResult = await finish(sessionId, ctx.cwd, "import", input, before, { state: prepared.state, op: { kind: "import", taskIds: prepared.taskIds } }, signal);
163
+ if (result.isError) return result;
164
+ return { ...result, content: [{ type: "text", text: `${head}: appended ${range(prepared.taskIds)}` }, ...result.content] };
165
+ });
166
+ },
167
+ });
168
+ }
package/src/index.ts CHANGED
@@ -34,6 +34,8 @@ import {
34
34
  READY_EVENT,
35
35
  toChangedEvent,
36
36
  } from "./ledger/contract.ts";
37
+ import { FLOW_NAMESPACE, validateFlowMetadata } from "./flow/metadata.ts";
38
+ import { FLOW_TOOL_NAME, registerFlowTool } from "./flow/tool.ts";
37
39
  import { makeCommitNow, makeFinishCall } from "./ledger/finish-call.ts";
38
40
  import { GuardRegistry } from "./ledger/guards.ts";
39
41
  import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
@@ -200,6 +202,7 @@ export default function (
200
202
  // Namespace and guard owners register on `todo:namespace` and `todo:guard`;
201
203
  // `todo:ready` asks the ones that loaded before this extension to register again.
202
204
  const namespaces = new NamespaceRegistry();
205
+ namespaces.own(FLOW_NAMESPACE, validateFlowMetadata);
203
206
  const guards = new GuardRegistry(options.guardTimeoutMs ?? GUARD_TIMEOUT_MS);
204
207
  pi.events.on(NAMESPACE_EVENT, (payload) => {
205
208
  const ignored = namespaces.register(payload);
@@ -212,6 +215,7 @@ export default function (
212
215
 
213
216
  const finish = makeFinishCall(pi, namespaces, guards);
214
217
  registerTodoTool(pi, finish);
218
+ registerFlowTool(pi, finish);
215
219
  registerHerdrOwner(pi, finish);
216
220
  registerHerdrSpend(pi, makeCommitNow(pi, namespaces));
217
221
  registerTodosCommand(pi);
@@ -381,7 +385,7 @@ export default function (
381
385
  // (branch is stale — message_end runs after tool_execution_end). A launch or
382
386
  // resume may start a run bound to no task, which the panel shows too.
383
387
  pi.on("tool_execution_end", async (event) => {
384
- if (event.isError || ![TOOL_NAME, "subagent", "subagent_resume"].includes(event.toolName)) return;
388
+ if (event.isError || ![TOOL_NAME, FLOW_TOOL_NAME, "subagent", "subagent_resume"].includes(event.toolName)) return;
385
389
  await refresh();
386
390
  });
387
391
 
@@ -1,7 +1,8 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import type { TaskState } from "../state/state.ts";
4
- import { withLegacyGraph } from "../state/state-reducer.ts";
4
+ import { newUid, withLegacyGraph } from "../state/state-reducer.ts";
5
+ import type { Task } from "../tool/types.ts";
5
6
  import { isSnapshotV1 } from "./schema.ts";
6
7
  import { readSessionSnapshot } from "./session-source.ts";
7
8
 
@@ -51,3 +52,50 @@ export async function readImport(before: TaskState, cwd: string, source: ImportS
51
52
  const tasks = snapshot.tasks.map(task => withLegacyGraph(origin ? { ...task, origin: { session: origin } } : task));
52
53
  return { tasks, nextId: snapshot.nextId };
53
54
  }
55
+
56
+ /** One task an append adds. `blockedBy` holds 1-based positions of earlier items in the same batch, not list ids, so a batch has no cycle. */
57
+ export interface AppendItem {
58
+ subject: string;
59
+ description?: string;
60
+ anchor?: string;
61
+ blockedBy?: number[];
62
+ metadata?: Record<string, unknown>;
63
+ }
64
+
65
+ /**
66
+ * The import path for a list that is not empty: `items` go after the existing tasks as pending tasks, numbered from `nextId`, their
67
+ * positions in `blockedBy` rewritten into those ids, each with a fresh uid. Prepares the state without writing it; the caller holds
68
+ * the session lock and commits it through the guarded import write, so the batch lands whole or not at all.
69
+ */
70
+ export function prepareAppend(before: TaskState, items: readonly AppendItem[]): { state: TaskState; taskIds: number[] } {
71
+ if (items.length === 0) throw new Error("append needs at least one task");
72
+ const first = before.nextId;
73
+ const uids = new Set(before.tasks.flatMap((t) => (t.uid ? [t.uid] : [])));
74
+ const added = items.map((item, i): Task => {
75
+ const id = first + i;
76
+ let uid = newUid();
77
+ while (uids.has(uid)) uid = newUid();
78
+ uids.add(uid);
79
+ const blockedBy = (item.blockedBy ?? []).map((position) => {
80
+ if (!Number.isSafeInteger(position) || position < 1 || position > i) {
81
+ throw new Error(`item ${i + 1} blockedBy: position ${position} is not an earlier item of this batch`);
82
+ }
83
+ return first + position - 1;
84
+ });
85
+ if (!item.subject.trim()) throw new Error(`item ${i + 1}: subject required`);
86
+ if (item.anchor !== undefined && !item.anchor.trim()) throw new Error(`item ${i + 1}: anchor must be a non-empty string`);
87
+ return {
88
+ id,
89
+ uid,
90
+ subject: item.subject,
91
+ status: "pending",
92
+ ...(item.description ? { description: item.description } : {}),
93
+ ...(blockedBy.length ? { blockedBy } : {}),
94
+ ...(item.metadata ? { metadata: structuredClone(item.metadata) } : {}),
95
+ ...(item.anchor !== undefined ? { anchor: item.anchor } : {}),
96
+ };
97
+ });
98
+ const state = { tasks: [...before.tasks, ...added], nextId: first + added.length };
99
+ if (!isSnapshotV1({ v: 1, tasks: added, nextId: state.nextId })) throw new Error("the appended tasks do not match the todo/v1 snapshot schema");
100
+ return { state, taskIds: added.map((t) => t.id) };
101
+ }
@@ -46,8 +46,11 @@ export function changedTasks(op: Op, params: TaskMutationParams, next: TaskState
46
46
  const find = (id: number) => next.tasks.find((t) => t.id === id);
47
47
  const had = (id: number) => before?.tasks.find((t) => t.id === id)?.metadata;
48
48
  switch (op.kind) {
49
- case "import":
50
- return next.tasks.map((task) => ({ task, op: "create", touched: [] }));
49
+ case "import": {
50
+ // An append judges only the tasks it adds; the list it extends was judged when each of them was written.
51
+ const added = op.taskIds ? new Set(op.taskIds) : undefined;
52
+ return next.tasks.filter((task) => !added || added.has(task.id)).map((task) => ({ task, op: "create", touched: [] }));
53
+ }
51
54
  case "create": {
52
55
  const items = Array.isArray(params.tasks) ? params.tasks : undefined;
53
56
  return op.taskIds.flatMap((id, i) => {
@@ -75,6 +78,14 @@ export function changedTasks(op: Op, params: TaskMutationParams, next: TaskState
75
78
 
76
79
  export class NamespaceRegistry {
77
80
  private readonly validators = new Map<string, NamespaceValidator>();
81
+ /** Namespaces the ledger itself owns; no `todo:namespace` payload replaces their validator. */
82
+ private readonly owned = new Set<string>();
83
+
84
+ /** Register the ledger's own validator for `ns`. */
85
+ own(ns: string, validate: NamespaceValidator): void {
86
+ this.owned.add(ns);
87
+ this.validators.set(ns, validate);
88
+ }
78
89
 
79
90
  /**
80
91
  * Handle a `todo:namespace` payload. A later registration of the same
@@ -92,6 +103,7 @@ export class NamespaceRegistry {
92
103
  if (typeof payload.validate !== "function") {
93
104
  return `${NAMESPACE_EVENT}: validate must be a function (ns "${payload.ns}")`;
94
105
  }
106
+ if (this.owned.has(payload.ns)) return `${NAMESPACE_EVENT}: ns "${payload.ns}" is owned by pi-todo-ledger`;
95
107
  this.validators.set(payload.ns, payload.validate as NamespaceValidator);
96
108
  return undefined;
97
109
  }
@@ -31,7 +31,8 @@ export type Op =
31
31
  | { kind: "delete"; id: number; subject: string }
32
32
  | { kind: "list"; statusFilter?: TaskStatus; includeDeleted: boolean }
33
33
  | { kind: "get"; task: Task }
34
- | { kind: "import" }
34
+ /** `taskIds`: the tasks an append added after the existing ones; absent when an import replaced an empty list. */
35
+ | { kind: "import"; taskIds?: number[] }
35
36
  | { kind: "clear"; count: number }
36
37
  | { kind: "error"; message: string };
37
38
 
@@ -161,10 +162,15 @@ function asCreateItem(value: unknown): TaskMutationParams | undefined {
161
162
  return value as TaskMutationParams;
162
163
  }
163
164
 
165
+ /** A fresh task uid: `t_` and ten random lowercase base32 characters. */
166
+ export function newUid(): string {
167
+ return `t_${Array.from(randomBytes(10), byte => "abcdefghijklmnopqrstuvwxyz234567"[byte & 31]).join("")}`;
168
+ }
169
+
164
170
  function buildCreatedTask(id: number, spec: TaskMutationParams, subject: string, now: string): Task {
165
171
  const newTask: Task = {
166
172
  id,
167
- uid: `t_${Array.from(randomBytes(10), byte => "abcdefghijklmnopqrstuvwxyz234567"[byte & 31]).join("")}`,
173
+ uid: newUid(),
168
174
  subject,
169
175
  status: "pending",
170
176
  };
@@ -97,7 +97,12 @@ export function formatContent(op: Op, state: TaskState): string {
97
97
  case "delete":
98
98
  return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
99
99
  case "import":
100
- return `Imported ${state.tasks.length} tasks`;
100
+ if (!op.taskIds) return `Imported ${state.tasks.length} tasks`;
101
+ return [`Appended ${op.taskIds.length} tasks`, ...op.taskIds.map((id) => {
102
+ const added = state.tasks.find((x) => x.id === id);
103
+ const block = added?.blockedBy?.length ? ` ⛓ ${added.blockedBy.map((dep) => `#${dep}`).join(",")}` : "";
104
+ return added ? `Created #${id}: ${sanitizeTerminalText(added.subject)} (pending)${block}${resultSuffix(added)}` : `Created #${id}`;
105
+ })].join("\n");
101
106
  case "clear":
102
107
  return `Cleared ${op.count} tasks`;
103
108
  case "list": {