@pi-unipi/kanboard 3.0.0-alpha.2 → 3.0.0-alpha.20

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,48 +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. **jev picks the mode** (one `choice` call over title + body ≤2000 chars):
43
- `direct` (small clear change) · `plan` (needs an approved plan) · `goal`
44
- (multi-turn objective with verification). jev null → `direct`; the choice is
45
- logged to `~/.unipi/logs/kanboard.log` with `UNIPI_DEBUG_KANBOARD=1`.
46
- 3. `set-run --mode`, then the task goes to the agent as a user message: title,
47
- body, last 10 activity entries, each dependency with its status and last note,
48
- and the rules (block with a comment to ask a question; never write
49
- `in_review`/`done`/`cancelled`; work only on this task).
50
- - **plan** → plan mode is entered through workflow's `unipi:plan-enter` runner
51
- first; approval stays interactive; a discarded plan releases the task to Todo
52
- with `plan discarded`.
53
- - **goal** → long-horizon's `unipi:goal-start` runner starts a goal with the
54
- task as the objective; the goal id is recorded with `set-run --goal` and
55
- completion is read back with `unipi:goal-status`.
56
- 4. Run end (a `/plan` settle after the last `agent_end`, once the agent reports
57
- idle with no queued messages): the task is re-read — if the agent blocked it,
58
- that is respected and reported (`▣ UNI-12 blocked: <comment>`) and the loop
59
- continues; otherwise `release --to in_review --comment <last assistant text
60
- ≤500 chars>`. `Esc` (aborted turn) → `release --to todo --comment "interrupted
61
- by user"` and the loop stops. Session shutdown → `release --to todo` with
62
- `session ended`.
63
- 5. After each task: `✓ UNI-12 → In Review: <first line>`, then the loop takes
64
- the next id from the session **queue** (`claim-next --id`; entries that went
65
- stale are dropped with a notice), falls back to `claim-next` while autowork
66
- is on, and stops when nothing is ready. The event loop is never blocked.
67
-
68
- Footer: `▣ UNI-12 · direct` while a task runs. The claimed task is persisted with
69
- `pi.appendEntry("unipi:kanboard-runner", …)`, so `/reload` or a resume offers to
70
- 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).
71
73
 
72
74
  ## Settings (hub section "Kanboard")
73
75
 
@@ -80,9 +82,11 @@ resume it or releases it to Todo.
80
82
  | `openBrowser` | `false` | Open the board in a browser on `open` |
81
83
  | `requireAuth` | `false` | Also require the access token on 127.0.0.1 (remote always does) |
82
84
  | `keepToken` | `false` | Reuse `<home>/token` across daemon restarts |
83
- | `queueMax` | `10` | Tasks a session may queue (0 = unlimited); passed to the CLI as `UNIPI_KANBOARD_QUEUE_MAX` |
84
- | `maxSessions` | `2` | Distinct sessions running tasks per project (`UNIPI_KANBOARD_MAX_SESSIONS`) |
85
- | `turnAddLimit` | `20` | `add` calls allowed per -do turn or runner task (0 = unlimited) |
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 |
86
90
  | *actions* | | `Open board…`, `Stop daemon`, `Summary agent command…`, `Rotate access token` |
87
91
 
88
92
  `Summary agent command…` writes through `settings set agent-command` and
@@ -201,10 +205,10 @@ The extension never edits those files — the binary owns them.
201
205
  | `UNI-5 is unreadable: … (line N)` | That task's own file is broken — repair it before moving/noting it. |
202
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. |
203
207
  | Nothing is ready | `unipi-kanboard list --ready --json` shows `waitingFor`; a cancelled dependency blocks forever — `link`/`unlink` to re-plan. |
204
- | 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). |
205
209
 
206
210
  ## Tests
207
211
 
208
212
  ```bash
209
- npm test -w packages/kanboard # bin resolution, commands, runner, settings
213
+ npm test -w packages/kanboard # bin resolution, commands, budget guard, monitor, settings
210
214
  ```
package/index.ts CHANGED
@@ -2,40 +2,57 @@
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. The board itself
9
- * is written by the Rust binary (`crates/kanboard`); this extension never edits
10
- * task files. Bash calls into the binary are gated by the write window
11
- * (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.
12
14
  */
13
15
 
14
16
  import { dirname } from "node:path";
15
17
  import { fileURLToPath } from "node:url";
16
18
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { Text } from "@earendil-works/pi-tui";
17
20
  import {
18
21
  MODULES,
19
22
  UNIPI_EVENTS,
20
23
  emitEvent,
21
24
  getPackageVersion,
25
+ getSettings,
26
+ getSharedKanboardStatus,
27
+ getSharedOwnerStatus,
22
28
  initUnipiDirs,
29
+ isChildProcess,
23
30
  registerCommandRunner,
24
- getSettings,
31
+ registerEvidenceContributor,
32
+ registerNudgeProvider,
33
+ registerProgressRenderer,
34
+ setSharedKanboardStatus,
35
+ appendProgress,
25
36
  } from "@pi-unipi/core";
26
37
 
27
38
  import { openCli, type KanboardCli } from "./src/bin.js";
28
- import { createWriteGuard } from "./src/guard.js";
39
+ import { kanboardInvocations } from "./src/guard.js";
40
+ import { maybeBadgeToolResult, registerBadgeRenderer } from "./src/badges.js";
29
41
  import {
30
- drainQueueAfterDo,
31
42
  registerKanboardCommands,
32
43
  runOpen,
33
44
  syncPiRuntime,
34
45
  runRotateTokenAction,
35
46
  runStopDaemon,
47
+ captureToBacklog,
36
48
  type CommandDeps,
37
49
  } from "./src/commands.js";
38
- import { createDebugLog, createRunner, registerPlanEventListener, type Runner } from "./src/runner.js";
50
+ import { createWriteGuard } from "./src/guard.js";
51
+ import { NOTICE_ENTRY, flushNotices, NoticeBuffer } from "./src/notice-buffer.js";
52
+ import { createKanboardMonitor } from "./src/monitor.js";
53
+ import { createDebugLog } from "./src/debug.js";
54
+ import { createProgressTracker, registerProgressReminders, ANTI_POISONING_SUFFIX } from "./src/reminders.js";
55
+ import { asTaskList, type KanboardTask } from "./src/shapes.js";
39
56
  import {
40
57
  ACTION_OPEN,
41
58
  ACTION_STOP_DAEMON,
@@ -52,8 +69,12 @@ export const SKILL_REVEAL_EVENT = "unipi:skills:reveal";
52
69
  export const KANBOARD_SKILL = "kanboard";
53
70
 
54
71
  export default function (pi: ExtensionAPI) {
55
- // One session id shared by the runner and the agent's bash calls.
72
+ // One session id shared by the agent's bash calls (refined at session_start
73
+ // from the pi session id; children keep the value they inherited).
56
74
  process.env.UNIPI_KANBOARD_SESSION ??= `pi-${process.pid}`;
75
+ // `start` claims belong to this pi process: the stale-claim reaper releases
76
+ // them to Todo when it dies (the agent's bash inherits the env).
77
+ process.env.UNIPI_KANBOARD_PID ??= String(process.pid);
57
78
  // Limits travel through the environment; refresh on load and before every
58
79
  // tool_call (see the guard registration in commands.ts).
59
80
  applyLimitEnv(readKanboardSettings());
@@ -62,14 +83,11 @@ export default function (pi: ExtensionAPI) {
62
83
 
63
84
  let cli: KanboardCli | null = null;
64
85
  let unavailable: string | null = null;
65
- let runner: Runner | null = null;
66
- const guard = createWriteGuard(
67
- () => {
68
- const status = runner?.status();
69
- return status?.phase === "running" ? status.taskId : null;
70
- },
71
- () => readKanboardSettings().turnAddLimit,
72
- );
86
+ const guard = createWriteGuard({
87
+ addLimit: () => readKanboardSettings().turnAddLimit,
88
+ doTasks: () => readKanboardSettings().doTasks,
89
+ doWrites: () => readKanboardSettings().doWrites,
90
+ });
73
91
  const sessionId = (): string => process.env.UNIPI_KANBOARD_SESSION ?? `pi-${process.pid}`;
74
92
 
75
93
  const projectSlug = (): string => {
@@ -83,8 +101,87 @@ export default function (pi: ExtensionAPI) {
83
101
  }
84
102
  };
85
103
 
86
- // Live getters: the command is registered before the binary is resolved, so
87
- // the deps object must read the current state at call time.
104
+ // ── board reads (lead monitor/evidence/holder/notice) ────────────────
105
+ const listTasks = async (args: string[] = []): Promise<KanboardTask[]> => {
106
+ const client = cli;
107
+ const slug = projectSlug();
108
+ if (!client || !slug) return [];
109
+ const payload = await client.run<unknown>(["list", ...args, "--json"], {
110
+ extraEnv: { UNIPI_KANBOARD_PROJECT: slug, UNIPI_KANBOARD_SESSION: sessionId() },
111
+ });
112
+ return asTaskList(payload).tasks;
113
+ };
114
+ const ownClaims = async (): Promise<KanboardTask[]> => {
115
+ try {
116
+ const session = sessionId();
117
+ return (await listTasks()).filter((task) => {
118
+ const run = task.run as { session?: string } | null | undefined;
119
+ return task.status === "in_progress" && run?.session === session;
120
+ });
121
+ } catch {
122
+ return [];
123
+ }
124
+ };
125
+
126
+ // ── monitor: the arbiter's kanboard nudge provider (lead only) ───────
127
+ // User-only notices queue here and flush at agent_settled (post boundary).
128
+ const pendingNotices = new NoticeBuffer();
129
+ const monitor = createKanboardMonitor({
130
+ list: () => listTasks(),
131
+ listReady: () => listTasks(["--ready"]),
132
+ session: sessionId,
133
+ ownerStatus: () => getSharedOwnerStatus(),
134
+ now: () => Date.now(),
135
+ // User-only: only QUEUE here — a sendMessage custom message would be
136
+ // converted to a user-role LLM message (never what a notice wants).
137
+ // kanboard's agent_settled handler drains the buffer (appendEntry + toast).
138
+ notify: (text, level) => {
139
+ pendingNotices.queue(text, level);
140
+ },
141
+ // The monitor turned autowork off itself (done / stalled): the guard's
142
+ // budget and the footer's `▣ autowork` flag must follow.
143
+ onAutoworkOff: () => {
144
+ guard.setAutowork(false);
145
+ void refreshHolder();
146
+ },
147
+ cliPrefix: () => {
148
+ const slug = projectSlug();
149
+ return cli && slug ? `${cli.binary.path} --actor agent --project ${slug}` : null;
150
+ },
151
+ debug,
152
+ });
153
+
154
+ const refreshHolder = async (): Promise<void> => {
155
+ try {
156
+ setSharedKanboardStatus({
157
+ claims: (await ownClaims()).map((task) => task.id),
158
+ autowork: guard.remaining().autowork,
159
+ });
160
+ } catch {
161
+ // The footer simply shows nothing until the next refresh.
162
+ }
163
+ };
164
+
165
+ if (!isChildProcess()) {
166
+ try {
167
+ registerNudgeProvider("kanboard", 50, (info) => monitor.propose(info));
168
+ } catch {
169
+ // Registration must never block module load.
170
+ }
171
+ try {
172
+ registerEvidenceContributor("kanboard", async () => ({
173
+ blocking: (await ownClaims()).map(
174
+ (task) => `${task.id} is still In Progress (claimed by this session) — finish it or move it to blocked`,
175
+ ),
176
+ notes: [],
177
+ }));
178
+ } catch {
179
+ // Registration must never block module load.
180
+ }
181
+ registerBadgeRenderer(pi);
182
+ }
183
+
184
+ // ── command plumbing ─────────────────────────────────────────────────
88
185
  const buildDeps = (): CommandDeps => ({
89
186
  get cli() {
90
187
  return cli;
@@ -94,13 +191,16 @@ export default function (pi: ExtensionAPI) {
94
191
  },
95
192
  settings: () => readKanboardSettings(process.cwd()),
96
193
  revealSkill,
97
- work: (ctx) => runner?.work(ctx) ?? Promise.resolve(),
98
- stop: (ctx) => runner?.stop(ctx),
99
- drainQueue: (ctx) => runner?.drain(ctx) ?? Promise.resolve(),
100
- status: () => runner?.status() ?? { taskId: null, mode: null, phase: "idle" },
194
+ setAutowork: (on) => {
195
+ guard.setAutowork(on);
196
+ monitor.setAutowork(on);
197
+ if (on) monitor.arm("autowork");
198
+ void refreshHolder();
199
+ },
101
200
  guard,
102
201
  session: sessionId,
103
202
  debug,
203
+ progress: (data) => appendProgress(pi, data),
104
204
  }) as CommandDeps;
105
205
 
106
206
  const revealSkill = (ctx: ExtensionContext | { cwd?: string }): void => {
@@ -119,22 +219,33 @@ export default function (pi: ExtensionAPI) {
119
219
  cli = opened;
120
220
  unavailable = null;
121
221
  debug(`binary: ${opened.binary.path} (${opened.binary.source})`);
122
- if (!runner) {
123
- runner = createRunner({
124
- pi,
125
- cli,
126
- project: projectSlug,
127
- cwd: ctx.cwd,
128
- settings: () => readKanboardSettings(ctx.cwd),
129
- debug,
130
- });
131
- registerPlanEventListener(pi, runner);
132
- }
133
222
  return true;
134
223
  };
135
224
 
225
+ registerProgressRenderer(pi);
136
226
  registerKanboardCommands(pi, buildDeps());
137
227
 
228
+ // ── API for other extensions (input-shortcuts K chord) ──────────────
229
+ // Add the editor text to this project's Backlog as a body-only task.
230
+ (globalThis as { __unipi_kanboard_api?: unknown }).__unipi_kanboard_api = {
231
+ captureToBacklog: (opts: { cwd: string; text: string }) => captureToBacklog(buildDeps(), opts),
232
+ };
233
+
234
+ // R1 progress reminders for hand-worked tasks (silent in child sessions).
235
+ registerProgressReminders(
236
+ pi,
237
+ createProgressTracker({
238
+ enabled: () => readKanboardSettings().reminders,
239
+ session: sessionId,
240
+ list: () => listTasks(),
241
+ cliPrefix: () => {
242
+ const slug = projectSlug();
243
+ return cli && slug ? `${cli.binary.path} --actor agent --project ${slug}` : null;
244
+ },
245
+ debug,
246
+ }),
247
+ );
248
+
138
249
  registerCommandRunner(ACTION_OPEN, async (ctx) => {
139
250
  const context = ctx as ExtensionContext | undefined;
140
251
  if (!context?.ui) return;
@@ -157,10 +268,78 @@ export default function (pi: ExtensionAPI) {
157
268
  await runRotateTokenAction(buildDeps(), context);
158
269
  });
159
270
 
271
+ // ── run hooks: monitor, badges, holder (lead only) ───────────────────
272
+ pi.on("before_agent_start", async (event) => {
273
+ try {
274
+ await monitor.onUserPrompt(String((event as { prompt?: unknown }).prompt ?? ""));
275
+ } catch {
276
+ // Prompt handling must never abort a turn.
277
+ }
278
+ return undefined;
279
+ });
280
+ pi.on("agent_start", () => {
281
+ try {
282
+ monitor.onAgentStart();
283
+ } catch {
284
+ // Accounting must never abort a turn.
285
+ }
286
+ });
287
+ pi.on("agent_end", async (event) => {
288
+ try {
289
+ guard.onAgentEnd();
290
+ monitor.onAgentEnd((event as { messages?: unknown[] }).messages);
291
+ } catch {
292
+ // Monitoring must never abort a turn.
293
+ }
294
+ });
295
+ // Post-boundary: entries append fine here (they are dropped inside the
296
+ // settle path), and the toast gives the notice a life outside the transcript.
297
+ pi.on("agent_settled", async (_event, ctx) => {
298
+ try {
299
+ const ui = ctx as unknown as { hasUI?: boolean; ui?: { notify?: (t: string, l?: string) => void } } | undefined;
300
+ flushNotices(
301
+ pi,
302
+ pendingNotices,
303
+ {
304
+ hasUI: ui?.hasUI,
305
+ notify: (text, level) => ui?.ui?.notify?.(text, level ?? "info"),
306
+ },
307
+ debug,
308
+ );
309
+ void refreshHolder();
310
+ } catch {
311
+ // The footer simply shows nothing until the next refresh.
312
+ }
313
+ });
314
+ pi.on("tool_result", async (event) => {
315
+ const toolEvent = event as { toolName?: string; input?: Record<string, unknown>; isError?: boolean };
316
+ try {
317
+ if (isChildProcess()) return undefined;
318
+ if (toolEvent.toolName !== "bash" && toolEvent.toolName !== "powershell") return undefined;
319
+ maybeBadgeToolResult(pi, String(toolEvent.toolName), toolEvent.input, toolEvent.isError === true);
320
+ if (toolEvent.isError) return undefined;
321
+ const invocations = kanboardInvocations(String(toolEvent.input?.command ?? ""));
322
+ if (invocations.some((inv) => inv.sub === "start" || inv.sub === "finish" || inv.sub === "move")) {
323
+ if (invocations.some((inv) => inv.sub === "start")) monitor.arm("start");
324
+ void refreshHolder();
325
+ }
326
+ } catch {
327
+ // Badges and holder refreshes must never abort a turn.
328
+ }
329
+ return undefined;
330
+ });
331
+
332
+ // ── session lifecycle ────────────────────────────────────────────────
160
333
  pi.on("session_start", async (_event, ctx) => {
161
334
  // Kanboard's own ambient children (summaries, --list-models) get this env:
162
335
  // they must not re-sync the runtime or spawn a daemon.
163
336
  if (process.env.UNIPI_KANBOARD_CHILD) return;
337
+ // Children keep the session id they inherited from the lead.
338
+ if (!isChildProcess()) {
339
+ // Step 0: reason is "startup" even for -c/-r — never branch on it.
340
+ process.env.UNIPI_KANBOARD_SESSION = `pi-${ctx.sessionManager.getSessionId()}`;
341
+ process.env.UNIPI_KANBOARD_PID = String(process.pid);
342
+ }
164
343
  initUnipiDirs();
165
344
  if (attach(ctx as unknown as ExtensionContext)) {
166
345
  const deps = buildDeps();
@@ -177,6 +356,50 @@ export default function (pi: ExtensionAPI) {
177
356
  debug(`unavailable: ${unavailable}`);
178
357
  return;
179
358
  }
359
+ // Reap claims whose pid died with the process (the runner used to do
360
+ // this): released tasks get the "session lost: <session>" activity the
361
+ // resume notice below keys on. The reaper acts as the system actor.
362
+ if (!isChildProcess()) {
363
+ try {
364
+ const reaped = await cli!.run<unknown>(["reap", "--json"], {
365
+ extraEnv: { UNIPI_KANBOARD_PROJECT: projectSlug(), UNIPI_KANBOARD_SESSION: sessionId() },
366
+ });
367
+ debug(`reap: ${JSON.stringify(reaped)}`);
368
+ } catch (error) {
369
+ debug(`reap failed: ${error instanceof Error ? error.message : String(error)}`);
370
+ }
371
+ }
372
+ void refreshHolder();
373
+
374
+ // Resume notice: claims the reaper released when a previous run of THIS
375
+ // session died ("session lost: <session> …"), or that a shutdown released
376
+ // ("released: … session ended mid-task (<session>)"). Once per start.
377
+ // Activity entries are ordered oldest-first — the LAST one must be the
378
+ // release (a task that moved on afterwards is not news).
379
+ if (!isChildProcess()) {
380
+ try {
381
+ const session = sessionId();
382
+ const stale = (await listTasks()).filter((task) => {
383
+ if (task.status !== "todo") return false;
384
+ const last = task.activity?.at(-1);
385
+ if (!last) return false;
386
+ return (
387
+ last.text.startsWith(`session lost: ${session}`) ||
388
+ last.text.includes(`released: session ended mid-task (${session})`)
389
+ );
390
+ });
391
+ if (stale.length > 0) {
392
+ const ids = stale.map((task) => task.id).join(", ");
393
+ (ctx as unknown as { ui?: { notify?: (t: string, l?: string) => void } }).ui?.notify?.(
394
+ `kanboard: ${ids} was released when the last run ended — ask me to re-start it`,
395
+ "info",
396
+ );
397
+ }
398
+ } catch (error) {
399
+ debug(`resume notice failed: ${error instanceof Error ? error.message : String(error)}`);
400
+ }
401
+ }
402
+
180
403
  const client = cli!;
181
404
  const settings = readKanboardSettings(ctx.cwd);
182
405
  if (settings.archiveAfterDays > 0 || settings.retentionDays > 0) {
@@ -192,26 +415,41 @@ export default function (pi: ExtensionAPI) {
192
415
  .then((payload) => debug(`archive-sweep: ${JSON.stringify(payload)}`))
193
416
  .catch((error) => debug(`archive-sweep failed: ${error instanceof Error ? error.message : String(error)}`));
194
417
  }
195
- await runner?.onSessionStart(ctx as unknown as ExtensionContext);
196
- });
197
-
198
- let drainPending = false;
199
- pi.on("agent_end", async (event, ctx) => {
200
- runner?.onAgentEnd(event as { messages?: unknown[] }, ctx as unknown as ExtensionContext);
201
- // A -do window closes on the first real agent_end (the 150ms echo guard
202
- // inside onAgentEnd skips the previous turn's late end). The drain itself
203
- // runs at agent_settled: sending a task prompt while the turn is still
204
- // finalizing would queue it as a follow-up that never gets delivered.
205
- if (guard.onAgentEnd()) drainPending = true;
206
- });
207
-
208
- pi.on("agent_settled", async (_event, ctx) => {
209
- if (!drainPending) return;
210
- drainPending = false;
211
- await drainQueueAfterDo(buildDeps(), ctx as unknown as ExtensionContext);
212
418
  });
213
419
 
214
420
  pi.on("session_shutdown", async (_event, ctx) => {
215
- await runner?.onSessionShutdown(ctx as unknown as ExtensionContext);
421
+ // Release this session's open claims so the board shows the truth. The
422
+ // in_progress → todo transition allows the system actor only (the agent
423
+ // cannot release), and release requires a comment — the next run's resume
424
+ // notice keys on it. Best effort: a dead pid is reaped with "session
425
+ // lost" anyway.
426
+ // Children (subagents, fusion sidekicks, kanboard's own helpers) inherit
427
+ // the lead's session id: their shutdown must never release the lead's
428
+ // claims (a finished subagent used to bounce the lead's task to Todo).
429
+ if (isChildProcess() || process.env.UNIPI_KANBOARD_CHILD) return;
430
+ try {
431
+ const session = sessionId();
432
+ const claims = await ownClaims();
433
+ const client = cli;
434
+ const slug = projectSlug();
435
+ if (!client || !slug || claims.length === 0) return;
436
+ for (const task of claims) {
437
+ await client
438
+ .run([
439
+ "--actor", "system",
440
+ "--project", slug,
441
+ "release", task.id, "--to", "todo",
442
+ "--comment", `released: session ended mid-task (${session})`,
443
+ ], {
444
+ extraEnv: { UNIPI_KANBOARD_PROJECT: slug, UNIPI_KANBOARD_SESSION: session },
445
+ })
446
+ .then(() => debug(`released ${task.id} at shutdown`))
447
+ .catch((error) => debug(`shutdown release ${task.id} failed: ${error instanceof Error ? error.message : String(error)}`));
448
+ }
449
+ setSharedKanboardStatus({ claims: [], autowork: guard.remaining().autowork });
450
+ } catch {
451
+ // Shutdown must never hang the session teardown.
452
+ }
453
+ void ctx;
216
454
  });
217
455
  }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@pi-unipi/kanboard",
3
- "version": "3.0.0-alpha.2",
3
+ "version": "3.0.0-alpha.20",
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.2"
34
+ "@pi-unipi/core": "3.0.0-alpha.20"
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.2",
52
- "@pi-unipi/kanboard-linux-arm64": "3.0.0-alpha.2",
53
- "@pi-unipi/kanboard-darwin-x64": "3.0.0-alpha.2",
54
- "@pi-unipi/kanboard-darwin-arm64": "3.0.0-alpha.2",
55
- "@pi-unipi/kanboard-win32-x64": "3.0.0-alpha.2"
51
+ "@pi-unipi/kanboard-linux-x64": "3.0.0-alpha.20",
52
+ "@pi-unipi/kanboard-linux-arm64": "3.0.0-alpha.20",
53
+ "@pi-unipi/kanboard-darwin-x64": "3.0.0-alpha.20",
54
+ "@pi-unipi/kanboard-darwin-arm64": "3.0.0-alpha.20",
55
+ "@pi-unipi/kanboard-win32-x64": "3.0.0-alpha.20"
56
56
  }
57
57
  }