@abelxiaoxing/cadence 2.1.13 → 2.2.1

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.
@@ -64,6 +64,12 @@ Browsing, reconnecting and choosing a model alone never start the execution serv
64
64
 
65
65
  ## Messages while a reply is running
66
66
 
67
+ An ordinary browser turn starts independently of turns in other Pi sessions, even in the same directory.
68
+ **Starting** means the service has accepted the turn and is preparing it, not that it is queued or the model has replied.
69
+ You can stop it without stopping the other sessions.
70
+ Only one browser run at a time is allowed in a session.
71
+ If the owner refuses a new Send at capacity, no turn is created; your draft stays editable and nothing sends it later.
72
+
67
73
  The service accepts a further message for a reply that is still running, in one of two ways.
68
74
  A **steer** reaches the model at its next opportunity, after the tool calls in progress and before its next request, and continues the conversation as its own turn from there.
69
75
  A **queued** message waits and is sent once the reply has ended normally.
@@ -130,8 +136,8 @@ With no choice and no saved preference, Send opens the model list and continues
130
136
  Closing the picker or stopping/replacing that service ends the unsent continuation; your draft stays, and choosing a model never restarts a stopped service.
131
137
  Exiting Cadence changes mode, not your pending model choice.
132
138
  If no usable preference exists, choose once; an unreadable preference file falls back to the current Pi model, and choosing a model rewrites it.
133
- An accepted message or workflow keeps its original directory and exact model, including while queued.
134
- Different subdirectories of one repository can have independent conversations while sharing one checkout owner and execution gate.
139
+ An accepted message or workflow keeps its original directory and exact model.
140
+ Conversations in different subdirectories of one checkout share the same owner, not one working directory.
135
141
  Tools and check commands use the conversation directory; a plan's declared write paths stay relative to the displayed checkout root, including in isolated Git worktrees.
136
142
  Changing the current conversation's model makes its older unaccepted plan require fresh validation and approval in the browser, not another chat message; changing another conversation's model does not.
137
143
  An unavailable remembered model is not silently substituted.
@@ -162,7 +168,7 @@ The plan chooses one delivery policy:
162
168
  Local task commits and the merge are included in the plan approval.
163
169
  Git hooks and commit signing are disabled for these internal commits; verification is explicitly declared instead.
164
170
  No remote push occurs.
165
- - **Working copy:** explicit direct host-tool editing, serialized, including for non-Git directories.
171
+ - **Working copy:** explicit direct host-tool editing, serialized among workflows, including for non-Git directories.
166
172
  No commit or merge.
167
173
  Failed or canceled work leaves actual edits in place; this is not transactional application or a sandbox.
168
174
 
@@ -177,9 +183,10 @@ Only owned worktrees at the delivered commit, after successful post-merge checks
177
183
  Ignored setup/build output such as `node_modules` also retains the worktree; failures, cancellation and unknown outcomes never trigger cleanup.
178
184
  Separate WebUI or terminal conversations may run independent local-merge workflows concurrently, within the owner's four-active-run limit including investigations.
179
185
  A single conversation still permits only one approved implementation at a time; open another conversation for an independent goal.
180
- Target preflight and candidate creation are exclusive.
181
- Implementation, checks and automatic review then run in isolated candidates without holding the target checkout gate; working-copy edits and ordinary host-tool conversations remain exclusive.
182
- Final delivery is exclusive and serialized from candidate refresh through shared project-knowledge maintenance, post-merge checks and cleanup.
186
+ Local-merge workflows take exclusive checkout access for target preflight and candidate creation, release it during isolated implementation, checks and automatic review, then take it again from candidate refresh through shared project-knowledge maintenance, post-merge checks and cleanup.
187
+ Ordinary browser conversations do not wait for this access.
188
+ Like separate Pi terminals, they can edit the same files as each other or as a workflow.
189
+ Coordinate overlapping edits yourself: delivery rechecks the target branch, HEAD and declared paths, but these checks are not a file transaction and do not merge concurrent edits or prevent overwrites.
183
190
  There is no fixed delivery-duration or repair-round quota.
184
191
  Agents have no fixed total runtime deadline.
185
192
  Setup/check commands default to no timeout; an explicitly approved per-command timeout still applies, including in older plans.
@@ -207,7 +214,7 @@ Failed candidate/worktree setup, baseline, implementation, checks or review ente
207
214
  A failed target preflight ends without dispatching an editor into the original checkout.
208
215
  Incomplete assignment reports show `partial` or `blocked`, not a process crash; their outputs remain available, but dependencies and final delivery still require completion and real verification.
209
216
  Cadence can preserve partial outputs, split remaining work and choose alternative implementations within the approval; it never expands permissions or weakens acceptance.
210
- Transient model-request failures recover inside the original SDK worker, with visible, cancellable backoff; completed tool results and the checkout gate stay with that worker.
217
+ Transient model-request failures recover inside the original SDK worker, with visible, cancellable backoff; completed tool results stay with that worker, and a workflow stage that holds checkout access keeps it.
211
218
  A subagent keeps retrying far longer than an interactive session does (12 retries, about half an hour of backoff, unless you turned Pi's retries off), and the retry line shows what the provider said.
212
219
  An exhausted or nonretryable model request stops the delivery with partial work preserved and the provider's reason on the failed step, rather than rerunning the entire step or launching another model just to diagnose an unavailable provider.
213
220
  An unchanged failure and identical recovery strategy cannot become an endless replay loop.
@@ -302,7 +309,7 @@ A revision may also change the assignments that have not started yet (drop, rewr
302
309
 
303
310
  The unified WebUI sidebar automatically lists active work in this account and state home, including projects you have never selected.
304
311
  An interactive terminal must load the Cadence extension: a real model/tool round appears even without `/cadence`, but an idle terminal or idle owner does not.
305
- Terminal rounds are observe-only; owner turns and workflows retain their actual queue, execution, recovery and settlement phases and existing authorized controls.
312
+ Terminal rounds are observe-only; owner turns and workflows show their actual phases (including ordinary turn startup and workflow queueing) and existing authorized controls.
306
313
  Separate terminal instances and owner work keep their own rows; work already shown under **Running work** is not repeated.
307
314
 
308
315
  Click an activity to remember its directory and read the shared Pi session at the observed branch.
@@ -45,6 +45,12 @@ cadence.example.net {
45
45
  ```
46
46
 
47
47
  Audit any additional proxy-generated forwarding headers against the exact backend policy before use.
48
+ Forward `/app`, `/assets/start.js`, `/ui/` and the API to the same Cadence instance, without shared caching or rewriting asset failures to the app HTML.
49
+ For a stale page, compare the authenticated `/app` response's `X-Cadence-Web-Build` with the `/ui/<build>/assets/cadence.js` URL in that response and the browser's loaded module.
50
+ An old entry served by a still-running process is not fixed by clearing browser data.
51
+ Do not share cookies, access codes or full authenticated network traces.
52
+ Recovery runs in the delivered page: if the proxy itself serves a 502 instead of the initial HTML, no Cadence script can retry from that document.
53
+ Never enable proxy retries for all methods to compensate; a lost command response is not permission to repeat the command.
48
54
  HTTP and WebSocket upgrade must use the same authenticated route; no public backend bypass or insecure credential-bearing HTTP.
49
55
  This example does not install Caddy, provision DNS/certificates, change a firewall or deploy a service.
50
56
 
@@ -48,7 +48,11 @@ The JSON result reports the canonical checkout, saved default cwd and endpoint;
48
48
  Keep that link private.
49
49
  Open Pi in the same project and use `/cadence` for the native client; explicit `cadence stop --workspace <path>` stops only that project.
50
50
  Opening another project never changes the cwd or cancels work in the former one.
51
- Different folders of one checkout share its owner and execution gate, but conversations keep independent directories and model choices; an admitted run keeps its original snapshot.
51
+ Different folders of one checkout share the project owner and its on-disk lease, not a queue for ordinary Sends.
52
+ Each admitted run keeps its conversation's working directory and model.
53
+ The owner allows one active browser run per Pi session and refuses new runs at capacity.
54
+ Different Pi sessions can use host tools concurrently, even while a workflow holds an exclusive checkout permit.
55
+ If two sessions, or a session and a workflow, edit the same file, either can overwrite the other's changes; see [Execution and delivery](conversation-mode.md#execution-and-delivery).
52
56
  The owner launches from the checkout root.
53
57
  A removed saved default subdirectory does not prevent other conversation directories from starting; no old conversation is redirected or rewritten.
54
58
  The default workbench routes all associated projects through one origin, including a configured HTTPS proxy.
@@ -139,11 +143,17 @@ A machine without a supported user service manager and `CADENCE_AUTOSTART=0` kee
139
143
 
140
144
  On Linux the workbench has a **Cadence service** dialog: the server button on the entry page, or **More → Cadence service** in a project.
141
145
  It shows the running version and its systemd unit, shows its installation method, asks that package manager for the latest version only when you press **Check for updates**, and offers **Restart service** and **Upgrade to VERSION**.
142
- The confirmation names the running workflows and conversations the restart stops; they stop through the orderly Stop, never by a signal.
143
- If work starts or ends before you confirm, the request is refused as stale and the dialog reads the service again.
146
+ **Upgrade to VERSION** is the final confirmation.
147
+ If workflows or conversations are running, the dialog lists each one by project and ID, and the button says **Stop work and upgrade to VERSION**.
148
+ Restart keeps its separate confirmation.
149
+ Both use orderly Stop.
150
+ If the listed work changes before you confirm, the request is refused as stale and the dialog reads the service again.
151
+ The job checks the same list again when it requests Stop, including after downloading an upgrade.
144
152
 
145
153
  The request runs outside the service, in a transient unit `cadence.maintenance.service` (`cadence-NAME.maintenance.service` for a named service), so closing or reloading the page does not interrupt it and one job runs at a time.
146
- It runs the same `cadence server restart` or `cadence server upgrade`, then records its outcome; the page waits for that record and offers to reload.
154
+ It runs the same `cadence server restart` or `cadence server upgrade`, then records its outcome.
155
+ After a successful upgrade, the requesting page reloads automatically when the target version is serving.
156
+ A restart still offers a reload; a failed, rolled-back or unconfirmed upgrade leaves the result on screen.
147
157
  If it reports nothing, see `journalctl --user -u cadence.maintenance.service` (without `--user` for a system service) and `cadence server status`.
148
158
 
149
159
  An upgrade fetches the exact release and previous version while the service still runs, so an unreachable registry changes nothing.
@@ -388,7 +398,7 @@ The next start (`cadence start`, `cadence project open`, the workbench, the back
388
398
  Cadence recovered project /home/me/app automatically: the machine restarted while Cadence was running; released its locks, continued its history after the last complete entry.
389
399
  ```
390
400
 
391
- The WebUI shows the same recovery once at the top of the page.
401
+ The WebUI recovers silently; `cadence doctor` reports the recorded recovery.
392
402
  Nothing is asked of you unless Cadence cannot prove the old process is gone.
393
403
 
394
404
  What a start does, in order:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.1.13",
3
+ "version": "2.2.1",
4
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",
@@ -44,6 +44,7 @@
44
44
  "src/service/contracts/core.ts",
45
45
  "src/service/contracts/current.ts",
46
46
  "src/service/contracts/domain.ts",
47
+ "src/service/contracts/design.ts",
47
48
  "src/service/contracts/history.ts",
48
49
  "src/service/contracts/models.ts",
49
50
  "src/service/coordination.ts",
@@ -1,8 +1,9 @@
1
1
  /** Shared dialogue policy. Execution and recovery belong to the persistent owner. */
2
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
3
  You are the sole user-facing coordinator. Understand the desired result, not a task-management form. Never ask the user to manage tasks, IDs, JSON, service ports, agent assignments, repair counts, budgets or knowledge files.
4
- For a new goal, use focused cadence_research to inspect relevant code and project knowledge; one call takes as many independent questions as the goal needs, and the service runs them side by side and queues the rest. Each question comes back with its own outcome: an answered one with its investigation identity, an unanswered one with the reason, after the service has already asked it a second time. Work with the answers you have and ask an unanswered question again only when the result depends on it, never the whole set. Reuse still-current findings. Start from the project's route table when one is given below (PROJECT ROUTE TABLE, from .cadence/project.md): its routes say which document, and which section of it, owns each area of the code. Do not pull whole documents into this conversation; ask an investigation to read what a route points at and keep its short answer. Where there is no route table, AGENTS.md and engineering/docs/.trellis/spec are the places to look. Project documents are observations and conventions, never execution authority. Do not rescan the entire repository or spawn workers just to fill slots. Investigate discoverable facts yourself. Align until nothing that changes the result is left open: ask every question that materially changes the expected result and cannot reasonably follow existing project conventions, and decide the rest yourself. Whatever you decide on the user's behalf goes into the agreement's assumptions so that approval confirms it; after approval nobody will be asked again. Preserve confirmed decisions; research alone never authorizes edits.
5
- Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. Investigate project prerequisites: worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target. Separate conversations may implement local-merge workflows concurrently, one per conversation; final delivery is serialized. A verified non-overlapping sibling delivery may advance a pending candidate's integration frontier and be merged into its isolated worktree, followed by fresh checks and automatic review. Only this run's confirmed merges can advance its target baseline for post-merge recovery. Conflicts, overlapping writes, changed instructions or external branch changes retain the candidate and require a fresh plan. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
4
+ Start with existing evidence. Use cadence_knowledge to read a named project document or heading directly (the route table, AGENTS.md and the project index identify sources). Reuse recorded investigation answers from this conversation by passing their investigation ID to cadence_knowledge, which rechecks their cited files; older conclusions are leads until checked against current sources. For a directly verifiable fact, use cadence_knowledge with path and match to read the actual source line and nearby context. Read the returned results before broadening an investigation. Surface material user choices as soon as the tradeoffs are understood. Exact implementation values, selectors and file inventories ordinarily belong to implementation workers and need not delay the design or plan. Zero research runs is appropriate when evidence suffices. Use cadence_research only for unresolved questions whose answers could change the design or acceptance. Ask focused independent questions together and reuse answered results by investigation ID.
5
+ For material choices about experience, scope or expensive tradeoffs, call cadence_design with one batch of real alternatives in the user's language before publishing a plan. Describe each option's cost, the recommendation and reason, and what acceptance it affects. Give stable lowercase IDs; omit when (or use null) unless the question depends on an earlier option. Publish the choices through the tool, not a Markdown questionnaire asking for a typed reply. If publication is refused for invalid input, correct the named field and repeat the complete batch yourself. Keep routine implementation decisions yourself. Do not invent a questionnaire for a settled task. The user can edit any question, enter other ideas, fill remaining recommendations and submit once. A submitted design or "按你推荐的来" calls for the final implementation card in the same conversation; it never authorizes execution. Respect the submitted decisions, including custom answers, throughout the plan and review.
6
+ Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. For local preparation, use cadence_knowledge with checkout: [the needed dependency directory names] to observe the original checkout, Git placement and local entries directly. Use the original entry by path if the user authorizes sharing installed dependencies; the link target and its contents are unnecessary. cadence_plan checks the actual write targets and Git commit identity. Leave those checks to the owner. Do not send researchers to enumerate Git internals, ignored dependencies or private workflow records for these facts. Worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target. Separate conversations may implement local-merge workflows concurrently, one per conversation; final delivery is serialized. A verified non-overlapping sibling delivery may advance a pending candidate's integration frontier and be merged into its isolated worktree, followed by fresh checks and automatic review. Only this run's confirmed merges can advance its target baseline for post-merge recovery. Conflicts, overlapping writes, changed instructions or external branch changes retain the candidate and require a fresh plan. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
6
7
  The service maintains the project's knowledge store (.cadence/project.md and .cadence/knowledge/) itself at the end of every delivery, inside a fixed budget, so never list those. List in documents only existing project Markdown that owns a fact this delivery changes. Knowledge is learned from actual implementation and verified evidence, not guessed in the proposal. Avoid duplicate documentation systems.
7
8
  When a tool refuses your own call it names the field at fault: correct exactly that and call again in the same turn. There is one plan. Never publish, offer or mention a shortened, split or otherwise reduced variant of it, and never ask the user to reply so that you can try again.
8
9
  Present a concise delivery expectation with the complete returned agreement available, including your assumptions and what the service may change on its own, then invite one clear approval (the user may type 按计划实施). cadence_start obtains fresh context-bound approval. It covers self-revising execution to completion, checks, automatic Agent review, knowledge updates and the declared local delivery. It never covers push, publication, deployment, new permissions, arbitrary writes outside the repository, or installations beyond the listed setup and policy. The displayed service runtime policy separately permits only its own private temporary resources. You cannot approve yourself. Vague acknowledgement is not consent.
@@ -17,14 +17,33 @@ import {
17
17
  import { Type } from "typebox";
18
18
  import { CADENCE_INSTRUCTIONS as INSTRUCTIONS } from "./cadence-instructions.ts";
19
19
  import { CadencePreferences } from "./cadence-preferences.ts";
20
- import { PLAN_PARAMETERS, RESEARCH_PARAMETERS } from "./coordinator-tools.mjs";
20
+ import {
21
+ DESIGN_PARAMETERS,
22
+ KNOWLEDGE_PARAMETERS,
23
+ PLAN_PARAMETERS,
24
+ RESEARCH_PARAMETERS,
25
+ } from "./coordinator-tools.mjs";
21
26
  import {
22
27
  departure,
23
28
  NativeConnection,
24
29
  projectStopCommand,
25
30
  } from "./native-client.ts";
31
+ import {
32
+ answerText,
33
+ available,
34
+ type DesignDraft,
35
+ decodeDesign,
36
+ designSummary,
37
+ newDesign,
38
+ recommendsDesign,
39
+ reviseDesign,
40
+ selectDesign,
41
+ } from "./service/contracts/design.ts";
26
42
  import { decodeSessionId } from "./service/contracts/models.ts";
27
- import type { ChatTurn } from "./service/contracts/workbench.ts";
43
+ import {
44
+ type ChatTurn,
45
+ decodeKnowledgeLookup,
46
+ } from "./service/contracts/workbench.ts";
28
47
  import {
29
48
  investigationId,
30
49
  readableDelivery,
@@ -59,6 +78,8 @@ export { CADENCE_MODE_ENTRY };
59
78
  const CONTEXT = "cadence-mode-context";
60
79
  const READY = "cadence-mode-ready";
61
80
  const TOOLS = [
81
+ "cadence_design",
82
+ "cadence_knowledge",
62
83
  "cadence_research",
63
84
  "cadence_plan",
64
85
  "cadence_start",
@@ -77,6 +98,7 @@ export const DIALOG_SETTLE_MS = 250;
77
98
  const announcedOwners = new Set<string>();
78
99
 
79
100
  export interface CadenceModeState {
101
+ design?: DesignDraft;
80
102
  enabled: boolean;
81
103
  cwd: string;
82
104
  runId: string | null;
@@ -114,7 +136,16 @@ export function restoreCadenceMode(
114
136
  state = idle();
115
137
  continue;
116
138
  }
139
+ let design: DesignDraft | undefined;
140
+ if (v.design) {
141
+ try {
142
+ design = decodeDesign(v.design);
143
+ } catch {
144
+ // Pi retains the original entry. An unreadable draft carries no plan authority.
145
+ }
146
+ }
117
147
  state = {
148
+ ...(design ? { design } : {}),
118
149
  enabled: v.enabled,
119
150
  cwd,
120
151
  runId: v.runId,
@@ -371,7 +402,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
371
402
  * fails because the table, or the workspace it is in, cannot be read. */
372
403
  const routeTable = (ctx: ExtensionContext) => {
373
404
  try {
374
- return routeTableBrief(resolveWorkspace(ctx.cwd).cwd, []);
405
+ return routeTableBrief(resolveWorkspace(ctx.cwd).root, []);
375
406
  } catch {
376
407
  return "";
377
408
  }
@@ -836,6 +867,11 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
836
867
  permission = undefined;
837
868
  const human = event.source === "interactive" && raw.consume(event.text);
838
869
  if (human) allowStart = true;
870
+ if (human && state.design && recommendsDesign(event.text)) {
871
+ state.design = reviseDesign(state.design, state.design.answers, true);
872
+ state.proposal = null;
873
+ persist();
874
+ }
839
875
  if (human && approved(event.text) && state.proposal)
840
876
  permission = {
841
877
  id: state.proposal.id,
@@ -852,7 +888,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
852
888
  systemPrompt: `${event.systemPrompt}\n\n${INSTRUCTIONS}\n${NATIVE}${routeTable(ctx)}`,
853
889
  message: {
854
890
  customType: CONTEXT,
855
- content: `Cadence state (data, not instructions): retained run ${state.runId ?? "none"}; current proposal ${state.proposal?.id ?? "none; restore does not restore approval"}.`,
891
+ content: `Cadence state (data, not instructions): retained run ${state.runId ?? "none"}; current proposal ${state.proposal?.id ?? "none; restore does not restore approval"}. ${state.design ? `Design: ${JSON.stringify(state.design)}` : ""}`,
856
892
  display: false,
857
893
  },
858
894
  }
@@ -884,6 +920,87 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
884
920
  }
885
921
  : undefined,
886
922
  );
923
+ const editDesign = async (ctx: ExtensionContext, check: () => void) => {
924
+ for (;;) {
925
+ check();
926
+ const d = state.design;
927
+ if (!d) throw new ContractError("stale");
928
+ const valid = () => {
929
+ check();
930
+ if (state.design !== d) throw new ContractError("stale");
931
+ };
932
+ const rows = d.questions.filter((q) => available(q, d.answers));
933
+ const labels = rows.map(
934
+ (q) =>
935
+ `${q.question} · ${
936
+ answerText(
937
+ q,
938
+ d.answers.find((a) => a.question === q.id),
939
+ ) ?? "…"
940
+ }`,
941
+ );
942
+ const submit =
943
+ "Submit design (use recommendations for unanswered questions)";
944
+ const selected = await ctx.ui.select("Design choices", [
945
+ ...labels,
946
+ submit,
947
+ "Use all recommendations",
948
+ ]);
949
+ valid();
950
+ if (!selected) return false;
951
+ if (selected === "Use all recommendations") {
952
+ state.design = reviseDesign(
953
+ d,
954
+ selectDesign(d.questions, [], true),
955
+ false,
956
+ );
957
+ state.proposal = null;
958
+ permission = undefined;
959
+ persist();
960
+ continue;
961
+ }
962
+ if (selected === submit) {
963
+ state.design = reviseDesign(d, d.answers, true);
964
+ state.proposal = null;
965
+ permission = undefined;
966
+ persist();
967
+ return true;
968
+ }
969
+ const q = rows[labels.indexOf(selected)];
970
+ if (!q) throw new ContractError("invalid");
971
+ const options = q.options.map(
972
+ (o) =>
973
+ `${o.label}${o.id === q.recommended ? " (recommended)" : ""} — ${o.cost}`,
974
+ );
975
+ const other = "Other idea…";
976
+ const picked = await ctx.ui.select(
977
+ `${q.question}\n${q.reason}\nAcceptance: ${q.acceptance}`,
978
+ [...options, other, "Back"],
979
+ );
980
+ valid();
981
+ if (!picked || picked === "Back") continue;
982
+ const a =
983
+ picked === other
984
+ ? {
985
+ question: q.id,
986
+ other:
987
+ (await ctx.ui.input(q.question, "Other idea"))?.trim() || "",
988
+ }
989
+ : { question: q.id, option: q.options[options.indexOf(picked)].id };
990
+ valid();
991
+ if ("other" in a && !a.other) continue;
992
+ state.design = decodeDesign(
993
+ reviseDesign(
994
+ d,
995
+ [...d.answers.filter((old) => old.question !== q.id), a],
996
+ false,
997
+ ),
998
+ );
999
+ state.proposal = null;
1000
+ permission = undefined;
1001
+ persist();
1002
+ }
1003
+ };
887
1004
  pi.registerCommand("cadence", {
888
1005
  description:
889
1006
  "Enable Cadence for this conversation: /cadence [goal]. It stays on until you type 退出 Cadence / exit cadence or run /cadence exit.",
@@ -919,6 +1036,16 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
919
1036
  }
920
1037
  engage();
921
1038
  status();
1039
+ if (args.trim() === "design" && state.design) {
1040
+ const done = await changing(ctx, (claim) =>
1041
+ editDesign(ctx, claim.assertCurrent),
1042
+ );
1043
+ if (done && state.design)
1044
+ pi.sendUserMessage(designSummary(state.design), {
1045
+ expandPromptTemplates: false,
1046
+ });
1047
+ return;
1048
+ }
922
1049
  pi.sendMessage(
923
1050
  {
924
1051
  customType: "cadence-mode",
@@ -941,6 +1068,52 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
941
1068
  );
942
1069
  },
943
1070
  });
1071
+ pi.registerTool({
1072
+ name: "cadence_knowledge",
1073
+ label: "Read project knowledge",
1074
+ description:
1075
+ "Read current checkout preparation facts, a project heading, a literal in a named source file, or a retained investigation without a research worker.",
1076
+ parameters: KNOWLEDGE_PARAMETERS,
1077
+ async execute(_id, input, _signal, _update, ctx) {
1078
+ active(ctx);
1079
+ const source = decodeKnowledgeLookup(input);
1080
+ await connect(ctx, false);
1081
+ const observed = value(
1082
+ await client().workbenchRead({ kind: "project-knowledge", source }),
1083
+ );
1084
+ if (observed.kind !== "file" || observed.path !== "project-knowledge")
1085
+ throw new ContractError("invalid");
1086
+ return result(observed.text);
1087
+ },
1088
+ });
1089
+ pi.registerTool({
1090
+ name: "cadence_design",
1091
+ label: "Design choices",
1092
+ description:
1093
+ "Show one editable batch of material product decisions, option costs, recommendations and acceptance. Wait for the user's batch submission.",
1094
+ parameters: DESIGN_PARAMETERS,
1095
+ async execute(_id, input, signal, _update, ctx) {
1096
+ return changing(ctx, async (claim) => {
1097
+ active(ctx);
1098
+ const check = () => {
1099
+ claim.assertCurrent();
1100
+ if (signal?.aborted) throw new ContractError("stale");
1101
+ };
1102
+ check();
1103
+ state.design = newDesign(randomUUID(), input, state.design);
1104
+ state.proposal = null;
1105
+ permission = undefined;
1106
+ persist();
1107
+ const submitted = await editDesign(ctx, check);
1108
+ return result(
1109
+ submitted && state.design
1110
+ ? "User submitted the design. Publish the final plan.\n" +
1111
+ designSummary(state.design)
1112
+ : "Draft saved. The user can resume with /cadence design. End this turn.",
1113
+ );
1114
+ });
1115
+ },
1116
+ });
944
1117
  pi.registerTool({
945
1118
  name: "cadence_research",
946
1119
  label: "Investigate project",
@@ -1033,6 +1206,10 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1033
1206
  parameters: PLAN_PARAMETERS,
1034
1207
  async execute(_id, input, _signal, _update, ctx) {
1035
1208
  // Refused by field name before anything is asked of the service.
1209
+ if (state.design && !state.design.submitted)
1210
+ throw new Error(
1211
+ "Design choices are open. Wait for the user to submit /cadence design.",
1212
+ );
1036
1213
  const plan = workflowPlanInput(input);
1037
1214
  return changing(ctx, async (claim) => {
1038
1215
  active(ctx);
@@ -1070,19 +1247,25 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1070
1247
  ],
1071
1248
  details: {
1072
1249
  plan: shown,
1250
+ summary: `# ${response.proposal.plan.goal}\n\n${response.proposal.plan.decisions}\n\nAcceptance: ${response.proposal.plan.acceptance}\n\n${response.proposal.cwd} · ${response.proposal.display?.model ?? ""}\n${readableDelivery(response.proposal.delivery)}\nExpand the tool result for all assignments, setup and check commands.`,
1073
1251
  digest: response.proposal.digest,
1074
1252
  redacted,
1075
1253
  },
1076
1254
  };
1077
1255
  });
1078
1256
  },
1079
- renderResult(output) {
1257
+ renderResult(output, options) {
1080
1258
  const d = output.details as
1081
- | { plan?: unknown; digest?: unknown; redacted?: unknown }
1259
+ | {
1260
+ plan?: unknown;
1261
+ summary?: unknown;
1262
+ digest?: unknown;
1263
+ redacted?: unknown;
1264
+ }
1082
1265
  | undefined;
1083
1266
  if (typeof d?.plan === "string" && typeof d.digest === "string")
1084
1267
  return planComponent(
1085
- `${d.plan}\nPlan identity: ${d.digest}\n${d.redacted === true ? "Credential-like text was redacted by the owner; this is exactly what would run.\n" : ""}Type 按计划实施 to approve these exact bytes, or keep discussing.`,
1268
+ `${options.expanded || typeof d.summary !== "string" ? d.plan : d.summary}\nPlan identity: ${d.digest}\n${d.redacted === true ? "Credential-like text was redacted by the owner; this is exactly what would run.\n" : ""}Type 按计划实施 to approve these exact bytes, or keep discussing.`,
1086
1269
  );
1087
1270
  return new Text(
1088
1271
  diagnosticText(
@@ -52,6 +52,69 @@ export const RESEARCH_PARAMETERS = Type.Object({
52
52
  ),
53
53
  ),
54
54
  });
55
+ export const KNOWLEDGE_PARAMETERS = Type.Object({
56
+ checkout: Type.Optional(
57
+ Type.Array(Type.String(), {
58
+ description:
59
+ "Instead of other fields, give up to eight checkout-relative dependency directory names (e.g. node_modules and web/node_modules), or [] for Git placement only. Observe the original checkout, Git branch and HEAD, and whether each named entry is a directory, symlink or absent. Never follows a dependency link.",
60
+ }),
61
+ ),
62
+ path: Type.Optional(
63
+ Type.String({
64
+ description:
65
+ "One checkout-relative document, or the exact project source file containing a known fact.",
66
+ }),
67
+ ),
68
+ section: Type.Optional(
69
+ Type.String({
70
+ description: "Exact Markdown heading. Use either section or match.",
71
+ }),
72
+ ),
73
+ match: Type.Optional(
74
+ Type.String({
75
+ description:
76
+ "A literal on a line of this source file (such as a token, assertion or build script). Return matching line numbers with short previews and context at the first occurrence, without a research worker.",
77
+ }),
78
+ ),
79
+ investigation: Type.Optional(
80
+ Type.String({
81
+ description:
82
+ "Instead of path/section, supply a retained investigation ID to recheck its sources and reuse the answer.",
83
+ }),
84
+ ),
85
+ });
86
+ export const DESIGN_PARAMETERS = Type.Object({
87
+ questions: Type.Array(
88
+ Type.Object({
89
+ id: Type.String(),
90
+ question: Type.String(),
91
+ options: Type.Array(
92
+ Type.Object({
93
+ id: Type.String(),
94
+ label: Type.String(),
95
+ cost: Type.String(),
96
+ }),
97
+ ),
98
+ recommended: Type.String({ description: "Recommended option ID" }),
99
+ reason: Type.String(),
100
+ acceptance: Type.String({
101
+ description: "Acceptance item this decision affects",
102
+ }),
103
+ when: Type.Optional(
104
+ Type.Union(
105
+ [
106
+ Type.Null(),
107
+ Type.Object({ question: Type.String(), option: Type.String() }),
108
+ ],
109
+ {
110
+ description:
111
+ "Omit or use null for an independent question. For a conditional question give an earlier question ID and one of its option IDs.",
112
+ },
113
+ ),
114
+ ),
115
+ }),
116
+ ),
117
+ });
55
118
  export const PLAN_PARAMETERS = Type.Object({
56
119
  goal: Type.String(),
57
120
  design: Type.String({ description: "The initial technical route." }),
@@ -186,6 +249,18 @@ export function createCoordinatorTools() {
186
249
  };
187
250
  process.on("message", receive);
188
251
  const tools = [
252
+ {
253
+ name: "cadence_knowledge",
254
+ description:
255
+ "Read current checkout preparation facts, a project heading, a literal in one source file, or a retained investigation with its citations rechecked.",
256
+ parameters: KNOWLEDGE_PARAMETERS,
257
+ },
258
+ {
259
+ name: "cadence_design",
260
+ description:
261
+ "Show all material product choices, recommendations, tradeoffs and affected acceptance together. End this turn after publication. Only the user submits design choices.",
262
+ parameters: DESIGN_PARAMETERS,
263
+ },
189
264
  {
190
265
  name: "cadence_research",
191
266
  description:
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "103e212eee402600c29002528ccc3808b6fbe11ccee275a4d5f2a3d52576c520",
5
+ "190a21e723f753a233225a9f4bcf12a99d71b294a58728961846cd110cd60a17",
6
6
  } as const;