@abelxiaoxing/cadence 2.2.0 → 2.2.2

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.
@@ -313,7 +323,9 @@ At sign-out or shutdown Windows ends the owner without orderly Stop: running wor
313
323
 
314
324
  - `alive` requires an authenticated exact-epoch reply.
315
325
  It is not a PID probe.
316
- `actions:false` can describe the unscoped owner model slot; conversation model readiness is separate, not permission to execute a plan.
326
+ In `status` and `diagnose`, `actions:false` can describe an empty unscoped owner model slot.
327
+ It does not disable conversation Send; the WebUI session reports workbench availability independently and each Send checks its own conversation model.
328
+ Neither flag is permission to execute a plan.
317
329
  - Disconnect this page (the WebUI More menu), browser close and Pi quit detach clients; admitted work continues.
318
330
  Use the client's **Cancel** for a run or management **stop** for the service.
319
331
  - Stop closes admission and waits original processes, credential writes, history writes, already-started publication continuations, owned networking and listener closure before releasing fences.
@@ -388,7 +400,7 @@ The next start (`cadence start`, `cadence project open`, the workbench, the back
388
400
  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
401
  ```
390
402
 
391
- The WebUI shows the same recovery once at the top of the page.
403
+ The WebUI recovers silently; `cadence doctor` reports the recorded recovery.
392
404
  Nothing is asked of you unless Cadence cannot prove the old process is gone.
393
405
 
394
406
  What a start does, in order:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
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",
@@ -2,7 +2,7 @@
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
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; use when for predictable dependencies on earlier options. 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.
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
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.
7
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.
8
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.
@@ -20,6 +20,7 @@ import { CadencePreferences } from "./cadence-preferences.ts";
20
20
  import {
21
21
  DESIGN_PARAMETERS,
22
22
  KNOWLEDGE_PARAMETERS,
23
+ knowledgeToolInput,
23
24
  PLAN_PARAMETERS,
24
25
  RESEARCH_PARAMETERS,
25
26
  } from "./coordinator-tools.mjs";
@@ -40,10 +41,7 @@ import {
40
41
  selectDesign,
41
42
  } from "./service/contracts/design.ts";
42
43
  import { decodeSessionId } from "./service/contracts/models.ts";
43
- import {
44
- type ChatTurn,
45
- decodeKnowledgeLookup,
46
- } from "./service/contracts/workbench.ts";
44
+ import type { ChatTurn } from "./service/contracts/workbench.ts";
47
45
  import {
48
46
  investigationId,
49
47
  readableDelivery,
@@ -396,7 +394,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
396
394
  context = ctx;
397
395
  };
398
396
  const summarize = (run: WorkflowRun) =>
399
- `Cadence ${run.status} • ${run.goal}\nRun: ${run.id} · route revision ${run.revision ?? 0} · stepsBefore ${run.stepsBefore ?? 0}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run.delivery)}\n${run.steps.map((s) => `${s.kind} ${s.id}${s.kind === "research" && s.status === "completed" ? ` · investigation ${s.childRunId ?? investigationId(s.id)}` : ""}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}\n${s.text}${s.truncated ? "\n[Preview truncated; full result retained by owner.]" : ""}`).join("\n")}\n${run.notice}${run.mergedCommit ? `\nLocal merge: ${run.mergedCommit}` : ""}${run.status === "unknown" ? "\nOutcome unknown: neither completed nor failed. Its actual effects are not inferred, and the owner keeps any fences." : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
397
+ `Cadence ${run.status} • ${run.goal}\nRun: ${run.id} · route revision ${run.revision ?? 0} · stepsBefore ${run.stepsBefore ?? 0}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run)}\n${run.steps.map((s) => `${s.kind} ${s.id}${s.kind === "research" && s.status === "completed" ? ` · investigation ${s.childRunId ?? investigationId(s.id)}` : ""}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}\n${s.text}${s.truncated ? "\n[Preview truncated; full result retained by owner.]" : ""}`).join("\n")}\n${run.notice}${run.mergedCommit ? `\nLocal merge: ${run.mergedCommit}` : ""}${run.status === "unknown" ? "\nOutcome unknown: neither completed nor failed. Its actual effects are not inferred, and the owner keeps any fences." : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
400
398
  const agentDir = () => getAgentDir();
401
399
  /** The project's route table for this turn's system prompt. A turn never
402
400
  * fails because the table, or the workspace it is in, cannot be read. */
@@ -1074,9 +1072,10 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1074
1072
  description:
1075
1073
  "Read current checkout preparation facts, a project heading, a literal in a named source file, or a retained investigation without a research worker.",
1076
1074
  parameters: KNOWLEDGE_PARAMETERS,
1075
+ prepareArguments: knowledgeToolInput,
1077
1076
  async execute(_id, input, _signal, _update, ctx) {
1078
1077
  active(ctx);
1079
- const source = decodeKnowledgeLookup(input);
1078
+ const source = knowledgeToolInput(input);
1080
1079
  await connect(ctx, false);
1081
1080
  const observed = value(
1082
1081
  await client().workbenchRead({ kind: "project-knowledge", source }),
@@ -1,6 +1,6 @@
1
1
  /** Serialized private child/owner bridge. Never a browser API or shell executor. */
2
2
  import { Type } from "typebox";
3
- import { LIMITS } from "./worker-public.mjs";
3
+ import { closed, knowledgeFields, LIMITS } from "./worker-public.mjs";
4
4
 
5
5
  /** The parameters of the two tools a coordinator calls, declared once for the
6
6
  * native extension and the browser coordinator. They state shape only: counts,
@@ -52,6 +52,75 @@ export const RESEARCH_PARAMETERS = Type.Object({
52
52
  ),
53
53
  ),
54
54
  });
55
+ const lookupExample =
56
+ 'Use {checkout:["node_modules"]}, {checkout:[]}, {path:"docs.md"} with optional section or match, or {investigation:"<retained UUID>"}.';
57
+ /** Only model arguments may contain empty placeholders. Validate before the SDK
58
+ * coerces scalar types, and again at direct tool entry (no caller is trusted). */
59
+ export function knowledgeToolInput(input) {
60
+ const bad = (field, why) => {
61
+ throw new Error(`${field}: ${why}. ${lookupExample}`);
62
+ };
63
+ const keys = Object.keys(input ?? {});
64
+ let raw;
65
+ try {
66
+ raw = closed(input, keys);
67
+ } catch {
68
+ bad("cadence_knowledge", "expected an object with named lookup fields");
69
+ }
70
+ const fields = Object.create(null);
71
+ for (const key of keys) {
72
+ if (!Object.hasOwn(knowledgeFields, key))
73
+ bad(JSON.stringify(key.slice(0, 80)), "unknown field; omit it");
74
+ if (key !== "checkout" && raw[key] === "") continue;
75
+ try {
76
+ fields[key] = knowledgeFields[key](raw[key]);
77
+ } catch {
78
+ bad(
79
+ key,
80
+ key === "checkout"
81
+ ? "give an array of up to eight nonempty dependency paths (each at most 1024 bytes)"
82
+ : key === "investigation"
83
+ ? "give a retained investigation UUID"
84
+ : "give a nonblank string within the field limit",
85
+ );
86
+ }
87
+ }
88
+ const { checkout, path, section, match, investigation } = fields;
89
+ if ((section || match) && !path)
90
+ bad(
91
+ section ? "section/path" : "match/path",
92
+ "name the source file in path",
93
+ );
94
+ if (section && match) bad("section/match", "choose one selector");
95
+ if (checkout?.length && (path || investigation))
96
+ bad("checkout", "cannot combine dependencies with path or investigation");
97
+ if (investigation && path) bad("investigation/path", "choose one source");
98
+ const relative = (name) =>
99
+ !/[\\:\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(name) &&
100
+ name
101
+ .split("/")
102
+ .every(
103
+ (part) =>
104
+ part &&
105
+ part !== "." &&
106
+ part !== ".." &&
107
+ part.toLowerCase() !== ".git",
108
+ );
109
+ if (path && !relative(path))
110
+ bad("path", "give a plain checkout-relative file path");
111
+ if (
112
+ checkout?.some(
113
+ (name) =>
114
+ !relative(name) || name.split("/").some((part) => part.startsWith(".")),
115
+ )
116
+ )
117
+ bad("checkout", "give plain checkout-relative dependency names");
118
+ if (investigation) return { investigation };
119
+ if (path)
120
+ return match ? { path, match } : section ? { path, section } : { path };
121
+ if (checkout) return { checkout };
122
+ bad("path/checkout/investigation", "no lookup selected");
123
+ }
55
124
  export const KNOWLEDGE_PARAMETERS = Type.Object({
56
125
  checkout: Type.Optional(
57
126
  Type.Array(Type.String(), {
@@ -101,11 +170,14 @@ export const DESIGN_PARAMETERS = Type.Object({
101
170
  description: "Acceptance item this decision affects",
102
171
  }),
103
172
  when: Type.Optional(
104
- Type.Object(
105
- { question: Type.String(), option: Type.String() },
173
+ Type.Union(
174
+ [
175
+ Type.Null(),
176
+ Type.Object({ question: Type.String(), option: Type.String() }),
177
+ ],
106
178
  {
107
179
  description:
108
- "Only relevant for this earlier question and selected option.",
180
+ "Omit or use null for an independent question. For a conditional question give an earlier question ID and one of its option IDs.",
109
181
  },
110
182
  ),
111
183
  ),
@@ -251,6 +323,7 @@ export function createCoordinatorTools() {
251
323
  description:
252
324
  "Read current checkout preparation facts, a project heading, a literal in one source file, or a retained investigation with its citations rechecked.",
253
325
  parameters: KNOWLEDGE_PARAMETERS,
326
+ prepareArguments: knowledgeToolInput,
254
327
  },
255
328
  {
256
329
  name: "cadence_design",
@@ -180,6 +180,13 @@ function decodeId(v) {
180
180
  invalid();
181
181
  return s;
182
182
  }
183
+ var knowledgeFields = Object.freeze({
184
+ checkout: (v) => list(v, 8, (entry) => text(entry, 1024, true)),
185
+ path: (v) => text(v, 1024, true),
186
+ section: (v) => text(v, 512, true),
187
+ match: (v) => text(v, 256, true),
188
+ investigation: decodeId
189
+ });
183
190
  function decodeHash(v) {
184
191
  const s = text(v, 64);
185
192
  if (!/^[0-9a-f]{64}$/.test(s))
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243",
5
+ "80875479add4b7830419060b7e5018a39de200665edfbdec20fc10d50861bfea",
6
6
  } as const;
@@ -31,7 +31,7 @@ export async function workflowDetails(
31
31
  throw new ContractError("invalid");
32
32
  const run = view.response.run;
33
33
  await ui.show(
34
- `${run.goal}\n${run.id} • ${run.status} / ${run.phase}\n${run.notice}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run.delivery)}\nMerged commit: ${run.mergedCommit ?? "none"}\nAutomatic Agent review is not human review. Step summaries are previews; select a step for its retained result.\n${pretty(run.steps)}`,
34
+ `${run.goal}\n${run.id} • ${run.status} / ${run.phase}\n${run.notice}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run)}\nMerged commit: ${run.mergedCommit ?? "none"}\nAutomatic Agent review is not human review. Step summaries are previews; select a step for its retained result.\n${pretty(run.steps)}`,
35
35
  );
36
36
  const labels = run.steps.map(
37
37
  (s, i) => `${i + 1}. ${s.kind} • ${s.id} • ${s.status}`,
@@ -9,6 +9,7 @@ import {
9
9
  list,
10
10
  text,
11
11
  } from "./core.ts";
12
+ import { entries, fields, issue, words } from "./workflow.ts";
12
13
 
13
14
  export interface DesignQuestion {
14
15
  id: string;
@@ -30,63 +31,91 @@ export interface DesignDraft {
30
31
  submitted: boolean;
31
32
  }
32
33
  const label = (v: unknown) => text(v, 1024, true);
33
- const key = (v: unknown) => {
34
- const s = text(v, 48, true);
34
+ const key = (v: unknown, path = "id") => {
35
+ const s = words(path, v, 48, true);
35
36
  if (!/^[a-z][a-z0-9-]*$/u.test(s))
36
- throw new Error("id: use lowercase letters, digits and hyphens");
37
+ return issue(
38
+ path,
39
+ "start with a lowercase letter; use lowercase letters, digits and hyphens",
40
+ );
37
41
  return s;
38
42
  };
39
- export function designQuestions(input: unknown): DesignQuestion[] {
40
- const { questions } = closed(input, ["questions"]);
43
+ function designQuestions(
44
+ input: unknown,
45
+ source: "tool" | "record",
46
+ ): DesignQuestion[] {
47
+ const { questions } = fields("design", input, ["questions"]);
41
48
  const seen = new Map<string, Set<string>>();
42
- const rows = list(questions, 12, (raw) => {
43
- const q = closed(raw, [
44
- "id",
45
- "question",
46
- "options",
47
- "recommended",
48
- "reason",
49
- "acceptance",
50
- ...(Object.hasOwn(raw ?? {}, "when") ? ["when"] : []),
51
- ]);
52
- const id = key(q.id);
53
- const options = list(q.options, 6, (raw) => {
54
- const o = closed(raw, ["id", "label", "cost"]);
55
- return { id: key(o.id), label: label(o.label), cost: label(o.cost) };
49
+ const rows = entries("questions", questions, 12, (raw, path) => {
50
+ const q = fields(
51
+ path,
52
+ raw,
53
+ ["id", "question", "options", "recommended", "reason", "acceptance"],
54
+ ["when"],
55
+ );
56
+ const id = key(q.id, `${path}.id`);
57
+ if (seen.has(id)) return issue(`${path}.id`, "use a distinct question ID");
58
+ const ids = new Set<string>();
59
+ const options = entries(`${path}.options`, q.options, 6, (raw, path) => {
60
+ const o = fields(path, raw, ["id", "label", "cost"]);
61
+ const id = key(o.id, `${path}.id`);
62
+ if (ids.has(id)) return issue(`${path}.id`, "use a distinct option ID");
63
+ ids.add(id);
64
+ return {
65
+ id,
66
+ label: words(`${path}.label`, o.label, 1024, true),
67
+ cost: words(`${path}.cost`, o.cost, 1024, true),
68
+ };
56
69
  });
57
- const ids = new Set(options.map((o) => o.id));
58
- const recommended = key(q.recommended);
59
- if (
60
- seen.has(id) ||
61
- ids.size !== options.length ||
62
- ids.size < 2 ||
63
- !ids.has(recommended)
64
- )
65
- throw new Error(
66
- "questions: use distinct question and option IDs and identify one recommended option",
67
- );
68
- const dep =
69
- q.when === undefined ? null : closed(q.when, ["question", "option"]);
70
- const when = dep && {
71
- question: key(dep.question),
72
- option: key(dep.option),
73
- };
74
- if (when && !seen.get(when.question)?.has(when.option))
75
- throw new Error("when: name an option of an earlier question");
70
+ if (options.length < 2)
71
+ return issue(`${path}.options`, "supply at least two alternatives");
72
+ const recommended = key(q.recommended, `${path}.recommended`);
73
+ if (!ids.has(recommended))
74
+ return issue(`${path}.recommended`, "name an option ID of this question");
75
+ // Some providers populate optional objects even for independent questions.
76
+ // Only an unambiguous no-dependency value may disappear at tool ingress.
77
+ let when: DesignQuestion["when"];
78
+ if (q.when !== undefined && !(source === "tool" && q.when === null)) {
79
+ const dep = fields(`${path}.when`, q.when, ["question", "option"]);
80
+ if (!(source === "tool" && dep.question === "" && dep.option === "")) {
81
+ const question = key(dep.question, `${path}.when.question`);
82
+ if (!seen.has(question))
83
+ return issue(
84
+ `${path}.when.question`,
85
+ "name an earlier question, or omit when for an independent question",
86
+ );
87
+ const option = key(dep.option, `${path}.when.option`);
88
+ if (!seen.get(question)?.has(option))
89
+ return issue(
90
+ `${path}.when.option`,
91
+ "name an option ID of the earlier question",
92
+ );
93
+ when = { question, option };
94
+ }
95
+ }
76
96
  seen.set(id, ids);
77
97
  return {
78
98
  id,
79
- question: label(q.question),
99
+ question: words(`${path}.question`, q.question, 1024, true),
80
100
  options,
81
101
  recommended,
82
- reason: label(q.reason),
83
- acceptance: label(q.acceptance),
102
+ reason: words(`${path}.reason`, q.reason, 1024, true),
103
+ acceptance: words(`${path}.acceptance`, q.acceptance, 1024, true),
84
104
  ...(when ? { when } : {}),
85
105
  };
86
106
  });
87
107
  if (!rows.length)
88
108
  throw new Error("questions: supply a material product decision");
89
- canonicalJson(rows, 24 * 1024);
109
+ try {
110
+ canonicalJson(rows, 24 * 1024);
111
+ } catch (error) {
112
+ if (!(error instanceof ContractError) || error.code !== "oversize")
113
+ throw error;
114
+ return issue(
115
+ "questions",
116
+ "the complete batch must fit in 24 KiB of encoded JSON",
117
+ );
118
+ }
90
119
  return rows;
91
120
  }
92
121
  export function designAnswers(v: unknown): DesignAnswer[] {
@@ -134,7 +163,7 @@ export function selectDesign(
134
163
  }
135
164
  export function decodeDesign(v: unknown): DesignDraft {
136
165
  const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
137
- const questions = designQuestions({ questions: o.questions });
166
+ const questions = designQuestions({ questions: o.questions }, "record");
138
167
  const submitted = bool(o.submitted);
139
168
  const answers = designAnswers(o.answers);
140
169
  if (
@@ -155,7 +184,7 @@ export function newDesign(
155
184
  input: unknown,
156
185
  previous?: DesignDraft,
157
186
  ): DesignDraft {
158
- const questions = designQuestions(input);
187
+ const questions = designQuestions(input, "tool");
159
188
  const retained =
160
189
  previous?.answers.filter((a) => {
161
190
  const before = previous.questions.find((q) => q.id === a.question);