@abelxiaoxing/cadence 2.0.20 → 2.0.22

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.
@@ -0,0 +1,114 @@
1
+ # Cadence conversation mode
2
+
3
+ In a trusted Pi terminal or a WebUI conversation in an explicitly selected project, enter `/cadence <goal>` once (or `/cadence` to discuss the goal).
4
+ Cadence stays enabled for the entire conversation, including after a goal finishes.
5
+ Continue using normal messages; do not repeat the command for clarification or another goal.
6
+ Type `退出 Cadence` or `exit cadence` (in Pi also `/cadence exit`) to leave the mode explicitly.
7
+ Leaving, closing Pi/browser and switching conversations detach; they do not cancel accepted work.
8
+ Browser conversation mode is retained by the project owner, not by a browser-only toggle, and works without a live Pi terminal.
9
+
10
+ ## Normal path
11
+
12
+ 1. Cadence delegates focused readonly repository investigations, reuses existing project documentation, and consolidates questions in the main conversation.
13
+ 2. Discuss requirements and decisions until the implementation and acceptance criteria are clear.
14
+ 3. Cadence presents one readable plan: scope, dependencies, setup, baseline checks, acceptance checks, repair budget and delivery policy.
15
+ 4. Type `按计划实施` after the plan to authorize those exact bytes.
16
+ In the browser, click **Implement this plan** or send that exact approval phrase for the currently displayed plan.
17
+ In Pi, the Start tool can alternatively present one native confirmation of the complete plan.
18
+ Native confirmation retains its raw-terminal guard.
19
+ Quoted/generated text, an old session entry and vague agreement are not approval; browser authentication alone is not consent.
20
+ 5. The persistent owner implements, reviews, verifies and delivers within that boundary.
21
+ Routine internal steps do not ask for more approval.
22
+ 6. Completion returns the conversation to Cadence **ready**, not ordinary mode.
23
+ Ask for status, more detail, cancellation, or the next goal normally.
24
+
25
+ Native mode is branch-aware; browser mode follows its server-owned conversation identity.
26
+ A saved native mode is active only in a trusted interactive terminal; print/RPC sessions keep ordinary tools and can still exit with `/cadence exit`.
27
+ In Pi, the agent panel lists workflow subagents and opens their transcripts; `cadence_status` can read one step's transcript.
28
+ Resume and compaction retain the mode/context, not execution grants.
29
+ Opening a different conversation does not enable Cadence there.
30
+ Restore never replays a command or automatically resumes an interrupted queue.
31
+ When an observation reply is lost, ask for status; do not infer that the action was absent.
32
+
33
+ ## Models and project knowledge
34
+
35
+ The first native use defaults to the current Pi provider/model/API/thinking selection.
36
+ The selected preference is remembered in `<agent-dir>/cadence/settings.json` (normally `~/.pi/agent/cadence/settings.json`) and reused across projects.
37
+ Ask Cadence to change its model in Pi, or use **Model** in the browser.
38
+ The browser restores an available saved preference on explicit Send; reads/login do not install a choice.
39
+ If no usable preference exists, choose once; an unreadable preference file falls back to the current Pi model, and choosing a model rewrites it.
40
+ An accepted run keeps its original exact model.
41
+ An unavailable remembered model is not silently substituted.
42
+ Pi's original model and authentication sources remain authoritative; Cadence does not copy credentials.
43
+
44
+ Repository investigation and discussion do not edit business code.
45
+ Approved work publishes a managed region in `.cadence/project.md` and readable plan/result notes under `.cadence/assistant/workflows/<run-id>/`.
46
+ Existing human text outside the managed region is preserved.
47
+ Existing architecture and development documents should be referenced, not duplicated.
48
+ Each worker receives the approved goal/design/decisions/acceptance and its exact assignment; oversized context is refused rather than silently clipped.
49
+ Private proposals, grants, native/auth outcomes and transcripts stay outside the checkout.
50
+ Markdown is not execution authority.
51
+ Old task summaries and history are neither imported nor reset.
52
+
53
+ ## Execution and delivery
54
+
55
+ The plan chooses one delivery policy:
56
+
57
+ - **Local merge:** requires an existing Git branch and configured commit identity.
58
+ Independent tasks use separate worktrees, up to two at once; dependencies are applied before their consumers.
59
+ The owner commits only declared file changes, integrates them into a separate candidate, runs independent readonly Agent review and real checks, then fast-forwards the unchanged target branch.
60
+ Local task commits and the merge are included in the plan approval.
61
+ Git hooks and commit signing are disabled for these internal commits; verification is explicitly declared instead.
62
+ No remote push occurs.
63
+ - **Working copy:** explicit direct host-tool editing, serialized, including for non-Git directories.
64
+ No commit or merge.
65
+ Failed or canceled work leaves actual edits in place; this is not transactional application or a sandbox.
66
+
67
+ A local-merge plan does not adopt existing dirty inputs into its committed baseline.
68
+ Dirty declared targets refuse before implementation; unrelated user changes made during a run are preserved and do not block integration (Git refuses a genuine overlap).
69
+ A write path naming a directory covers the files below it; in Git, working-copy edits outside the declared writes fail the run (the edits stay).
70
+ Unresolved conflicts or a changed target stop integration.
71
+ Cadence never resets, stashes, force-pushes or silently cleans uncertain worktrees.
72
+ Ignored generated Markdown remains ignored and is published without forcing it into Git.
73
+ Clean worktrees are removed after a successful merge (plain `git worktree remove`, which also deletes their ignored setup output such as `node_modules`); dirty or moved ones and all results are retained.
74
+ Only one approved implementation runs at a time; approving a second while one is active is refused with `conflict`.
75
+ The 90-minute budget starts when the run acquires the checkout; Cancel/Stop never interrupt the final fast-forward (a hung `git merge` therefore delays Stop until Git exits).
76
+ Local-merge plans cannot declare files that Git ignores; use working-copy delivery for those.
77
+ After an owner restart, an unfinished run is shown as `unknown` with its retained worktrees; it is never resumed.
78
+ Credential-looking text in plans and research questions is shown and approved redacted.
79
+
80
+ An isolated worktree does **not** inherit ignored `node_modules`, build output, credentials or profiles.
81
+ Investigate prerequisites during planning.
82
+ If dependencies/setup are needed, include the exact commands in the plan for explicit approval.
83
+ No dependency/browser download or source-profile copying is implicit.
84
+ Baseline checks are separate from acceptance checks that need newly implemented files.
85
+ Failed declared baseline checks stop before editing.
86
+ At most two approved repair rounds may follow failed review/checks; repairs cannot expand scope or weaken acceptance.
87
+ Final candidate checks must pass before merge.
88
+ Post-merge failures remain failures and report the actual merge commit; no rollback is fabricated.
89
+ Automatic review is never recorded as human review.
90
+
91
+ To request orderly closure, ask Cadence to cancel in Pi, or use **Cancel workflow — request stop** in the browser (the browser coordinator cannot cancel).
92
+ A pending or unknown cancellation is not reported as stopped.
93
+ Failures, timeouts and unknown process/auth/storage outcomes remain distinct; unknown resources retain fences for explicit informed recovery.
94
+
95
+ ## Service and compatibility
96
+
97
+ An explicit native mode entry/current user Send may start or reuse its local project owner on demand.
98
+ It does not install a system service, enable boot startup, select another account's credentials or expose a public listener.
99
+ Pi says once which command stops an owner it started; when Pi runs on Bun, Node must be on `PATH`.
100
+ An existing owner/configuration is reused, not silently replaced after a connection failure.
101
+ System-service installation and remote access remain separate explicit operations described in [Service management](service-management.md) and [Remote access](remote-access.md).
102
+
103
+ `/cadence-inspect` retains the previous advanced task/history UI for diagnostics and legacy workflows; it is not needed for conversation mode.
104
+ The WebUI uses the same execution engine with a separate, context-bound browser confirmation path.
105
+ Its main composer stays in the same conversation; the plan card, workflow progress and actual merge outcomes appear inline.
106
+ Research, implementation and review subagents are listed in the lower-left **Subagents** dock, together with legacy task children; selecting one (or **Open subagent context** on a step) opens its full transcript and retained result in the main area, and **Back to conversation** returns.
107
+ Active workflows are listed under **Running conversations** with **Cancel workflow — request stop**; this includes native-started workflows, and an unavailable observation is not proof of no work.
108
+ **Legacy task** retains the old create/plan/Save/Start/check/human-Review route explicitly, rather than making `/cadence` create a legacy task.
109
+ Existing browser conversations enter the new mode only on explicit Send/activation; old tasks and Pi transcripts are not converted or imported.
110
+ Approval grants are neither stored in the browser nor restored after restart.
111
+ Losing a response only observes its original command/run identity; it never retries execution.
112
+ Exit does not stop accepted work, and **Cancel workflow — request stop** remains independent of conversation mode.
113
+ There is no generic browser shell/PTY, service management/recovery or checkpoint pause/resume feature.
114
+ Conversation response completion is distinct from workflow completion; read the workflow card for actual delivery/check outcomes.
@@ -1,7 +1,9 @@
1
1
  # Explicit service management
2
2
 
3
- The native `/cadence` view and browser are clients of the same owner, started explicitly or by the [background service](#background-service).
4
- Opening either view, extension discovery, login and package installation do not start it.
3
+ Native conversation mode and the browser use the shared project-owner implementation.
4
+ Extension discovery, login and package installation do not start an owner.
5
+ Explicit `/cadence` mode/current user Send can start or reuse a local owner without installing a boot service; see [Conversation mode](conversation-mode.md).
6
+ The optional [background service](#background-service) remains an explicit management operation.
5
7
  Use one coordination state-home for the checkout; a different state-home is not a recovery route.
6
8
  Stop older Cadence sessions before starting the shared service.
7
9
 
@@ -111,13 +113,13 @@ For an explicit single-project definition, the older guards remain: no SDK means
111
113
 
112
114
  While no service is registered, Pi's session-start card shows a separate warning naming `cadence server install` for an installed package copy (`node <copy>/src/service-cli.mjs server install` for Pi's managed copy, which puts no bin on `PATH`); a checkout loaded with `pi -e` stays quiet.
113
115
  It is a warning rather than part of the info card because Pi's TUI replaces one info status with the next.
114
- `/cadence` names the same command when it finds no owner.
116
+ The legacy `/cadence-inspect` client names the same management command when no owner exists; daily `/cadence` instead uses explicit on-demand project startup, without requiring a boot service.
115
117
  A machine without a supported user service manager and `CADENCE_AUTOSTART=0` keep both quiet; with `CADENCE_LINGER=0` they suggest `--no-linger`.
116
118
 
117
119
  ### One copy for Pi and the service
118
120
 
119
121
  After `npm install -g`, `pi install "$(npm root -g)/@abelxiaoxing/cadence"` records that path and loads it in place, so an npm upgrade updates the service and native `/cadence` together.
120
- Pi's own package install (`pi install npm:@abelxiaoxing/cadence`) also loads the native client, but its copy puts no `cadence` on `PATH`; register its service with `node ~/.pi/agent/npm/node_modules/@abelxiaoxing/cadence/src/service-cli.mjs server install`.
122
+ Pi's own package install (`pi install npm:@abelxiaoxing/cadence`) also loads the native client, but its copy puts no `cadence` on `PATH`; if you want the optional boot service, register it with `node ~/.pi/agent/npm/node_modules/@abelxiaoxing/cadence/src/service-cli.mjs server install`.
121
123
  Keep one copy: two copies drift apart on upgrade, and a native client refuses an owner whose service contract differs from its own.
122
124
  A unit registered by an earlier version's Pi install hook keeps running; `cadence server restart` from the copy you keep rewrites it, and `pi update` no longer restarts it.
123
125
  Opening the private link once leaves an HttpOnly cookie in that browser; the address without the token only explains how to get the link.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.0.20",
4
- "description": "Shared Pi task workspace: native terminal and WebUI, persistent service, checks and human review.",
3
+ "version": "2.0.22",
4
+ "description": "Conversation-driven Pi workspace: persistent native and WebUI workflows, explicit plan approval, checks and local delivery.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "engines": {
@@ -71,7 +71,12 @@
71
71
  "licenses",
72
72
  "src/conversation-context.mjs",
73
73
  "src/conversation-resources.mjs",
74
- "src/service/contracts/workbench.ts"
74
+ "src/service/contracts/workbench.ts",
75
+ "src/cadence-mode.ts",
76
+ "src/cadence-preferences.ts",
77
+ "src/service/contracts/workflow.ts",
78
+ "src/cadence-instructions.ts",
79
+ "src/coordinator-tools.mjs"
75
80
  ],
76
81
  "pi": {
77
82
  "extensions": [
@@ -1,12 +1,19 @@
1
1
  /** Cadence service children on the background-agent panel. Observation only:
2
2
  * a Pi TUI session attaches to the owner already running for its workspace
3
- * (never starting one), polls the active roster and task snapshots, and
4
- * announces each child run on Pi's `subagent:*` bus. Reads go through the
3
+ * (never starting one), polls the active task roster and task snapshots plus
4
+ * the conversation-workflow roster and runs, and announces each child run
5
+ * (task children and workflow research/implementation/review subagents) on
6
+ * Pi's `subagent:*` bus. Reads go through the
5
7
  * typed ServiceClient; nothing here starts, cancels, retries or keeps work
6
8
  * alive, and leaving the session only detaches. */
7
9
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
10
  import { SUBAGENT_EVENTS, SUBAGENT_VIEW } from "./agent-panel-model.ts";
9
11
  import { departure, NativeConnection } from "./native-client.ts";
12
+ import type { ChatTurn } from "./service/contracts/workbench.ts";
13
+ import type {
14
+ WorkflowRun,
15
+ WorkflowStep,
16
+ } from "./service/contracts/workflow.ts";
10
17
  import type { ServiceClient } from "./service-client.ts";
11
18
  import {
12
19
  type ContentRef,
@@ -25,6 +32,8 @@ export interface FeedConnection {
25
32
  refresh(): Promise<unknown>;
26
33
  compatible(): boolean;
27
34
  detach(): Promise<void>;
35
+ /** Drop an attachment whose owner the registry proves gone or replaced. */
36
+ forgetSuperseded?(cwd: string): boolean;
28
37
  }
29
38
  /** Readonly ServiceClient reads only: no command, preflight or Cancel. */
30
39
  export type FeedClient = Pick<
@@ -36,6 +45,7 @@ export type FeedClient = Pick<
36
45
  | "tools"
37
46
  | "contents"
38
47
  | "detail"
48
+ | "workbenchRead"
39
49
  >;
40
50
  export interface CadenceFeedOptions {
41
51
  connection?: () => FeedConnection;
@@ -56,7 +66,7 @@ export const FEED_TIMING: FeedTiming = {
56
66
  idleMs: LIMITS.heartbeatMs,
57
67
  retryMs: 15_000,
58
68
  };
59
- /** Retained reads are paged; a child larger than this stays in /cadence History. */
69
+ /** Retained reads are paged; a child larger than this stays in /cadence-inspect History. */
60
70
  const MAX_PAGES = 50;
61
71
  const MAX_DETAIL_STEPS = 8;
62
72
  /** Characters of one field shown in the panel; the rest stays retained. */
@@ -64,6 +74,14 @@ const TEXT_CAP = 64 * 1024;
64
74
  const CACHE_CHARS = 16 * 1024 * 1024;
65
75
  /** Snapshots after an episode drained, while its children still look unsettled. */
66
76
  const DRAIN_LOOKS = 5;
77
+ /** A running workflow subagent not shown in a view refreshes its activity at
78
+ * most this often; its retained transcript is one bounded owner file. */
79
+ const WORKFLOW_ACTIVITY_MS = 10_000;
80
+ const WORKFLOW_KINDS: Partial<Record<WorkflowStep["kind"], string>> = {
81
+ research: "Research",
82
+ implementation: "Implementation",
83
+ review: "Review",
84
+ };
67
85
 
68
86
  type Child = {
69
87
  id: string;
@@ -84,6 +102,14 @@ type Child = {
84
102
  failedSeq?: string;
85
103
  /** Final transcript messages already announced. */
86
104
  sent: number;
105
+ /** A conversation-workflow subagent, read through workflow transcripts. */
106
+ workflow?: {
107
+ runId: string;
108
+ stepId: string;
109
+ /** The final transcript was announced after the step ended. */
110
+ done?: boolean;
111
+ readAt?: number;
112
+ };
87
113
  };
88
114
  type Tool = Extract<HistoryRecord, { kind: "tool" }>;
89
115
  type Block = { index: number; ref: ContentRef };
@@ -176,6 +202,74 @@ function parseArgs(text: string | undefined): object {
176
202
  return {};
177
203
  }
178
204
  }
205
+ const capped = (text: string) =>
206
+ text.length > TEXT_CAP
207
+ ? `${text.slice(0, TEXT_CAP)}\n… (truncated; the project owner retains the full text)`
208
+ : text;
209
+ /** A workflow step transcript in Pi's message shapes. Each assistant message
210
+ * carries its tool calls, followed by their results; while the turn runs, its
211
+ * last group may still grow and is a streaming snapshot. */
212
+ export function turnMessages(
213
+ turn: ChatTurn,
214
+ finished: boolean,
215
+ ): { messages: object[]; partial?: object } {
216
+ const messages: object[] = [];
217
+ let group:
218
+ | { assistant: { role: string; content: object[] }; results: object[] }
219
+ | undefined;
220
+ const close = () => {
221
+ if (group) messages.push(group.assistant, ...group.results);
222
+ group = undefined;
223
+ };
224
+ for (const item of turn.items) {
225
+ if (item.role === "user") {
226
+ close();
227
+ messages.push({
228
+ role: "user",
229
+ content: [{ type: "text", text: capped(item.text) }],
230
+ });
231
+ } else if (item.role === "assistant") {
232
+ close();
233
+ group = {
234
+ assistant: {
235
+ role: "assistant",
236
+ content: item.text ? [{ type: "text", text: capped(item.text) }] : [],
237
+ },
238
+ results: [],
239
+ };
240
+ } else {
241
+ group ??= { assistant: { role: "assistant", content: [] }, results: [] };
242
+ const name = item.name || "tool";
243
+ group.assistant.content.push({
244
+ type: "toolCall",
245
+ id: item.id,
246
+ name,
247
+ arguments: parseArgs(item.args),
248
+ });
249
+ group.results.push({
250
+ role: "toolResult",
251
+ toolCallId: item.id,
252
+ toolName: name,
253
+ content: [{ type: "text", text: capped(item.text) }],
254
+ isError: item.error,
255
+ });
256
+ }
257
+ }
258
+ if (finished || !group) {
259
+ close();
260
+ return { messages };
261
+ }
262
+ return { messages, partial: group.assistant };
263
+ }
264
+ function turnWorking(turn: ChatTurn, finished: boolean): string {
265
+ const tools = turn.items.filter((i) => i.role === "tool");
266
+ const last = tools.at(-1);
267
+ if (!last) return "Working";
268
+ if (!finished && turn.items.at(-1) === last && !last.text && !last.error)
269
+ return `Running ${last.name || "tool"}`;
270
+ const n = tools.length;
271
+ return `Working · ${n} tool call${n === 1 ? "" : "s"} (last: ${last.name || "tool"})`;
272
+ }
179
273
 
180
274
  class Feed {
181
275
  private client: FeedClient | undefined;
@@ -192,6 +286,9 @@ class Feed {
192
286
  string,
193
287
  { taskId: string; drained: number }
194
288
  >();
289
+ /** Conversation workflow → consecutive unreadable looks, followed until
290
+ * its run is observed finished. */
291
+ private readonly workflows = new Map<string, number>();
195
292
  constructor(
196
293
  private readonly pi: ExtensionAPI,
197
294
  private readonly cwd: string,
@@ -245,13 +342,19 @@ class Feed {
245
342
  next = await this.observe(this.client);
246
343
  } catch {
247
344
  // Absent, stopped, restarted or incompatible owner: detach and look
248
- // again later. Observation never starts one.
345
+ // again later. Observation never starts one. An owner the registry
346
+ // proves gone or replaced cannot accept a detach (a restarted one on the
347
+ // same port refuses the old capability), so its attachment is dropped.
249
348
  this.client = undefined;
250
- await this.connection.detach().catch(() => {});
349
+ if (!this.connection.forgetSuperseded?.(this.cwd))
350
+ await this.connection.detach().catch(() => {});
251
351
  // Still no compatible owner a whole retry after losing it: the children
252
352
  // followed so far can no longer be observed from this session.
253
- if (attaching)
353
+ if (attaching) {
254
354
  this.abandon([...this.episodes.keys()], "owner unavailable");
355
+ for (const runId of [...this.workflows.keys()])
356
+ this.abandonWorkflow(runId, "owner unavailable");
357
+ }
255
358
  } finally {
256
359
  this.busy = false;
257
360
  }
@@ -291,12 +394,183 @@ class Feed {
291
394
  this.abandon([runId], "no settled row after the run ended");
292
395
  }
293
396
  }
397
+ await this.observeWorkflows(client, ends);
398
+ if (this.stopped) return this.timing.activeMs;
294
399
  await this.refreshActivity(client);
295
400
  await this.refreshTranscript(client);
296
401
  // Ends follow the transcript so its last streaming snapshot is replaced
297
402
  // by the final message rather than kept beside it.
298
403
  for (const end of ends) this.emit("end", end);
299
- return this.episodes.size ? this.timing.activeMs : this.timing.idleMs;
404
+ return this.episodes.size || this.workflows.size
405
+ ? this.timing.activeMs
406
+ : this.timing.idleMs;
407
+ }
408
+
409
+ /** Conversation-workflow subagents: the live roster names runs, each run
410
+ * read names its steps' child IDs. Readonly; an older owner without these
411
+ * reads leaves only task children. */
412
+ private async observeWorkflows(
413
+ client: FeedClient,
414
+ ends: object[],
415
+ ): Promise<void> {
416
+ if (typeof client.workbenchRead !== "function") return;
417
+ const signal = this.abort.signal;
418
+ const roster = await client.workbenchRead(
419
+ { kind: "workflow-active" },
420
+ signal,
421
+ );
422
+ if (this.stopped) return;
423
+ const live = new Set<string>();
424
+ if (roster.kind === "ok" && roster.value.kind === "workflow-active")
425
+ for (const run of roster.value.runs) {
426
+ live.add(run.id);
427
+ if (!this.workflows.has(run.id)) this.workflows.set(run.id, 0);
428
+ }
429
+ for (const [runId, misses] of [...this.workflows]) {
430
+ const reply = await client.workbenchRead(
431
+ { kind: "workflow", id: runId },
432
+ signal,
433
+ );
434
+ if (this.stopped) return;
435
+ if (
436
+ reply.kind === "error" ||
437
+ reply.value.kind !== "workflow" ||
438
+ reply.value.response.type !== "run" ||
439
+ reply.value.response.run.id !== runId
440
+ ) {
441
+ if (misses + 1 >= DRAIN_LOOKS)
442
+ this.abandonWorkflow(runId, "workflow not readable");
443
+ else this.workflows.set(runId, misses + 1);
444
+ continue;
445
+ }
446
+ this.workflows.set(runId, 0);
447
+ const run = reply.value.response.run;
448
+ const open =
449
+ live.has(runId) || ["queued", "running"].includes(run.status);
450
+ for (const step of run.steps) this.followStep(run, step, open, ends);
451
+ if (!open) this.workflows.delete(runId);
452
+ }
453
+ }
454
+ private followStep(
455
+ run: WorkflowRun,
456
+ step: WorkflowStep,
457
+ open: boolean,
458
+ ends: object[],
459
+ ): void {
460
+ const kind = WORKFLOW_KINDS[step.kind];
461
+ if (!step.childRunId || !kind) return;
462
+ const id = step.childRunId;
463
+ // A step still marked running in a finished run did not report its end.
464
+ const outcome =
465
+ step.status === "running" ? (open ? null : "unknown") : step.status;
466
+ let child = this.state.children.get(id);
467
+ if (!child) {
468
+ child = {
469
+ id,
470
+ label: step.id,
471
+ runId: `workflow:${run.id}`,
472
+ storeId: "",
473
+ seq: "",
474
+ lifecycle: outcome ? "settled" : "running",
475
+ ended: false,
476
+ activity: "",
477
+ sent: 0,
478
+ workflow: { runId: run.id, stepId: step.id },
479
+ };
480
+ this.state.children.set(id, child);
481
+ this.emit("start", {
482
+ id,
483
+ label: step.id,
484
+ kind,
485
+ // A subagent first seen settled ran before this session looked.
486
+ startedAt: outcome ? null : this.now(),
487
+ });
488
+ }
489
+ if (child.ended) return;
490
+ if (!outcome) {
491
+ this.activity(child, child.working ?? `Working · ${run.phase}`);
492
+ return;
493
+ }
494
+ child.lifecycle = "settled";
495
+ this.activity(child, outcome);
496
+ child.ended = true;
497
+ ends.push({
498
+ id,
499
+ status:
500
+ outcome === "completed"
501
+ ? "done"
502
+ : outcome === "canceled"
503
+ ? "cancelled"
504
+ : "error",
505
+ endedAt: this.now(),
506
+ ...(outcome === "completed" || outcome === "canceled"
507
+ ? {}
508
+ : { error: `${child.label} · ${outcome}` }),
509
+ });
510
+ }
511
+ private abandonWorkflow(runId: string, why: string): void {
512
+ this.workflows.delete(runId);
513
+ for (const child of this.state.children.values()) {
514
+ if (child.workflow?.runId !== runId || child.ended) continue;
515
+ this.activity(child, "outcome not observed");
516
+ child.ended = true;
517
+ this.emit("end", {
518
+ id: child.id,
519
+ status: "error",
520
+ endedAt: this.now(),
521
+ error: `${child.label} · outcome not observed here (${why}); ask cadence_status or open the WebUI`,
522
+ });
523
+ }
524
+ }
525
+ /** Reads one workflow step transcript; undefined when it is unreadable. */
526
+ private async workflowTurn(
527
+ client: FeedClient,
528
+ child: Child,
529
+ ): Promise<ChatTurn | null | undefined> {
530
+ const w = child.workflow;
531
+ if (!w || typeof client.workbenchRead !== "function") return undefined;
532
+ w.readAt = this.now();
533
+ const reply = await client.workbenchRead(
534
+ { kind: "workflow-transcript", id: w.runId, stepId: w.stepId },
535
+ this.abort.signal,
536
+ );
537
+ if (
538
+ reply.kind === "error" ||
539
+ reply.value.kind !== "workflow-transcript" ||
540
+ reply.value.runId !== w.runId ||
541
+ reply.value.stepId !== w.stepId
542
+ )
543
+ return undefined;
544
+ return reply.value.turn;
545
+ }
546
+ private async refreshWorkflowTranscript(
547
+ client: FeedClient,
548
+ child: Child,
549
+ ): Promise<void> {
550
+ const w = child.workflow;
551
+ if (!w || w.done || child.failedSeq !== undefined) return;
552
+ const turn = await this.workflowTurn(client, child);
553
+ if (this.stopped) return;
554
+ if (turn === undefined) {
555
+ // Reopening the view retries, like a failed task transcript read.
556
+ child.failedSeq = "workflow";
557
+ return;
558
+ }
559
+ if (!turn) return;
560
+ const finished = !["queued", "running"].includes(turn.status);
561
+ const built = turnMessages(turn, finished);
562
+ child.working = turnWorking(turn, finished);
563
+ if (!child.ended) this.activity(child, child.working);
564
+ for (let i = child.sent; i < built.messages.length; i++)
565
+ this.emit("message", { id: child.id, message: built.messages[i] });
566
+ child.sent = Math.max(child.sent, built.messages.length);
567
+ if (built.partial)
568
+ this.emit("message", {
569
+ id: child.id,
570
+ message: built.partial,
571
+ streaming: true,
572
+ });
573
+ if (finished && child.ended) w.done = true;
300
574
  }
301
575
 
302
576
  /** Announce this episode's children; true while any still looks unsettled. */
@@ -381,7 +655,7 @@ class Feed {
381
655
  }
382
656
  /** Stop following these episodes. Their unsettled children end as errors
383
657
  * that say the outcome was not observed, instead of spinning as running for
384
- * the rest of the session; /cadence History keeps the actual outcome. */
658
+ * the rest of the session; /cadence-inspect History keeps the actual outcome. */
385
659
  private abandon(runIds: string[], why: string): void {
386
660
  for (const runId of runIds) {
387
661
  this.episodes.delete(runId);
@@ -393,7 +667,7 @@ class Feed {
393
667
  id: child.id,
394
668
  status: "error",
395
669
  endedAt: this.now(),
396
- error: `${child.label} · outcome not observed here (${why}); see /cadence History`,
670
+ error: `${child.label} · outcome not observed here (${why}); see /cadence-inspect History`,
397
671
  });
398
672
  }
399
673
  }
@@ -440,6 +714,23 @@ class Feed {
440
714
  /** Latest tool for running children not shown in a view (that read covers it). */
441
715
  private async refreshActivity(client: FeedClient): Promise<void> {
442
716
  for (const child of this.state.children.values()) {
717
+ if (child.workflow) {
718
+ if (
719
+ child.ended ||
720
+ child.id === this.state.viewing ||
721
+ !this.workflows.has(child.workflow.runId) ||
722
+ this.now() - (child.workflow.readAt ?? 0) < WORKFLOW_ACTIVITY_MS
723
+ )
724
+ continue;
725
+ const turn = await this.workflowTurn(client, child);
726
+ if (this.stopped || !turn) continue;
727
+ child.working = turnWorking(
728
+ turn,
729
+ !["queued", "running"].includes(turn.status),
730
+ );
731
+ this.activity(child, child.working);
732
+ continue;
733
+ }
443
734
  if (
444
735
  child.ended ||
445
736
  child.lifecycle !== "running" ||
@@ -459,6 +750,7 @@ class Feed {
459
750
  private async refreshTranscript(client: FeedClient): Promise<void> {
460
751
  const id = this.state.viewing;
461
752
  const child = id === undefined ? undefined : this.state.children.get(id);
753
+ if (child?.workflow) return this.refreshWorkflowTranscript(client, child);
462
754
  if (
463
755
  !child ||
464
756
  child.transcriptSeq === child.seq ||
@@ -539,7 +831,7 @@ class Feed {
539
831
  }
540
832
  // One detail page can exceed the cap on its own, with no cursor left.
541
833
  if (cursor || text.length > TEXT_CAP)
542
- text = `${text.slice(0, TEXT_CAP)}\n… (truncated; the full text is in /cadence History)`;
834
+ text = `${text.slice(0, TEXT_CAP)}\n… (truncated; the full text is in /cadence-inspect History)`;
543
835
  this.state.remember(key, text);
544
836
  return text;
545
837
  }
@@ -0,0 +1,7 @@
1
+ /** Shared conversation policy; clients supply distinct human-consent adapters. */
2
+ export const CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
3
+ You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
4
+ For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
5
+ Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.
6
+ Present the returned complete plan and invite a single clear execution approval (the user can type 按计划实施). cadence_start binds the exact displayed plan and obtains fresh user consent; never interpret a vague acknowledgement as approval. No further confirmations are needed for the approved bounded pipeline. No push, publication, deployment, recursive delegation or scope expansion. If a material decision changes, revise the plan and seek fresh approval.
7
+ During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;