@pi-unipi/kanboard 3.0.0-alpha.14 → 3.0.0-alpha.16

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/README.md CHANGED
@@ -3,10 +3,14 @@
3
3
  The pi half of **kanboard v3**: a per-project board for deferred work. The
4
4
  storage, transition rules and web UI live in the Rust binary
5
5
  ([`crates/kanboard`](../../crates/kanboard) — one writer for every change); this
6
- package is the terminal-side bridge: commands, the task runner, hub settings and
7
- the `kanboard` skill.
6
+ package is the terminal-side bridge: commands, the `-do` budget, the turn
7
+ arbiter's kanboard monitor, hub settings and the `kanboard` skill.
8
+ **There is no runner** — the session works board tasks itself; the runner,
9
+ queue and strategy labels were removed (see
10
+ [`docs/plans/2026-09-30-01a0f095.md`](../../docs/plans/2026-09-30-01a0f095.md)).
8
11
 
9
- Spec: [`docs/specs/2026-09-24-kanboard-v3-design.md`](../../docs/specs/2026-09-24-kanboard-v3-design.md).
12
+ Spec: [`docs/specs/2026-09-24-kanboard-v3-design.md`](../../docs/specs/2026-09-24-kanboard-v3-design.md)
13
+ (superseded for the runner/queue/strategy parts).
10
14
 
11
15
  ## Commands
12
16
 
@@ -18,7 +22,7 @@ Spec: [`docs/specs/2026-09-24-kanboard-v3-design.md`](../../docs/specs/2026-09-2
18
22
  | `open [--host H] [--port N]` | Ensure the daemon (reuse a healthy one, else spawn `serve` detached) and print `http://127.0.0.1:<port>/p/<slug>`. The browser opens only when `openBrowser` is on. |
19
23
  | `onboard` | `project add` for this workspace and remembers the slug. Idempotent. |
20
24
  | `close` | Shut down the board daemon — the web UI goes offline until the next `open`. Running tasks are unaffected. |
21
- | `status` | Daemon pid/port, project counts, active claims (session/pid/host/staleness), this session's queue, and the runner's current task. |
25
+ | `status` | Daemon pid/port, project counts and active claims (session/pid/host/staleness). |
22
26
  | `doctor` | ✓/✗ setup check (binary, daemon health, project, summary agent, bind, claims) as a display-only message. |
23
27
 
24
28
  The other three commands are separate slash commands:
@@ -26,56 +30,46 @@ The other three commands are separate slash commands:
26
30
  | Command | What it does |
27
31
  |---|---|
28
32
  | `/unipi:kanboard-add [-p 1-5] [--after ID] [--status backlog\|todo] <title>` | Capture a task — no agent turn. Lines below the title are the body; existing file paths pasted there are attached. `-p` maps 1 none · 2 low · 3 medium · 4 high · 5 urgent. |
29
- | `/unipi:kanboard-do <request>` | Reveal the skill and hand the request to the agent with board writes enabled for that turn. The agent may add/move/queue/note; it cannot run tasks — queued ids are drained by the runner when the turn ends. |
30
- | `/unipi:kanboard-autowork start\|stop` | `start` runs ready tasks one by one (queue order first, then `claim-next`); `stop` finishes the current task, then stops. |
33
+ | `/unipi:kanboard-do <request>` | Reveal the skill and hand the request to the agent with a **budget**: `doTasks` task slots (each `start` uses one) and `doWrites` board writes (add, edit, link, order, move backlog↔todo, note on tasks you don't hold). Always free: reads, and `finish`, `move <ID> blocked --comment` and `note` on tasks this session started. Budgets persist across turns until spent; `-do` tops up without stacking, `off` revokes. Children never write. |
34
+ | `/unipi:kanboard-autowork start\|stop` | `start` turns autowork on: the session works every ready task one at a time, in any mode it chooses, with no budget limits. `stop` turns the offers off (never aborts the current turn). |
31
35
 
32
36
  The old `add`/`work`/`stop` subcommands and bare-text capture now just point at
33
37
  these commands.
34
38
 
35
- ## Runner (`/unipi:kanboard-autowork start`)
36
-
37
- One job per session. The **runner owns the lifecycle transitions** the agent is
38
- not allowed to write:
39
-
40
- 1. `claim-next --session <sid> --pid <ppid> --host <host> --gate <chainGate>` —
41
- nothing ready → `Nothing ready (N waiting on deps, M blocked)`.
42
- 2. **The task's labels decide how it runs** (`edit <ID> --strategy
43
- none|goal|ralph|swarm|graph` and `--plan yes|no`; `auto`/unset = jev picks).
44
- jev gets one `choice` call with only the unset questions (title + body
45
- ≤2000 chars): strategy criteria none/goal/ralph/swarm/graph + plan yes/no.
46
- jev null → `none` + no plan; the decision is logged to
47
- `~/.unipi/logs/kanboard.log` with `UNIPI_DEBUG_KANBOARD=1`.
48
- 3. `set-run --mode`, then the task goes to the agent as a user message: title,
49
- body, last 10 activity entries, each dependency with its status and last note,
50
- and the rules (block with a comment to ask a question; never write
51
- `in_review`/`done`/`cancelled`; work only on this task).
52
- - **plan=yes** → plan mode is entered through workflow's `unipi:plan-enter`
53
- runner first; approval stays interactive; a discarded plan releases the
54
- task to Todo with `plan discarded`. The chosen strategy applies to the
55
- work turn after approval (deferred until `planModeChanged`).
56
- - **goal** → long-horizon's `unipi:goal-start` runner starts a goal with the
57
- task as the objective; the goal id is recorded with `set-run --goal` and
58
- completion is read back with `unipi:goal-status`.
59
- - **swarm / graph** → long-horizon's `unipi:lh-explicit` runner sets the
60
- explicit mode for the work turn.
61
- - **ralph** → `unipi:ralph-start` starts the checklist loop (task title +
62
- body as the checklist file); with no `- [ ]` items or a failed start it
63
- falls back to goal, then none.
64
- 4. Run end (a `/plan` settle after the last `agent_end`, once the agent reports
65
- idle with no queued messages): the task is re-read — if the agent blocked it,
66
- that is respected and reported (`▣ UNI-12 blocked: <comment>`) and the loop
67
- continues; otherwise `release --to in_review --comment <last assistant text
68
- ≤500 chars>`. `Esc` (aborted turn) → `release --to todo --comment "interrupted
69
- by user"` and the loop stops. Session shutdown → `release --to todo` with
70
- `session ended`.
71
- 5. After each task: `✓ UNI-12 → In Review: <first line>`, then the loop takes
72
- the next id from the session **queue** (`claim-next --id`; entries that went
73
- stale are dropped with a notice), falls back to `claim-next` while autowork
74
- is on, and stops when nothing is ready. The event loop is never blocked.
75
-
76
- Footer: `▣ UNI-12 · <strategy>[ +plan]` while a task runs. The claimed task is persisted with
77
- `pi.appendEntry("unipi:kanboard-runner", …)`, so `/reload` or a resume offers to
78
- resume it or releases it to Todo.
39
+ ## Continuation: the turn arbiter's monitor
40
+
41
+ There is no runner loop. When a run settles, `src/monitor.ts` — a nudge
42
+ provider on core's turn arbiter (`agent_before_settle`) — proposes at most one
43
+ continuation:
44
+
45
+ - **Claims (priority 50):** a task this session started is still In Progress →
46
+ `↻ UNI-30 still In Progress — continue, or finish/block it (n/5)`.
47
+ - **Autowork-next (priority 40):** autowork on, no open claims, a ready task
48
+ exists → `↻ next ready: UNI-33 <title> …`; nothing ready → an
49
+ `autowork done` notice, then autowork turns itself off.
50
+
51
+ The monitor defers to a **long-horizon owner** (priority 100), to **pending
52
+ events** and to **wait sources** (a running bg wake, a busy sidekick, a
53
+ background subagent). It **disarms** on an aborted/errored run (Esc never gets
54
+ talked over) and when a goal stops paused/budget with claims open (notice
55
+ only). Runaway guards: 2 nudged runs with zero tool calls → `⚠ stalled`, a
56
+ hard cap of 5 nudges per task, a question heuristic (the agent asked the user
57
+ something → notice, no nudge), and in autowork the same stall rule plus a
58
+ 3-offers-per-task cap. After an Esc, a later prompt that names a claimed id
59
+ re-arms the monitor.
60
+
61
+ **Children are read-only.** Sidekicks and subagents may read the board; every
62
+ write is refused with "board writes are the lead's job — report this to the
63
+ lead". Reminders are silent there too.
64
+
65
+ **Session identity & lifecycle.** On every lead `session_start` the session id
66
+ becomes `UNIPI_KANBOARD_SESSION = pi-<pi session id>` (stable across `-c`/`-r`)
67
+ and `UNIPI_KANBOARD_PID` the process pid. At startup stale claims whose pid died
68
+ are reaped (`session lost: …`), and tasks released that way get a one-time
69
+ notice ("UNI-30 was released when the last run ended — ask me to re-start it").
70
+ On `session_shutdown` this session's open claims are released to Todo with
71
+ `released: session ended mid-task (<session>)` (actor system — the agent actor
72
+ cannot release).
79
73
 
80
74
  ## Settings (hub section "Kanboard")
81
75
 
@@ -88,10 +82,11 @@ resume it or releases it to Todo.
88
82
  | `openBrowser` | `false` | Open the board in a browser on `open` |
89
83
  | `requireAuth` | `false` | Also require the access token on 127.0.0.1 (remote always does) |
90
84
  | `keepToken` | `false` | Reuse `<home>/token` across daemon restarts |
91
- | `queueMax` | `10` | Tasks a session may queue (0 = unlimited); passed to the CLI as `UNIPI_KANBOARD_QUEUE_MAX` |
92
- | `maxSessions` | `2` | Distinct sessions running tasks per project (`UNIPI_KANBOARD_MAX_SESSIONS`) |
93
- | `turnAddLimit` | `20` | `add` calls allowed per -do turn or runner task (0 = unlimited) |
94
- | `reminders` | `true` | Progress reminders for hand-worked tasks: a steer on the first file-changing call while a mentioned task is still Todo (R1), and a follow-up at turn end while a started task is still In Progress (R2, max 2 per task). Text only, silent in runner runs |
85
+ | `maxSessions` | `2` | Distinct sessions holding in-progress tasks per project (`UNIPI_KANBOARD_MAX_SESSIONS`) |
86
+ | `turnAddLimit` | `20` | `add` calls allowed per turn (0 = unlimited) — the runaway guard, applies in autowork too |
87
+ | `reminders` | `true` | R1: steer on the first file-changing call while a mentioned task is still Todo (text only, never blocks; silent in child sessions) |
88
+ | `doTasks` | `5` | Task slots a `/unipi:kanboard-do` grants (each `start` costs one) |
89
+ | `doWrites` | `10` | Board writes a `/unipi:kanboard-do` grants; a stored `doCredits` migrates into this |
95
90
  | *actions* | | `Open board…`, `Stop daemon`, `Summary agent command…`, `Rotate access token` |
96
91
 
97
92
  `Summary agent command…` writes through `settings set agent-command` and
@@ -210,10 +205,10 @@ The extension never edits those files — the binary owns them.
210
205
  | `UNI-5 is unreadable: … (line N)` | That task's own file is broken — repair it before moving/noting it. |
211
206
  | The daemon looks stale | `unipi-kanboard status` (pid + liveness), then `/unipi:kanboard close`, `unipi-kanboard stop` (SIGTERM, ≤3s) or the hub's **Stop daemon** action. |
212
207
  | Nothing is ready | `unipi-kanboard list --ready --json` shows `waitingFor`; a cancelled dependency blocks forever — `link`/`unlink` to re-plan. |
213
- | The runner prompts for permission on every board call | Fixed in auto mode: `unipi-kanboard … --actor agent` is allow-listed by the permission gate (ask mode still asks). |
208
+ | A board call prompts for permission | Fixed in auto mode: `unipi-kanboard … --actor agent` is allow-listed by the permission gate (ask mode still asks). |
214
209
 
215
210
  ## Tests
216
211
 
217
212
  ```bash
218
- npm test -w packages/kanboard # bin resolution, commands, runner, settings
213
+ npm test -w packages/kanboard # bin resolution, commands, budget guard, monitor, settings
219
214
  ```
package/index.ts CHANGED
@@ -2,36 +2,43 @@
2
2
  * @pi-unipi/kanboard — pi extension.
3
3
  *
4
4
  * Bridges the terminal to the board: `/unipi:kanboard` (open/close/onboard/
5
- * status/doctor — bare lists the commands), `/unipi:kanboard-add`,
6
- * `/unipi:kanboard-do` (opens the board-write window for one turn),
7
- * `/unipi:kanboard-autowork` (the runner loop: queue first, then claim-next).
8
- * The runner owns claim → In Progress and run-end → In Review for queued work;
9
- * an agent working a task by hand uses `start`/`finish` (free), nudged by the
10
- * progress reminders (src/reminders.ts). The board itself
11
- * is written by the Rust binary (`crates/kanboard`); this extension never edits
12
- * task files. Bash calls into the binary are gated by the write window
13
- * (src/guard.ts): reads always pass, writes need a -do turn or a running task.
5
+ * status/doctor/show — bare lists the commands), `/unipi:kanboard-add`,
6
+ * `/unipi:kanboard-do` (grants task slots + a write budget for one prompt),
7
+ * `/unipi:kanboard-autowork` (work every ready task in this session). The
8
+ * session works tasks itself — there is no runner. Continuation is the turn
9
+ * arbiter's job: src/monitor.ts proposes at most one nudge per settle (claims
10
+ * first, then the next ready autowork task). Bash calls into the Rust binary
11
+ * are gated by src/guard.ts: reads always pass, children never write, writes
12
+ * cost the -do budget (own-claim closes are free). The board itself is
13
+ * written by the binary; this extension never edits task files.
14
14
  */
15
15
 
16
16
  import { dirname } from "node:path";
17
17
  import { fileURLToPath } from "node:url";
18
18
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { Text } from "@earendil-works/pi-tui";
19
20
  import {
20
21
  MODULES,
21
22
  UNIPI_EVENTS,
22
23
  emitEvent,
23
24
  getPackageVersion,
25
+ getSettings,
26
+ getSharedKanboardStatus,
27
+ getSharedOwnerStatus,
24
28
  initUnipiDirs,
29
+ isChildProcess,
25
30
  registerCommandRunner,
26
- getSettings,
27
- appendProgress,
31
+ registerEvidenceContributor,
32
+ registerNudgeProvider,
28
33
  registerProgressRenderer,
34
+ setSharedKanboardStatus,
35
+ appendProgress,
29
36
  } from "@pi-unipi/core";
30
37
 
31
38
  import { openCli, type KanboardCli } from "./src/bin.js";
32
- import { createWriteGuard } from "./src/guard.js";
39
+ import { kanboardInvocations } from "./src/guard.js";
40
+ import { maybeBadgeToolResult, registerBadgeRenderer } from "./src/badges.js";
33
41
  import {
34
- drainQueueAfterDo,
35
42
  registerKanboardCommands,
36
43
  runOpen,
37
44
  syncPiRuntime,
@@ -39,9 +46,12 @@ import {
39
46
  runStopDaemon,
40
47
  type CommandDeps,
41
48
  } from "./src/commands.js";
42
- import { createDebugLog, createRunner, registerPlanEventListener, type Runner } from "./src/runner.js";
43
- import { createProgressTracker, registerProgressReminders, sendReminder } from "./src/reminders.js";
44
- import { asTaskList } from "./src/shapes.js";
49
+ import { createWriteGuard } from "./src/guard.js";
50
+ import { NOTICE_ENTRY, flushNotices, NoticeBuffer } from "./src/notice-buffer.js";
51
+ import { createKanboardMonitor } from "./src/monitor.js";
52
+ import { createDebugLog } from "./src/debug.js";
53
+ import { createProgressTracker, registerProgressReminders, ANTI_POISONING_SUFFIX } from "./src/reminders.js";
54
+ import { asTaskList, type KanboardTask } from "./src/shapes.js";
45
55
  import {
46
56
  ACTION_OPEN,
47
57
  ACTION_STOP_DAEMON,
@@ -58,7 +68,8 @@ export const SKILL_REVEAL_EVENT = "unipi:skills:reveal";
58
68
  export const KANBOARD_SKILL = "kanboard";
59
69
 
60
70
  export default function (pi: ExtensionAPI) {
61
- // One session id shared by the runner and the agent's bash calls.
71
+ // One session id shared by the agent's bash calls (refined at session_start
72
+ // from the pi session id; children keep the value they inherited).
62
73
  process.env.UNIPI_KANBOARD_SESSION ??= `pi-${process.pid}`;
63
74
  // `start` claims belong to this pi process: the stale-claim reaper releases
64
75
  // them to Todo when it dies (the agent's bash inherits the env).
@@ -71,15 +82,11 @@ export default function (pi: ExtensionAPI) {
71
82
 
72
83
  let cli: KanboardCli | null = null;
73
84
  let unavailable: string | null = null;
74
- let runner: Runner | null = null;
75
- const guard = createWriteGuard(
76
- () => {
77
- const status = runner?.status();
78
- return status?.phase === "running" ? status.taskId : null;
79
- },
80
- () => readKanboardSettings().turnAddLimit,
81
- () => readKanboardSettings().doCredits,
82
- );
85
+ const guard = createWriteGuard({
86
+ addLimit: () => readKanboardSettings().turnAddLimit,
87
+ doTasks: () => readKanboardSettings().doTasks,
88
+ doWrites: () => readKanboardSettings().doWrites,
89
+ });
83
90
  const sessionId = (): string => process.env.UNIPI_KANBOARD_SESSION ?? `pi-${process.pid}`;
84
91
 
85
92
  const projectSlug = (): string => {
@@ -93,8 +100,87 @@ export default function (pi: ExtensionAPI) {
93
100
  }
94
101
  };
95
102
 
96
- // Live getters: the command is registered before the binary is resolved, so
97
- // the deps object must read the current state at call time.
103
+ // ── board reads (lead monitor/evidence/holder/notice) ────────────────
104
+ const listTasks = async (args: string[] = []): Promise<KanboardTask[]> => {
105
+ const client = cli;
106
+ const slug = projectSlug();
107
+ if (!client || !slug) return [];
108
+ const payload = await client.run<unknown>(["list", ...args, "--json"], {
109
+ extraEnv: { UNIPI_KANBOARD_PROJECT: slug, UNIPI_KANBOARD_SESSION: sessionId() },
110
+ });
111
+ return asTaskList(payload).tasks;
112
+ };
113
+ const ownClaims = async (): Promise<KanboardTask[]> => {
114
+ try {
115
+ const session = sessionId();
116
+ return (await listTasks()).filter((task) => {
117
+ const run = task.run as { session?: string } | null | undefined;
118
+ return task.status === "in_progress" && run?.session === session;
119
+ });
120
+ } catch {
121
+ return [];
122
+ }
123
+ };
124
+
125
+ // ── monitor: the arbiter's kanboard nudge provider (lead only) ───────
126
+ // User-only notices queue here and flush at agent_settled (post boundary).
127
+ const pendingNotices = new NoticeBuffer();
128
+ const monitor = createKanboardMonitor({
129
+ list: () => listTasks(),
130
+ listReady: () => listTasks(["--ready"]),
131
+ session: sessionId,
132
+ ownerStatus: () => getSharedOwnerStatus(),
133
+ now: () => Date.now(),
134
+ // User-only: only QUEUE here — a sendMessage custom message would be
135
+ // converted to a user-role LLM message (never what a notice wants).
136
+ // kanboard's agent_settled handler drains the buffer (appendEntry + toast).
137
+ notify: (text, level) => {
138
+ pendingNotices.queue(text, level);
139
+ },
140
+ // The monitor turned autowork off itself (done / stalled): the guard's
141
+ // budget and the footer's `▣ autowork` flag must follow.
142
+ onAutoworkOff: () => {
143
+ guard.setAutowork(false);
144
+ void refreshHolder();
145
+ },
146
+ cliPrefix: () => {
147
+ const slug = projectSlug();
148
+ return cli && slug ? `${cli.binary.path} --actor agent --project ${slug}` : null;
149
+ },
150
+ debug,
151
+ });
152
+
153
+ const refreshHolder = async (): Promise<void> => {
154
+ try {
155
+ setSharedKanboardStatus({
156
+ claims: (await ownClaims()).map((task) => task.id),
157
+ autowork: guard.remaining().autowork,
158
+ });
159
+ } catch {
160
+ // The footer simply shows nothing until the next refresh.
161
+ }
162
+ };
163
+
164
+ if (!isChildProcess()) {
165
+ try {
166
+ registerNudgeProvider("kanboard", 50, (info) => monitor.propose(info));
167
+ } catch {
168
+ // Registration must never block module load.
169
+ }
170
+ try {
171
+ registerEvidenceContributor("kanboard", async () => ({
172
+ blocking: (await ownClaims()).map(
173
+ (task) => `${task.id} is still In Progress (claimed by this session) — finish it or move it to blocked`,
174
+ ),
175
+ notes: [],
176
+ }));
177
+ } catch {
178
+ // Registration must never block module load.
179
+ }
180
+ registerBadgeRenderer(pi);
181
+ }
182
+
183
+ // ── command plumbing ─────────────────────────────────────────────────
98
184
  const buildDeps = (): CommandDeps => ({
99
185
  get cli() {
100
186
  return cli;
@@ -104,10 +190,12 @@ export default function (pi: ExtensionAPI) {
104
190
  },
105
191
  settings: () => readKanboardSettings(process.cwd()),
106
192
  revealSkill,
107
- work: (ctx) => runner?.work(ctx) ?? Promise.resolve(),
108
- stop: (ctx) => runner?.stop(ctx),
109
- drainQueue: (ctx) => runner?.drain(ctx) ?? Promise.resolve(),
110
- status: () => runner?.status() ?? { taskId: null, mode: null, phase: "idle" },
193
+ setAutowork: (on) => {
194
+ guard.setAutowork(on);
195
+ monitor.setAutowork(on);
196
+ if (on) monitor.arm("autowork");
197
+ void refreshHolder();
198
+ },
111
199
  guard,
112
200
  session: sessionId,
113
201
  debug,
@@ -130,35 +218,19 @@ export default function (pi: ExtensionAPI) {
130
218
  cli = opened;
131
219
  unavailable = null;
132
220
  debug(`binary: ${opened.binary.path} (${opened.binary.source})`);
133
- if (!runner) {
134
- runner = createRunner({
135
- pi,
136
- cli,
137
- project: projectSlug,
138
- cwd: ctx.cwd,
139
- settings: () => readKanboardSettings(ctx.cwd),
140
- debug,
141
- });
142
- registerPlanEventListener(pi, runner);
143
- }
144
221
  return true;
145
222
  };
146
223
 
147
224
  registerProgressRenderer(pi);
148
225
  registerKanboardCommands(pi, buildDeps());
149
226
 
150
- // R1/R2 progress reminders for hand-worked tasks (silent in runner runs).
151
- const reminders = registerProgressReminders(
227
+ // R1 progress reminders for hand-worked tasks (silent in child sessions).
228
+ registerProgressReminders(
152
229
  pi,
153
230
  createProgressTracker({
154
231
  enabled: () => readKanboardSettings().reminders,
155
- runnerOwned: () => (runner?.status().phase ?? "idle") !== "idle",
156
232
  session: sessionId,
157
- list: async () => {
158
- const slug = projectSlug();
159
- if (!cli || !slug) return [];
160
- return asTaskList(await cli.run<unknown>(["list"], { extraEnv: { UNIPI_KANBOARD_PROJECT: slug } })).tasks;
161
- },
233
+ list: () => listTasks(),
162
234
  cliPrefix: () => {
163
235
  const slug = projectSlug();
164
236
  return cli && slug ? `${cli.binary.path} --actor agent --project ${slug}` : null;
@@ -189,10 +261,78 @@ export default function (pi: ExtensionAPI) {
189
261
  await runRotateTokenAction(buildDeps(), context);
190
262
  });
191
263
 
264
+ // ── run hooks: monitor, badges, holder (lead only) ───────────────────
265
+ pi.on("before_agent_start", async (event) => {
266
+ try {
267
+ await monitor.onUserPrompt(String((event as { prompt?: unknown }).prompt ?? ""));
268
+ } catch {
269
+ // Prompt handling must never abort a turn.
270
+ }
271
+ return undefined;
272
+ });
273
+ pi.on("agent_start", () => {
274
+ try {
275
+ monitor.onAgentStart();
276
+ } catch {
277
+ // Accounting must never abort a turn.
278
+ }
279
+ });
280
+ pi.on("agent_end", async (event) => {
281
+ try {
282
+ guard.onAgentEnd();
283
+ monitor.onAgentEnd((event as { messages?: unknown[] }).messages);
284
+ } catch {
285
+ // Monitoring must never abort a turn.
286
+ }
287
+ });
288
+ // Post-boundary: entries append fine here (they are dropped inside the
289
+ // settle path), and the toast gives the notice a life outside the transcript.
290
+ pi.on("agent_settled", async (_event, ctx) => {
291
+ try {
292
+ const ui = ctx as unknown as { hasUI?: boolean; ui?: { notify?: (t: string, l?: string) => void } } | undefined;
293
+ flushNotices(
294
+ pi,
295
+ pendingNotices,
296
+ {
297
+ hasUI: ui?.hasUI,
298
+ notify: (text, level) => ui?.ui?.notify?.(text, level ?? "info"),
299
+ },
300
+ debug,
301
+ );
302
+ void refreshHolder();
303
+ } catch {
304
+ // The footer simply shows nothing until the next refresh.
305
+ }
306
+ });
307
+ pi.on("tool_result", async (event) => {
308
+ const toolEvent = event as { toolName?: string; input?: Record<string, unknown>; isError?: boolean };
309
+ try {
310
+ if (isChildProcess()) return undefined;
311
+ if (toolEvent.toolName !== "bash" && toolEvent.toolName !== "powershell") return undefined;
312
+ maybeBadgeToolResult(pi, String(toolEvent.toolName), toolEvent.input, toolEvent.isError === true);
313
+ if (toolEvent.isError) return undefined;
314
+ const invocations = kanboardInvocations(String(toolEvent.input?.command ?? ""));
315
+ if (invocations.some((inv) => inv.sub === "start" || inv.sub === "finish" || inv.sub === "move")) {
316
+ if (invocations.some((inv) => inv.sub === "start")) monitor.arm("start");
317
+ void refreshHolder();
318
+ }
319
+ } catch {
320
+ // Badges and holder refreshes must never abort a turn.
321
+ }
322
+ return undefined;
323
+ });
324
+
325
+ // ── session lifecycle ────────────────────────────────────────────────
192
326
  pi.on("session_start", async (_event, ctx) => {
193
327
  // Kanboard's own ambient children (summaries, --list-models) get this env:
194
328
  // they must not re-sync the runtime or spawn a daemon.
195
329
  if (process.env.UNIPI_KANBOARD_CHILD) return;
330
+ // Children keep the session id they inherited from the lead.
331
+ if (!isChildProcess()) {
332
+ // Step 0: reason is "startup" even for -c/-r — never branch on it.
333
+ process.env.UNIPI_KANBOARD_SESSION = `pi-${ctx.sessionManager.getSessionId()}`;
334
+ process.env.UNIPI_KANBOARD_PID = String(process.pid);
335
+ }
196
336
  initUnipiDirs();
197
337
  if (attach(ctx as unknown as ExtensionContext)) {
198
338
  const deps = buildDeps();
@@ -209,6 +349,50 @@ export default function (pi: ExtensionAPI) {
209
349
  debug(`unavailable: ${unavailable}`);
210
350
  return;
211
351
  }
352
+ // Reap claims whose pid died with the process (the runner used to do
353
+ // this): released tasks get the "session lost: <session>" activity the
354
+ // resume notice below keys on. The reaper acts as the system actor.
355
+ if (!isChildProcess()) {
356
+ try {
357
+ const reaped = await cli!.run<unknown>(["reap", "--json"], {
358
+ extraEnv: { UNIPI_KANBOARD_PROJECT: projectSlug(), UNIPI_KANBOARD_SESSION: sessionId() },
359
+ });
360
+ debug(`reap: ${JSON.stringify(reaped)}`);
361
+ } catch (error) {
362
+ debug(`reap failed: ${error instanceof Error ? error.message : String(error)}`);
363
+ }
364
+ }
365
+ void refreshHolder();
366
+
367
+ // Resume notice: claims the reaper released when a previous run of THIS
368
+ // session died ("session lost: <session> …"), or that a shutdown released
369
+ // ("released: … session ended mid-task (<session>)"). Once per start.
370
+ // Activity entries are ordered oldest-first — the LAST one must be the
371
+ // release (a task that moved on afterwards is not news).
372
+ if (!isChildProcess()) {
373
+ try {
374
+ const session = sessionId();
375
+ const stale = (await listTasks()).filter((task) => {
376
+ if (task.status !== "todo") return false;
377
+ const last = task.activity?.at(-1);
378
+ if (!last) return false;
379
+ return (
380
+ last.text.startsWith(`session lost: ${session}`) ||
381
+ last.text.includes(`released: session ended mid-task (${session})`)
382
+ );
383
+ });
384
+ if (stale.length > 0) {
385
+ const ids = stale.map((task) => task.id).join(", ");
386
+ (ctx as unknown as { ui?: { notify?: (t: string, l?: string) => void } }).ui?.notify?.(
387
+ `kanboard: ${ids} was released when the last run ended — ask me to re-start it`,
388
+ "info",
389
+ );
390
+ }
391
+ } catch (error) {
392
+ debug(`resume notice failed: ${error instanceof Error ? error.message : String(error)}`);
393
+ }
394
+ }
395
+
212
396
  const client = cli!;
213
397
  const settings = readKanboardSettings(ctx.cwd);
214
398
  if (settings.archiveAfterDays > 0 || settings.retentionDays > 0) {
@@ -224,30 +408,37 @@ export default function (pi: ExtensionAPI) {
224
408
  .then((payload) => debug(`archive-sweep: ${JSON.stringify(payload)}`))
225
409
  .catch((error) => debug(`archive-sweep failed: ${error instanceof Error ? error.message : String(error)}`));
226
410
  }
227
- await runner?.onSessionStart(ctx as unknown as ExtensionContext);
228
- });
229
-
230
- let drainPending = false;
231
- pi.on("agent_end", async (event, ctx) => {
232
- runner?.onAgentEnd(event as { messages?: unknown[] }, ctx as unknown as ExtensionContext);
233
- // A -do window closes on the first real agent_end (the 150ms echo guard
234
- // inside onAgentEnd skips the previous turn's late end). The drain itself
235
- // runs at agent_settled: sending a task prompt while the turn is still
236
- // finalizing would queue it as a follow-up that never gets delivered.
237
- if (guard.onAgentEnd()) drainPending = true;
238
- });
239
-
240
- pi.on("agent_settled", async (_event, ctx) => {
241
- const reminder = reminders.takePending();
242
- if (drainPending) {
243
- drainPending = false;
244
- await drainQueueAfterDo(buildDeps(), ctx as unknown as ExtensionContext);
245
- }
246
- // A drained queue hands the session to the runner: the reminder is moot.
247
- if (reminder && (runner?.status().phase ?? "idle") === "idle") sendReminder(pi, reminder);
248
411
  });
249
412
 
250
413
  pi.on("session_shutdown", async (_event, ctx) => {
251
- await runner?.onSessionShutdown(ctx as unknown as ExtensionContext);
414
+ // Release this session's open claims so the board shows the truth. The
415
+ // in_progress → todo transition allows the system actor only (the agent
416
+ // cannot release), and release requires a comment — the next run's resume
417
+ // notice keys on it. Best effort: a dead pid is reaped with "session
418
+ // lost" anyway.
419
+ try {
420
+ const session = sessionId();
421
+ const claims = await ownClaims();
422
+ const client = cli;
423
+ const slug = projectSlug();
424
+ if (!client || !slug || claims.length === 0) return;
425
+ for (const task of claims) {
426
+ await client
427
+ .run([
428
+ "--actor", "system",
429
+ "--project", slug,
430
+ "release", task.id, "--to", "todo",
431
+ "--comment", `released: session ended mid-task (${session})`,
432
+ ], {
433
+ extraEnv: { UNIPI_KANBOARD_PROJECT: slug, UNIPI_KANBOARD_SESSION: session },
434
+ })
435
+ .then(() => debug(`released ${task.id} at shutdown`))
436
+ .catch((error) => debug(`shutdown release ${task.id} failed: ${error instanceof Error ? error.message : String(error)}`));
437
+ }
438
+ setSharedKanboardStatus({ claims: [], autowork: guard.remaining().autowork });
439
+ } catch {
440
+ // Shutdown must never hang the session teardown.
441
+ }
442
+ void ctx;
252
443
  });
253
444
  }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@pi-unipi/kanboard",
3
- "version": "3.0.0-alpha.14",
3
+ "version": "3.0.0-alpha.16",
4
4
  "description": "Kanboard v3 — deferred-work board: CLI/daemon bridge, task runner and skill",
5
5
  "type": "module",
6
6
  "main": "index.ts",
7
7
  "license": "MIT",
8
8
  "author": "Neuron Mr White",
9
9
  "scripts": {
10
- "test": "npx tsx --test tests/**/*.test.ts"
10
+ "test": "UNIPI_FUSION_CHILD= UNIPI_SUBAGENT_CHILD= UNIPI_KANBOARD_CHILD= npx tsx --test tests/*.test.ts tests/*/*.test.ts"
11
11
  },
12
12
  "repository": {
13
13
  "type": "git",
@@ -31,7 +31,7 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@pi-unipi/core": "3.0.0-alpha.14"
34
+ "@pi-unipi/core": "3.0.0-alpha.16"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@earendil-works/pi-coding-agent": "^0.87.1",
@@ -48,10 +48,10 @@
48
48
  "themes": []
49
49
  },
50
50
  "optionalDependencies": {
51
- "@pi-unipi/kanboard-linux-x64": "3.0.0-alpha.14",
52
- "@pi-unipi/kanboard-linux-arm64": "3.0.0-alpha.14",
53
- "@pi-unipi/kanboard-darwin-x64": "3.0.0-alpha.14",
54
- "@pi-unipi/kanboard-darwin-arm64": "3.0.0-alpha.14",
55
- "@pi-unipi/kanboard-win32-x64": "3.0.0-alpha.14"
51
+ "@pi-unipi/kanboard-linux-x64": "3.0.0-alpha.16",
52
+ "@pi-unipi/kanboard-linux-arm64": "3.0.0-alpha.16",
53
+ "@pi-unipi/kanboard-darwin-x64": "3.0.0-alpha.16",
54
+ "@pi-unipi/kanboard-darwin-arm64": "3.0.0-alpha.16",
55
+ "@pi-unipi/kanboard-win32-x64": "3.0.0-alpha.16"
56
56
  }
57
57
  }