pi-todo-ledger 0.4.0 → 0.6.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 +25 -0
- package/README.md +12 -0
- package/docs/overlay.md +21 -25
- package/docs/tool-schema.md +4 -0
- package/package.json +1 -1
- package/src/index.ts +6 -2
- package/src/ledger/finish-call.ts +46 -0
- package/src/ledger/herdr-owner.ts +74 -0
- package/src/state/store.ts +16 -4
- package/src/todo-overlay.ts +10 -4
- package/src/todo.ts +16 -67
- package/src/tool/response-envelope.ts +9 -15
- package/src/view/format.ts +33 -35
- package/src/view/plan.ts +74 -0
- package/src/view/task-labels.ts +29 -0
package/CONTRACT.md
CHANGED
|
@@ -152,6 +152,31 @@ Error: metadata.<ns> refused #<id>: <reason>
|
|
|
152
152
|
`clear`, `list`, and `get` run no validators.
|
|
153
153
|
Namespaces nobody registered pass unchecked.
|
|
154
154
|
|
|
155
|
+
### Optional Herdr launch identity (`metadata.herdr`)
|
|
156
|
+
|
|
157
|
+
When `pi-herdr-agents` acknowledges a `subagent` launch with `details.status: "started"` and echoes the call's `item`, the ledger looks up that task in the **calling session**.
|
|
158
|
+
`item` can be a stable task uid or `<session8>#<id>`, where `session8` is the first eight hex digits of the calling session id.
|
|
159
|
+
A numeric reference identifies the task present at dispatch: ordinary updates keep that identity even on a legacy task without a uid, while clearing or replaying the list invalidates a pending legacy binding.
|
|
160
|
+
Missing, unknown, foreign-session, or tombstoned items and failed or uncertain launches leave the list unchanged.
|
|
161
|
+
|
|
162
|
+
A match issues a normal guarded `update`: `owner` becomes the full `details.name`, and `metadata.herdr` records the launch:
|
|
163
|
+
|
|
164
|
+
```json
|
|
165
|
+
{ "name": "api-worker", "id": "0accb6d1-4380-4d51-a6d7-81dd0408d82f", "pane": "w1:p4" }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`name` is verbatim; `id` is the child **run id** (`details.id`), not the parent's session id or a path-derived id.
|
|
169
|
+
`pane` is the acknowledged `details.worktree.paneId` and is absent for ordinary launches.
|
|
170
|
+
On another successful assignment the new record replaces the old one, so an old pane id does not carry forward.
|
|
171
|
+
Other metadata stays intact; a refusal leaves the launch successful but adds the reason to its response.
|
|
172
|
+
Manual `owner` updates (including `self`) are still allowed; the optional `herdr` record describes the last bound launch, not proof of a live pane or of the current owner's identity.
|
|
173
|
+
|
|
174
|
+
Use `metadata.herdr.id` as the stable key when resolving or messaging the worker.
|
|
175
|
+
Use a name with `/boss send` only when it matches the name Straw Boss shows; on an unlabeled pane it may derive `api-worker` from the launch script for `API worker`.
|
|
176
|
+
For names longer than 24 UTF-16 units, Straw Boss displays just the first 23 units plus `…` in the `sb_name` pane token.
|
|
177
|
+
Resolve the live pane at read time rather than targeting that cosmetic label or a saved pane id.
|
|
178
|
+
This namespace needs no new status, schema field, or contract version.
|
|
179
|
+
|
|
155
180
|
## 4. Change guards
|
|
156
181
|
|
|
157
182
|
A namespace validator judges one task's value.
|
package/README.md
CHANGED
|
@@ -42,6 +42,18 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
|
|
|
42
42
|
`evidence` items are appended after the existing ones; `at` defaults to the time of the call.
|
|
43
43
|
`get` shows all three fields.
|
|
44
44
|
|
|
45
|
+
`create`, `update`, `get`, and `list` print each task's stable `uid` if it has one (for example, `t_k7wrx2jzfq`).
|
|
46
|
+
Pass that value as a Herdr `subagent`'s `item` (or use `<session8>#<id>` from the same session).
|
|
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
|
+
Use `metadata.herdr.id` to resolve or message the worker by its run key.
|
|
49
|
+
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
|
+
You can still set `owner` by hand.
|
|
51
|
+
|
|
52
|
+
The panel and `/todos` indent each open task under its first unfinished blocker and show its owner as `@owner`.
|
|
53
|
+
To mark a task as waiting for someone, set `metadata.waitsOn` to their name; to defer it until a particular time, set `metadata.until` to an ISO timestamp, e.g. `2027-01-15T09:00:00+08:00`.
|
|
54
|
+
An open task shows `⏸` with the name or the future deadline in local time.
|
|
55
|
+
These keys are display conventions: they neither schedule a wake-up nor change the task's `status` or the `todo/v1` contract.
|
|
56
|
+
|
|
45
57
|
`graph` names the work graph of the plan a task belongs to, one of `single-loop`, `fan-out/fan-in`, and `orchestrator-worker`; any other value is refused.
|
|
46
58
|
One session often runs several plans, so each task carries its own.
|
|
47
59
|
An update replaces it and `graph: null` clears it.
|
package/docs/overlay.md
CHANGED
|
@@ -23,13 +23,13 @@ snapshots are saved.
|
|
|
23
23
|
|
|
24
24
|
## Anatomy of a row
|
|
25
25
|
|
|
26
|
-
```
|
|
27
|
-
● Todos (
|
|
28
|
-
├─
|
|
29
|
-
├─
|
|
30
|
-
├─
|
|
31
|
-
├─
|
|
32
|
-
└─
|
|
26
|
+
```text
|
|
27
|
+
● Todos (0/5) · fan-out/fan-in
|
|
28
|
+
├─ ◐ #1 Scope @Ari
|
|
29
|
+
├─ ○ #3 API
|
|
30
|
+
├─ ○ #4 Check API
|
|
31
|
+
├─ ○ #5 UI
|
|
32
|
+
└─ ⏸ #2 Approve waits Pat
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
- **Heading** — `● Todos (done/total)` in the accent color while any task is
|
|
@@ -39,10 +39,11 @@ snapshots are saved.
|
|
|
39
39
|
Completed and deleted subjects render dim and struck through.
|
|
40
40
|
- **activeForm** — appended dim in parentheses, only while the task is
|
|
41
41
|
`in_progress`.
|
|
42
|
-
- **
|
|
43
|
-
-
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
- **Waiting** — `⏸` replaces the open-task glyph when `metadata.waitsOn` names a party or `metadata.until` is an ISO time in the future. The row shows the party, the local deadline, or both. An elapsed deadline no longer marks a task as waiting.
|
|
43
|
+
- **Owner** — `@owner` follows the subject in muted text.
|
|
44
|
+
- **Dependencies** — open rows nest under the first unfinished `blockedBy` id; siblings are visited in id order. Other unfinished blockers appear in the `⛓ #1,#2` tail. If another prerequisite interrupts a branch, `↳ #N` names the parent the row returns to.
|
|
45
|
+
- **Graph** — the heading names the graph when all open tasks share it; otherwise a root shows its own graph, if set.
|
|
46
|
+
- **`#id` prefix** — shown on every overlay row when at least one visible task carries a `blockedBy`.
|
|
46
47
|
- **Prefixes** — `├─` on each row, `└─` on the last one. A blank spacer line is
|
|
47
48
|
always appended below the panel so it is not flush against the input box.
|
|
48
49
|
|
|
@@ -86,21 +87,16 @@ label rather than advertising an unbindable key.
|
|
|
86
87
|
|
|
87
88
|
## `/todos`
|
|
88
89
|
|
|
89
|
-
`/todos`
|
|
90
|
-
|
|
90
|
+
`/todos` shows the whole dependency tree, independent of the overlay's row budget and auto-hiding.
|
|
91
|
+
Completed tasks follow in their own section.
|
|
91
92
|
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
── In Progress ──
|
|
100
|
-
◐ #3 Create DemoTodoRepository (creating the repository)
|
|
101
|
-
── Completed ──
|
|
102
|
-
✓ #1 Create DemoTodo domain entity
|
|
103
|
-
✓ #2 Create IDemoTodoRepository interface
|
|
93
|
+
```text
|
|
94
|
+
1 in progress · 4 pending · fan-out/fan-in
|
|
95
|
+
◐ #1 Scope @Ari
|
|
96
|
+
○ #3 API
|
|
97
|
+
○ #4 Check API
|
|
98
|
+
○ #5 UI
|
|
99
|
+
⏸ #2 Approve waits Pat
|
|
104
100
|
```
|
|
105
101
|
|
|
106
102
|
The header omits any count that is zero. Sections appear only when they have
|
package/docs/tool-schema.md
CHANGED
|
@@ -187,6 +187,10 @@ any disk writes.
|
|
|
187
187
|
|
|
188
188
|
## Content strings
|
|
189
189
|
|
|
190
|
+
The table shows the base messages.
|
|
191
|
+
`create`, `update` (including a no-op), `list`, and `get` append the stable `uid` to each task's summary line when it has one.
|
|
192
|
+
An open task that follows the [waiting convention](../README.md#using-it) also shows `⏸` and its reason on that line.
|
|
193
|
+
|
|
190
194
|
| Situation | `content[0].text` |
|
|
191
195
|
| --- | --- |
|
|
192
196
|
| Created | `Created #3: Write the parser (pending)` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-todo-ledger",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|
package/src/index.ts
CHANGED
|
@@ -33,7 +33,9 @@ import {
|
|
|
33
33
|
READY_EVENT,
|
|
34
34
|
toChangedEvent,
|
|
35
35
|
} from "./ledger/contract.ts";
|
|
36
|
+
import { makeFinishCall } from "./ledger/finish-call.ts";
|
|
36
37
|
import { GuardRegistry } from "./ledger/guards.ts";
|
|
38
|
+
import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
|
|
37
39
|
import { NamespaceRegistry } from "./ledger/namespaces.ts";
|
|
38
40
|
import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
|
|
39
41
|
import { replayFromBranch } from "./state/replay.ts";
|
|
@@ -186,7 +188,9 @@ export default function (
|
|
|
186
188
|
if (ignored) console.warn(`[pi-todo-ledger] ignored ${ignored}`);
|
|
187
189
|
});
|
|
188
190
|
|
|
189
|
-
|
|
191
|
+
const finish = makeFinishCall(pi, namespaces, guards);
|
|
192
|
+
registerTodoTool(pi, finish);
|
|
193
|
+
registerHerdrOwner(pi, finish);
|
|
190
194
|
registerTodosCommand(pi);
|
|
191
195
|
pi.events.emit(READY_EVENT, { v: CONTRACT_VERSION });
|
|
192
196
|
|
|
@@ -308,7 +312,7 @@ export default function (
|
|
|
308
312
|
// Reads getTodos() at render time; do NOT call replayFromBranch here
|
|
309
313
|
// (branch is stale — message_end runs after tool_execution_end).
|
|
310
314
|
pi.on("tool_execution_end", async (event) => {
|
|
311
|
-
if (event.toolName !== TOOL_NAME || event.isError) return;
|
|
315
|
+
if ((event.toolName !== TOOL_NAME && event.toolName !== "subagent") || event.isError) return;
|
|
312
316
|
try {
|
|
313
317
|
await updateTodoOverlay();
|
|
314
318
|
} catch (e) {
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { changesState, type ApplyResult } from "../state/state-reducer.ts";
|
|
3
|
+
import type { TaskState } from "../state/state.ts";
|
|
4
|
+
import { commitState, replaceState } from "../state/store.ts";
|
|
5
|
+
import { buildToolResult } from "../tool/response-envelope.ts";
|
|
6
|
+
import type { TaskAction, TaskMutationParams } from "../tool/types.ts";
|
|
7
|
+
import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./contract.ts";
|
|
8
|
+
import type { GuardRegistry } from "./guards.ts";
|
|
9
|
+
import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
|
|
10
|
+
|
|
11
|
+
export const ABORTED = "call aborted; nothing changed";
|
|
12
|
+
|
|
13
|
+
export function refuse(action: TaskAction, input: TaskMutationParams, state: TaskState, message: string) {
|
|
14
|
+
return { ...buildToolResult(action, input, state, { kind: "error", message }), isError: true };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
|
|
18
|
+
export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry) {
|
|
19
|
+
return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal) => {
|
|
20
|
+
const guardChange = {
|
|
21
|
+
op: action === "import" ? "create" as const : action as GuardOp,
|
|
22
|
+
params: input, before: before.tasks, after: result.state.tasks, sessionId, cwd,
|
|
23
|
+
};
|
|
24
|
+
if (!changesState(result.op)) {
|
|
25
|
+
// A valid no-op update reaches guards, but writes no entry and emits no event.
|
|
26
|
+
if (result.op.kind === "update") {
|
|
27
|
+
const refusal = await guards.check({ ...guardChange, noop: true });
|
|
28
|
+
if (refusal) return refuse(action, input, before, refusal);
|
|
29
|
+
if (signal?.aborted) return refuse(action, input, before, ABORTED);
|
|
30
|
+
}
|
|
31
|
+
commitState(sessionId, result.state);
|
|
32
|
+
return buildToolResult(action, input, result.state, result.op);
|
|
33
|
+
}
|
|
34
|
+
const refusal = namespaces.check(changedTasks(result.op, input, result.state)) ?? (await guards.check(guardChange));
|
|
35
|
+
if (refusal) return refuse(action, input, before, refusal);
|
|
36
|
+
if (signal?.aborted) return refuse(action, input, before, ABORTED);
|
|
37
|
+
// Append before committing the live slot; even nested tool calls survive replay, and a failed append changes nothing.
|
|
38
|
+
pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
|
|
39
|
+
if (action === "clear") replaceState(sessionId, result.state);
|
|
40
|
+
else commitState(sessionId, result.state);
|
|
41
|
+
pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
|
|
42
|
+
return buildToolResult(action, input, result.state, result.op);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type FinishCall = ReturnType<typeof makeFinishCall>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { withSessionLock } from "../state/session-lock.ts";
|
|
3
|
+
import { applyTaskMutation } from "../state/state-reducer.ts";
|
|
4
|
+
import { getState, listGeneration, sid } from "../state/store.ts";
|
|
5
|
+
import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
6
|
+
import type { FinishCall } from "./finish-call.ts";
|
|
7
|
+
import { runningGuard } from "./guards.ts";
|
|
8
|
+
|
|
9
|
+
const uid = /^t_[a-z2-7]{10}$/;
|
|
10
|
+
const local = /^([a-f0-9]{8})#([1-9]\d*)$/i;
|
|
11
|
+
const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
|
|
12
|
+
const nonblank = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0;
|
|
13
|
+
|
|
14
|
+
interface LaunchTarget { item: string; id: number; uid?: string; generation: symbol }
|
|
15
|
+
|
|
16
|
+
/** Per-load observer. A returned name is data, not a shell argument or a pane lookup. */
|
|
17
|
+
export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
|
|
18
|
+
// A numeric id can be reused by clear or a branch switch before Herdr acknowledges the launch.
|
|
19
|
+
// Pin the list generation for a legacy task; ordinary updates replace task objects but retain this identity.
|
|
20
|
+
const pending = new Map<string, Map<string, LaunchTarget>>();
|
|
21
|
+
pi.on("tool_call", (event, ctx) => {
|
|
22
|
+
if (event.toolName !== "subagent" || typeof event.input.item !== "string") return;
|
|
23
|
+
const item = event.input.item;
|
|
24
|
+
const match = local.exec(item);
|
|
25
|
+
if (!match) return;
|
|
26
|
+
const session = sid(ctx);
|
|
27
|
+
if (session.slice(0, 8).toLowerCase() !== match[1].toLowerCase()) return;
|
|
28
|
+
const task = getState(session).tasks.find(t => t.id === Number(match[2]) && t.status !== "deleted");
|
|
29
|
+
const generation = listGeneration(session);
|
|
30
|
+
if (!task || !generation) return;
|
|
31
|
+
const calls = pending.get(session) ?? new Map<string, LaunchTarget>();
|
|
32
|
+
calls.set(event.toolCallId, { item, id: task.id, uid: task.uid, generation });
|
|
33
|
+
pending.set(session, calls);
|
|
34
|
+
});
|
|
35
|
+
// A blocked call need not produce a result. Drop any leftover captures at the turn boundary.
|
|
36
|
+
pi.on("agent_end", (_event, ctx) => { pending.delete(sid(ctx)); });
|
|
37
|
+
pi.on("tool_result", async (event, ctx) => {
|
|
38
|
+
if (event.toolName !== "subagent") return;
|
|
39
|
+
const session = sid(ctx);
|
|
40
|
+
const calls = pending.get(session);
|
|
41
|
+
const capture = calls?.get(event.toolCallId);
|
|
42
|
+
calls?.delete(event.toolCallId);
|
|
43
|
+
if (!calls?.size) pending.delete(session);
|
|
44
|
+
const d = event.details;
|
|
45
|
+
if (event.isError || !record(d) || d.status !== "started" || !nonblank(d.name) || !nonblank(d.id)) return;
|
|
46
|
+
const item = d.item;
|
|
47
|
+
if (typeof item !== "string" || item !== event.input.item) return;
|
|
48
|
+
const pinned = capture?.item === item ? capture : undefined;
|
|
49
|
+
if (!pinned && !uid.test(item)) return;
|
|
50
|
+
const pane = record(d.worktree) ? d.worktree.paneId : undefined;
|
|
51
|
+
const herdr = { name: d.name, id: d.id, ...(nonblank(pane) ? { pane } : {}) };
|
|
52
|
+
const warn = (why: string) => ({
|
|
53
|
+
content: [...event.content, { type: "text" as const, text: `Todo owner binding: ${sanitizeTerminalText(why)}` }],
|
|
54
|
+
structuredContent: event.structuredContent,
|
|
55
|
+
});
|
|
56
|
+
if (runningGuard(session)) return warn("cannot update the list from its own change guard");
|
|
57
|
+
try {
|
|
58
|
+
return await withSessionLock(session, async () => {
|
|
59
|
+
const before = getState(session);
|
|
60
|
+
if (pinned && !pinned.uid && listGeneration(session) !== pinned.generation) return;
|
|
61
|
+
const task = pinned && !pinned.uid
|
|
62
|
+
? before.tasks.find(t => t.id === pinned.id && !t.uid)
|
|
63
|
+
: before.tasks.find(t => t.uid === (pinned?.uid ?? item));
|
|
64
|
+
if (!task || task.status === "deleted") return;
|
|
65
|
+
const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr } };
|
|
66
|
+
const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params));
|
|
67
|
+
if (result.details.error) return warn(result.details.error);
|
|
68
|
+
});
|
|
69
|
+
} catch (error) {
|
|
70
|
+
// Herdr already launched the child. Don't turn a persistence error into a failed launch/retry.
|
|
71
|
+
return warn(error instanceof Error ? error.message : String(error));
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
package/src/state/store.ts
CHANGED
|
@@ -8,7 +8,12 @@ import { EMPTY_STATE, type TaskState } from "./state.ts";
|
|
|
8
8
|
* The Map is the single mutation seam — only `commitState` / `replaceState` /
|
|
9
9
|
* `evictSession` write it; the reducer (`state/state-reducer.ts`) stays pure.
|
|
10
10
|
*/
|
|
11
|
-
|
|
11
|
+
interface SessionSlot {
|
|
12
|
+
state: TaskState;
|
|
13
|
+
/** In-process identity of the list, not the session. Never serialized. */
|
|
14
|
+
generation: symbol;
|
|
15
|
+
}
|
|
16
|
+
const sessions = new Map<string, SessionSlot>();
|
|
12
17
|
|
|
13
18
|
/**
|
|
14
19
|
* Ctx-less render pointer: which slot do the ctx-free readers (the overlay's
|
|
@@ -37,7 +42,7 @@ function freshState(): TaskState {
|
|
|
37
42
|
/** Get-or-read a session's slot: the committed slot by identity, or a fresh
|
|
38
43
|
* EMPTY_STATE copy (not stored) when the slot is absent. */
|
|
39
44
|
function slotFor(sessionId: string): TaskState {
|
|
40
|
-
return sessions.get(sessionId) ?? freshState();
|
|
45
|
+
return sessions.get(sessionId)?.state ?? freshState();
|
|
41
46
|
}
|
|
42
47
|
|
|
43
48
|
/**
|
|
@@ -64,7 +69,12 @@ export function getState(sessionId: string): TaskState {
|
|
|
64
69
|
* `replayFromBranch` decodes the latest snapshot, keyed to the session.
|
|
65
70
|
*/
|
|
66
71
|
export function replaceState(sessionId: string, next: TaskState): void {
|
|
67
|
-
sessions.set(sessionId, next);
|
|
72
|
+
sessions.set(sessionId, { state: next, generation: Symbol() });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Together with the local id, identifies a legacy task until clear, replay, or eviction. */
|
|
76
|
+
export function listGeneration(sessionId: string): symbol | undefined {
|
|
77
|
+
return sessions.get(sessionId)?.generation;
|
|
68
78
|
}
|
|
69
79
|
|
|
70
80
|
/**
|
|
@@ -73,7 +83,9 @@ export function replaceState(sessionId: string, next: TaskState): void {
|
|
|
73
83
|
* `/todos`, `renderCall`), keyed to the calling session.
|
|
74
84
|
*/
|
|
75
85
|
export function commitState(sessionId: string, next: TaskState): void {
|
|
76
|
-
sessions.
|
|
86
|
+
const slot = sessions.get(sessionId);
|
|
87
|
+
if (slot) slot.state = next;
|
|
88
|
+
else replaceState(sessionId, next);
|
|
77
89
|
}
|
|
78
90
|
|
|
79
91
|
/** Drop a session's slot on `session_shutdown`. No-op if the slot is absent. */
|
package/src/todo-overlay.ts
CHANGED
|
@@ -18,7 +18,8 @@ import { COLLAPSE_KEY_OFF, getMaxWidgetLines, resolveCollapseKey } from "./confi
|
|
|
18
18
|
import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
|
|
19
19
|
import { selectHasActive, selectOverlayLayout, selectShowTaskIds, selectTodoCounts } from "./state/selectors.ts";
|
|
20
20
|
import { getRenderState } from "./state/store.ts";
|
|
21
|
-
import {
|
|
21
|
+
import { formatPlanTaskLine } from "./view/format.ts";
|
|
22
|
+
import { planView } from "./view/plan.ts";
|
|
22
23
|
|
|
23
24
|
const WIDGET_KEY = "rpiv-todos";
|
|
24
25
|
|
|
@@ -140,7 +141,11 @@ export class TodoOverlay {
|
|
|
140
141
|
const overlayTasks = this.selectOverlayTasks(snapshot);
|
|
141
142
|
if (overlayTasks.length === 0) return [];
|
|
142
143
|
|
|
143
|
-
const
|
|
144
|
+
const plan = planView(overlayTasks);
|
|
145
|
+
// Keep completed rows in their old slots; fill open slots in display order before budgeting.
|
|
146
|
+
let nextOpen = 0;
|
|
147
|
+
const tasks = overlayTasks.map(t => t.status === "completed" ? t : plan.ordered[nextOpen++]);
|
|
148
|
+
const overlayState = { tasks, nextId: snapshot.nextId };
|
|
144
149
|
const truncate = (line: string): string => truncateToWidth(line, width, "…");
|
|
145
150
|
const counts = selectTodoCounts(overlayState);
|
|
146
151
|
const hasActive = selectHasActive(overlayState);
|
|
@@ -149,7 +154,8 @@ export class TodoOverlay {
|
|
|
149
154
|
const headingColor = hasActive ? "accent" : "dim";
|
|
150
155
|
const headingIcon = hasActive ? "●" : "○";
|
|
151
156
|
const headingText = `${t("overlay.heading", OVERLAY_HEADING)} (${counts.completed}/${counts.total})`;
|
|
152
|
-
const
|
|
157
|
+
const graph = plan.sharedGraph ? ` · ${theme.fg("dim", plan.sharedGraph)}` : "";
|
|
158
|
+
const heading = truncate(`${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}${graph}`);
|
|
153
159
|
|
|
154
160
|
// Collapsed view: just the heading + a dim "└─" expand hint, then the
|
|
155
161
|
// trailing spacer. Short-circuit before the budget math and the completed-
|
|
@@ -178,7 +184,7 @@ export class TodoOverlay {
|
|
|
178
184
|
const bodyBudget = this.uiCtx?.getToolsExpanded?.() === true ? overlayTasks.length : getMaxWidgetLines() - 1;
|
|
179
185
|
const layout = selectOverlayLayout(overlayState, bodyBudget);
|
|
180
186
|
for (const task of layout.visible) {
|
|
181
|
-
lines.push(truncate(`${theme.fg("dim", "├─")} ${
|
|
187
|
+
lines.push(truncate(`${theme.fg("dim", "├─")} ${formatPlanTaskLine(task, theme, showIds, plan.rows.get(task.id))}`));
|
|
182
188
|
}
|
|
183
189
|
|
|
184
190
|
const newlyDisplayedCompletedTaskIds = overlayTasks
|
package/src/todo.ts
CHANGED
|
@@ -14,18 +14,15 @@
|
|
|
14
14
|
|
|
15
15
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { loadConfig, validateGuidanceFields } from "./config.ts";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
17
|
+
import { ABORTED, type FinishCall, refuse } from "./ledger/finish-call.ts";
|
|
18
|
+
import { runningGuard } from "./ledger/guards.ts";
|
|
19
19
|
import { readImport } from "./ledger/import-snapshot.ts";
|
|
20
|
-
import { changedTasks, type NamespaceRegistry } from "./ledger/namespaces.ts";
|
|
21
20
|
import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
|
|
22
21
|
import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
|
|
23
|
-
import { applyTaskMutation, type ApplyResult
|
|
22
|
+
import { applyTaskMutation, type ApplyResult } from "./state/state-reducer.ts";
|
|
24
23
|
import { withSessionLock } from "./state/session-lock.ts";
|
|
25
|
-
import
|
|
26
|
-
import { commitState, getRenderState, getState, sid } from "./state/store.ts";
|
|
24
|
+
import { getRenderState, getState, sid } from "./state/store.ts";
|
|
27
25
|
import { prepareTodoArguments } from "./tool/normalize-params.ts";
|
|
28
|
-
import { buildToolResult } from "./tool/response-envelope.ts";
|
|
29
26
|
import {
|
|
30
27
|
COMMAND_NAME,
|
|
31
28
|
ERR_REQUIRES_INTERACTIVE,
|
|
@@ -36,12 +33,11 @@ import {
|
|
|
36
33
|
TOOL_NAME,
|
|
37
34
|
TodoParamsSchema,
|
|
38
35
|
} from "./tool/types.ts";
|
|
39
|
-
import {
|
|
36
|
+
import { formatPlanTaskLine, renderTodoCall, renderTodoResult } from "./view/format.ts";
|
|
37
|
+
import { planView } from "./view/plan.ts";
|
|
40
38
|
|
|
41
39
|
// English fallbacks for localized /todos section headers — the box-drawing
|
|
42
40
|
// decoration is part of the localized string so translators can adjust spacing.
|
|
43
|
-
const SECTION_PENDING = "── Pending ──";
|
|
44
|
-
const SECTION_IN_PROGRESS = "── In Progress ──";
|
|
45
41
|
const SECTION_COMPLETED = "── Completed ──";
|
|
46
42
|
|
|
47
43
|
// ---------------------------------------------------------------------------
|
|
@@ -75,14 +71,7 @@ export const DEFAULT_PROMPT_GUIDELINES: string[] = [
|
|
|
75
71
|
"Optional bookkeeping fields: points (effort, 0 to 10), anchor (the check that shows the task is done, e.g. a test command), and evidence (runs of checks, each {command, sha?, result: pass|fail, at?}). On update, points and anchor replace; evidence is appended, never replaced.",
|
|
76
72
|
];
|
|
77
73
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
/** An `isError` result for a refused call; the list is reported as it was. */
|
|
81
|
-
function refuse(action: TaskAction, input: TaskMutationParams, state: TaskState, message: string) {
|
|
82
|
-
return { ...buildToolResult(action, input, state, { kind: "error", message }), isError: true };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry): void {
|
|
74
|
+
export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall): void {
|
|
86
75
|
const guidance = validateGuidanceFields(loadConfig().guidance);
|
|
87
76
|
pi.registerTool({
|
|
88
77
|
name: TOOL_NAME,
|
|
@@ -120,42 +109,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
|
|
|
120
109
|
} else {
|
|
121
110
|
result = applyTaskMutation(before, action, input);
|
|
122
111
|
}
|
|
123
|
-
|
|
124
|
-
op: action === "import" ? "create" as const : action as GuardOp,
|
|
125
|
-
params: input as Record<string, unknown>,
|
|
126
|
-
before: before.tasks,
|
|
127
|
-
after: result.state.tasks,
|
|
128
|
-
sessionId,
|
|
129
|
-
cwd: ctx.cwd,
|
|
130
|
-
};
|
|
131
|
-
if (!changesState(result.op)) {
|
|
132
|
-
// A valid update that changes nothing still reaches the guards (flagged `noop`):
|
|
133
|
-
// re-asserting a status is how an agent reports it after a reload, and guards may
|
|
134
|
-
// track it. It writes no snapshot and emits no event.
|
|
135
|
-
if (result.op.kind === "update") {
|
|
136
|
-
const refusal = await guards.check({ ...guardChange, noop: true });
|
|
137
|
-
if (refusal) return refuse(action, input, before, refusal);
|
|
138
|
-
if (signal?.aborted) return refuse(action, input, before, ABORTED);
|
|
139
|
-
}
|
|
140
|
-
commitState(sessionId, result.state);
|
|
141
|
-
return buildToolResult(action, input, result.state, result.op);
|
|
142
|
-
}
|
|
143
|
-
// Namespace owners, then change guards, see the change before it commits; a refusal
|
|
144
|
-
// leaves state untouched.
|
|
145
|
-
const refusal =
|
|
146
|
-
namespaces.check(changedTasks(result.op, input, result.state)) ?? (await guards.check(guardChange));
|
|
147
|
-
if (refusal) return refuse(action, input, before, refusal);
|
|
148
|
-
if (signal?.aborted) return refuse(action, input, before, ABORTED);
|
|
149
|
-
// Persist the snapshot as a custom entry on the calling session's branch, however the
|
|
150
|
-
// tool was reached: a call made through another tool (`ctx.executeTool`, e.g. codemode)
|
|
151
|
-
// never lands as a standalone `toolResult`, so its `details` alone would not survive
|
|
152
|
-
// replay. Pi's own codemode persists its `store()` the same way.
|
|
153
|
-
// The entry is written before the live state commits: if appending throws, the call
|
|
154
|
-
// fails with the list unchanged, so live state never runs ahead of the branch.
|
|
155
|
-
pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
|
|
156
|
-
commitState(sessionId, result.state);
|
|
157
|
-
pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
|
|
158
|
-
return buildToolResult(action, input, result.state, result.op);
|
|
112
|
+
return finish(sessionId, ctx.cwd, action, input, before, result, signal);
|
|
159
113
|
});
|
|
160
114
|
},
|
|
161
115
|
|
|
@@ -183,7 +137,7 @@ export function registerTodoTool(pi: ExtensionAPI, namespaces: NamespaceRegistry
|
|
|
183
137
|
|
|
184
138
|
export function registerTodosCommand(pi: ExtensionAPI): void {
|
|
185
139
|
pi.registerCommand(COMMAND_NAME, {
|
|
186
|
-
description: "Show
|
|
140
|
+
description: "Show the current branch's plan by dependency, then its completed todos",
|
|
187
141
|
handler: async (_args, ctx) => {
|
|
188
142
|
if (!ctx.hasUI) {
|
|
189
143
|
ctx.ui.notify(t("command.requires_interactive", ERR_REQUIRES_INTERACTIVE), "error");
|
|
@@ -195,7 +149,8 @@ export function registerTodosCommand(pi: ExtensionAPI): void {
|
|
|
195
149
|
ctx.ui.notify(t("command.no_todos", MSG_NO_TODOS), "info");
|
|
196
150
|
return;
|
|
197
151
|
}
|
|
198
|
-
const
|
|
152
|
+
const { completed } = selectTasksByStatus(state);
|
|
153
|
+
const plan = planView(visible);
|
|
199
154
|
const counts = selectTodoCounts(state);
|
|
200
155
|
|
|
201
156
|
const header: string[] = [];
|
|
@@ -203,18 +158,12 @@ export function registerTodosCommand(pi: ExtensionAPI): void {
|
|
|
203
158
|
if (counts.inProgress > 0) header.push(`${counts.inProgress} ${formatStatusLabel("in_progress")}`);
|
|
204
159
|
if (counts.pending > 0) header.push(`${counts.pending} ${formatStatusLabel("pending")}`);
|
|
205
160
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}
|
|
211
|
-
if (groups.inProgress.length > 0) {
|
|
212
|
-
lines.push(t("command.section.in_progress", SECTION_IN_PROGRESS));
|
|
213
|
-
for (const task of groups.inProgress) lines.push(formatCommandTaskLine(task, "◐"));
|
|
214
|
-
}
|
|
215
|
-
if (groups.completed.length > 0) {
|
|
161
|
+
if (plan.sharedGraph) header.push(plan.sharedGraph);
|
|
162
|
+
const lines = [header.join(" · ")];
|
|
163
|
+
for (const task of plan.ordered) lines.push(` ${formatPlanTaskLine(task, ctx.ui.theme, true, plan.rows.get(task.id))}`);
|
|
164
|
+
if (completed.length) {
|
|
216
165
|
lines.push(t("command.section.completed", SECTION_COMPLETED));
|
|
217
|
-
for (const task of
|
|
166
|
+
for (const task of completed) lines.push(` ${formatPlanTaskLine(task, ctx.ui.theme, true)}`);
|
|
218
167
|
}
|
|
219
168
|
|
|
220
169
|
ctx.ui.notify(lines.join("\n"), "info");
|
|
@@ -1,22 +1,19 @@
|
|
|
1
1
|
import type { TaskState } from "../state/state.ts";
|
|
2
2
|
import type { Op } from "../state/state-reducer.ts";
|
|
3
3
|
import { deriveBlocks } from "../state/task-graph.ts";
|
|
4
|
+
import { isOpen, resultSuffix } from "../view/task-labels.ts";
|
|
4
5
|
import { sanitizeTerminalText } from "./sanitize.ts";
|
|
5
6
|
import type { Task, TaskAction, TaskDetails, TaskMutationParams } from "./types.ts";
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
|
-
*
|
|
9
|
-
* line. Used by the `list` content branch only — the overlay and `/todos`
|
|
10
|
-
* formatting paths use `view/format.ts` for richer presentations.
|
|
9
|
+
* Compact `list` row for the caller. The widget and /todos use the tree layout instead.
|
|
11
10
|
*/
|
|
12
11
|
function formatListLine(t: Task): string {
|
|
13
12
|
const block = t.blockedBy?.length ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}` : "";
|
|
14
13
|
const form = t.status === "in_progress" && t.activeForm ? ` (${sanitizeTerminalText(t.activeForm)})` : "";
|
|
15
|
-
return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
|
|
14
|
+
return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}${resultSuffix(t)}`;
|
|
16
15
|
}
|
|
17
16
|
|
|
18
|
-
const isOpen = (t: Task): boolean => t.status === "pending" || t.status === "in_progress";
|
|
19
|
-
|
|
20
17
|
/**
|
|
21
18
|
* `list` body. When an open task names a graph, open tasks are grouped under
|
|
22
19
|
* `<graph>:` headers in first-seen order, then `no graph:`, then `closed:` for
|
|
@@ -46,13 +43,11 @@ function formatList(view: readonly Task[]): string {
|
|
|
46
43
|
}
|
|
47
44
|
|
|
48
45
|
/**
|
|
49
|
-
*
|
|
50
|
-
* pre-refactor `todo.ts:354-376` — description, activeForm, blockedBy, blocks,
|
|
51
|
-
* owner — so envelope-level snapshot tests stay byte-equivalent.
|
|
46
|
+
* `get` shows the local id and stable uid on the first line, followed by the set fields.
|
|
52
47
|
*/
|
|
53
48
|
function formatGetLines(task: Task, state: TaskState): string {
|
|
54
49
|
const blocks = deriveBlocks(state.tasks).get(task.id) ?? [];
|
|
55
|
-
const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}`];
|
|
50
|
+
const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}${resultSuffix(task)}`];
|
|
56
51
|
if (task.description) lines.push(` description: ${sanitizeTerminalText(task.description)}`);
|
|
57
52
|
if (task.activeForm) lines.push(` activeForm: ${sanitizeTerminalText(task.activeForm)}`);
|
|
58
53
|
if (task.blockedBy?.length) {
|
|
@@ -75,8 +70,6 @@ function formatGetLines(task: Task, state: TaskState): string {
|
|
|
75
70
|
/**
|
|
76
71
|
* Pure formatter: `(op, state) → string`. Closed switch on `op.kind` —
|
|
77
72
|
* adding a new `Op` variant fails to compile here until a branch is added.
|
|
78
|
-
* The strings on each branch are byte-equivalent to pre-refactor `todo.ts`
|
|
79
|
-
* reducer output.
|
|
80
73
|
*/
|
|
81
74
|
export function formatContent(op: Op, state: TaskState): string {
|
|
82
75
|
switch (op.kind) {
|
|
@@ -86,16 +79,17 @@ export function formatContent(op: Op, state: TaskState): string {
|
|
|
86
79
|
.map((id) => {
|
|
87
80
|
const created = state.tasks.find((x) => x.id === id);
|
|
88
81
|
if (!created) return `Created #${id}`;
|
|
89
|
-
return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)`;
|
|
82
|
+
return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)${resultSuffix(created)}`;
|
|
90
83
|
})
|
|
91
84
|
.join("\n");
|
|
92
85
|
}
|
|
93
86
|
case "update": {
|
|
87
|
+
const suffix = resultSuffix(state.tasks.find(t => t.id === op.id)!);
|
|
94
88
|
if (!op.changed) {
|
|
95
|
-
return `No change: #${op.id} already matches the requested values (status: ${op.toStatus})`;
|
|
89
|
+
return `No change: #${op.id} already matches the requested values (status: ${op.toStatus})${suffix}`;
|
|
96
90
|
}
|
|
97
91
|
const transition = op.fromStatus !== op.toStatus ? ` (${op.fromStatus} → ${op.toStatus})` : "";
|
|
98
|
-
return `Updated #${op.id}${transition}`;
|
|
92
|
+
return `Updated #${op.id}${transition}${suffix}`;
|
|
99
93
|
}
|
|
100
94
|
case "delete":
|
|
101
95
|
return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
|
package/src/view/format.ts
CHANGED
|
@@ -5,6 +5,8 @@ import { selectTaskSubjectById } from "../state/selectors.ts";
|
|
|
5
5
|
import type { TaskState } from "../state/state.ts";
|
|
6
6
|
import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
7
7
|
import type { Task, TaskAction, TaskDetails, TaskMutationParams, TaskStatus } from "../tool/types.ts";
|
|
8
|
+
import type { PlanRow } from "./plan.ts";
|
|
9
|
+
import { uidSuffix, waitingLabel } from "./task-labels.ts";
|
|
8
10
|
|
|
9
11
|
// Re-export so legacy import paths (todo.ts, tests) continue to resolve;
|
|
10
12
|
// the canonical definition lives in the i18n bridge.
|
|
@@ -67,39 +69,33 @@ export function overlayStatusGlyph(status: TaskStatus, theme: Theme): string {
|
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
/**
|
|
70
|
-
* Format a
|
|
72
|
+
* Format a task row for the overlay or /todos. The subject color
|
|
71
73
|
* reflects task state while IDs and supporting metadata stay visually quiet.
|
|
72
74
|
*/
|
|
73
|
-
export function
|
|
74
|
-
const
|
|
75
|
+
export function formatPlanTaskLine(t: Task, theme: Theme, showId: boolean, row?: PlanRow): string {
|
|
76
|
+
const wait = waitingLabel(t);
|
|
77
|
+
const glyph = wait ? theme.fg("warning", "⏸") : overlayStatusGlyph(t.status, theme);
|
|
75
78
|
const subjectColor =
|
|
76
79
|
t.status === "in_progress" ? "accent" : t.status === "completed" || t.status === "deleted" ? "muted" : "text";
|
|
77
80
|
let subject = theme.fg(subjectColor, sanitizeTerminalText(t.subject));
|
|
78
81
|
if (t.status === "completed" || t.status === "deleted") {
|
|
79
82
|
subject = theme.strikethrough(subject);
|
|
80
83
|
}
|
|
81
|
-
let line = `${glyph}`;
|
|
84
|
+
let line = `${" ".repeat(row?.depth ?? 0)}${glyph}`;
|
|
82
85
|
if (showId) line += ` ${theme.fg("dim", `#${t.id}`)}`;
|
|
83
86
|
line += ` ${subject}`;
|
|
87
|
+
if (t.owner) line += ` ${theme.fg("muted", `@${sanitizeTerminalText(t.owner)}`)}`;
|
|
88
|
+
if (wait) line += ` ${theme.fg("muted", wait)}`;
|
|
84
89
|
if (t.status === "in_progress" && t.activeForm) {
|
|
85
90
|
line += ` ${theme.fg("muted", `(${sanitizeTerminalText(t.activeForm)})`)}`;
|
|
86
91
|
}
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
|
|
92
|
+
if (row?.graph) line += ` ${theme.fg("dim", row.graph)}`;
|
|
93
|
+
if (row?.resumeParent !== undefined) line += ` ${theme.fg("dim", `↳ #${row.resumeParent}`)}`;
|
|
94
|
+
const blockers = row?.otherBlockers ?? t.blockedBy;
|
|
95
|
+
if (blockers?.length) line += ` ${theme.fg("muted", `⛓ ${blockers.map(id => `#${id}`).join(",")}`)}`;
|
|
90
96
|
return line;
|
|
91
97
|
}
|
|
92
98
|
|
|
93
|
-
/**
|
|
94
|
-
* Format a single task line for the `/todos` slash command (no glyph color,
|
|
95
|
-
* indented bullet prefix).
|
|
96
|
-
*/
|
|
97
|
-
export function formatCommandTaskLine(t: Task, glyph: string): string {
|
|
98
|
-
const form = t.status === "in_progress" && t.activeForm ? ` (${sanitizeTerminalText(t.activeForm)})` : "";
|
|
99
|
-
const block = t.blockedBy?.length ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}` : "";
|
|
100
|
-
return ` ${glyph} #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
99
|
// ---------------------------------------------------------------------------
|
|
104
100
|
// Tool render hooks — wrapped so `todo.ts` becomes a thin call-site.
|
|
105
101
|
// ---------------------------------------------------------------------------
|
|
@@ -136,16 +132,23 @@ export function renderTodoCall(
|
|
|
136
132
|
}
|
|
137
133
|
|
|
138
134
|
/**
|
|
139
|
-
*
|
|
140
|
-
*
|
|
135
|
+
* A refusal renders its reason. Task results show only the affected or requested
|
|
136
|
+
* rows; operations with no rows keep the short success mark.
|
|
141
137
|
*/
|
|
142
138
|
export function renderTodoResult(result: ToolResultView, theme: Theme, isError = false): Text {
|
|
143
139
|
const failure = failureReason(result, isError);
|
|
144
140
|
if (failure !== undefined) return new Text(theme.fg("error", failure ? `✗ ${failure}` : "✗"), 0, 0);
|
|
145
141
|
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
142
|
+
const details = result.details as TaskDetails | undefined;
|
|
143
|
+
const tasks = echoedTasks(details);
|
|
144
|
+
if (tasks.length) {
|
|
145
|
+
const rows = tasks.map(task => {
|
|
146
|
+
const wait = waitingLabel(task);
|
|
147
|
+
const label = wait ? `⏸ ${wait}` : `${STATUS_GLYPH[task.status]} ${formatStatusLabel(task.status)}`;
|
|
148
|
+
const subject = details?.action === "list" || tasks.length > 1 ? ` ${sanitizeTerminalText(task.subject)}` : "";
|
|
149
|
+
return `${theme.fg(wait ? "warning" : STATUS_COLOR[task.status], label)} #${task.id}${subject}${theme.fg("dim", uidSuffix(task))}`;
|
|
150
|
+
});
|
|
151
|
+
return new Text(rows.join("\n"), 0, 0);
|
|
149
152
|
}
|
|
150
153
|
return new Text(theme.fg("success", "✓"), 0, 0);
|
|
151
154
|
}
|
|
@@ -164,21 +167,16 @@ function failureReason(result: ToolResultView, isError: boolean): string | undef
|
|
|
164
167
|
return sanitizeTerminalText(message.split("\n")[0]);
|
|
165
168
|
}
|
|
166
169
|
|
|
167
|
-
/**
|
|
168
|
-
function
|
|
169
|
-
if (!details) return
|
|
170
|
+
/** Use the result's snapshot, not the live slot: a historic card belongs to its own call. */
|
|
171
|
+
function echoedTasks(details?: TaskDetails): Task[] {
|
|
172
|
+
if (!details?.tasks || !details.params) return [];
|
|
170
173
|
const params = details.params as TaskMutationParams;
|
|
171
174
|
switch (details.action) {
|
|
172
|
-
case "create":
|
|
173
|
-
return details.tasks.at(-1)?.status;
|
|
174
|
-
case "update":
|
|
175
|
-
return params.status ?? details.tasks.find((t) => t.id === params.id)?.status;
|
|
176
|
-
case "delete":
|
|
177
|
-
return details.tasks.find((t) => t.id === params.id)?.status;
|
|
178
|
-
case "list":
|
|
175
|
+
case "create": return details.tasks.slice(-(params.tasks?.length ?? 1));
|
|
179
176
|
case "get":
|
|
180
|
-
case "
|
|
181
|
-
case "
|
|
182
|
-
|
|
177
|
+
case "update":
|
|
178
|
+
case "delete": return details.tasks.filter(t => t.id === params.id);
|
|
179
|
+
case "list": return details.tasks.filter(t => (params.includeDeleted || t.status !== "deleted") && (!params.status || t.status === params.status));
|
|
180
|
+
default: return [];
|
|
183
181
|
}
|
|
184
182
|
}
|
package/src/view/plan.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { isGraph, type Task } from "../tool/types.ts";
|
|
2
|
+
import { isOpen } from "./task-labels.ts";
|
|
3
|
+
|
|
4
|
+
export interface PlanRow {
|
|
5
|
+
depth: number;
|
|
6
|
+
graph?: Task["graph"];
|
|
7
|
+
otherBlockers: number[];
|
|
8
|
+
/** A cross-edge interrupted the displayed branch; identify the parent explicitly. */
|
|
9
|
+
resumeParent?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Read-only projection shared by the widget and /todos. Edges to finished work don't indent a row. */
|
|
13
|
+
export function planView(tasks: readonly Task[]) {
|
|
14
|
+
const open = tasks.filter(isOpen).sort((a, b) => a.id - b.id);
|
|
15
|
+
const graph = open[0]?.graph;
|
|
16
|
+
const sharedGraph = isGraph(graph) && open.every(task => task.graph === graph) ? graph : undefined;
|
|
17
|
+
const byId = new Map(open.map(task => [task.id, task]));
|
|
18
|
+
const rows = new Map<number, PlanRow>();
|
|
19
|
+
// Only the mutation and import paths enforce unique ids; don't traverse ambiguous legacy edges.
|
|
20
|
+
if (byId.size !== open.length) return { ordered: open, sharedGraph, rows };
|
|
21
|
+
const blockers = new Map<number, number[]>();
|
|
22
|
+
const children = new Map<number, Task[]>();
|
|
23
|
+
const roots: Task[] = [];
|
|
24
|
+
for (const task of open) {
|
|
25
|
+
const deps = (task.blockedBy ?? []).filter(id => byId.has(id));
|
|
26
|
+
blockers.set(task.id, deps);
|
|
27
|
+
if (!deps.length) roots.push(task);
|
|
28
|
+
else {
|
|
29
|
+
const siblings = children.get(deps[0]) ?? [];
|
|
30
|
+
siblings.push(task);
|
|
31
|
+
children.set(deps[0], siblings);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Visit first-parent subtrees in id order. For a join, emit any remaining prerequisites
|
|
36
|
+
// before the joined row. Iterative even for a long chain restored from a snapshot.
|
|
37
|
+
const ordered: Task[] = [];
|
|
38
|
+
const reached = new Set<number>();
|
|
39
|
+
const ancestry: number[] = [];
|
|
40
|
+
const branches = roots.slice().reverse();
|
|
41
|
+
while (branches.length) {
|
|
42
|
+
const branch = branches.pop()!;
|
|
43
|
+
const siblings = children.get(branch.id) ?? [];
|
|
44
|
+
for (let i = siblings.length - 1; i >= 0; i--) branches.push(siblings[i]);
|
|
45
|
+
const stack = [{ task: branch, emit: false }];
|
|
46
|
+
while (stack.length) {
|
|
47
|
+
const { task, emit } = stack.pop()!;
|
|
48
|
+
const deps = blockers.get(task.id)!;
|
|
49
|
+
if (!emit) {
|
|
50
|
+
if (reached.has(task.id)) continue;
|
|
51
|
+
reached.add(task.id);
|
|
52
|
+
stack.push({ task, emit: true });
|
|
53
|
+
for (let i = deps.length - 1; i >= 0; i--) {
|
|
54
|
+
if (!reached.has(deps[i])) stack.push({ task: byId.get(deps[i])!, emit: false });
|
|
55
|
+
}
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const parent = rows.get(deps[0]);
|
|
59
|
+
const depth = parent ? parent.depth + 1 : 0;
|
|
60
|
+
const resumeParent = parent && ancestry[depth - 1] !== deps[0] ? deps[0] : undefined;
|
|
61
|
+
rows.set(task.id, {
|
|
62
|
+
depth, otherBlockers: deps.slice(1), resumeParent,
|
|
63
|
+
graph: !depth && !sharedGraph && isGraph(task.graph) ? task.graph : undefined,
|
|
64
|
+
});
|
|
65
|
+
if (resumeParent !== undefined) ancestry.length = 0;
|
|
66
|
+
ancestry.length = depth;
|
|
67
|
+
ancestry[depth] = task.id;
|
|
68
|
+
ordered.push(task);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Replay predates cycle checks. Never hide a historical row we couldn't place in a tree.
|
|
72
|
+
for (const task of open) if (!rows.has(task.id)) ordered.push(task);
|
|
73
|
+
return { ordered, rows, sharedGraph };
|
|
74
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
2
|
+
import type { Task } from "../tool/types.ts";
|
|
3
|
+
|
|
4
|
+
export function isOpen(task: Task): boolean {
|
|
5
|
+
return task.status === "pending" || task.status === "in_progress";
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// A legacy task can lack a uid. A made-up one would not identify it to other extensions.
|
|
9
|
+
export function uidSuffix(task: Task): string {
|
|
10
|
+
return typeof task.uid === "string" ? ` ${sanitizeTerminalText(task.uid)}` : "";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const isoDateTime = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/i;
|
|
14
|
+
const localTime = new Intl.DateTimeFormat(undefined, { dateStyle: "short", timeStyle: "short" });
|
|
15
|
+
|
|
16
|
+
/** A hint for this render, never a status transition or a stored field. */
|
|
17
|
+
export function waitingLabel(task: Task): string {
|
|
18
|
+
if (!isOpen(task)) return "";
|
|
19
|
+
const who = task.metadata?.waitsOn;
|
|
20
|
+
const party = typeof who === "string" ? sanitizeTerminalText(who).trim() : "";
|
|
21
|
+
const until = task.metadata?.until;
|
|
22
|
+
const time = typeof until === "string" && isoDateTime.test(until) ? Date.parse(until) : NaN;
|
|
23
|
+
return [party && `waits ${party}`, time > Date.now() && `until ${localTime.format(time)}`].filter(Boolean).join(" · ");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function resultSuffix(task: Task): string {
|
|
27
|
+
const wait = waitingLabel(task);
|
|
28
|
+
return `${uidSuffix(task)}${wait ? ` ⏸ ${wait}` : ""}`;
|
|
29
|
+
}
|