@abelxiaoxing/cadence 2.1.2 → 2.1.4

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.
@@ -21,7 +21,12 @@ Do not spawn workers or retry the whole work session.
21
21
  The service owns delegation and recovery.
22
22
  These are host tools, not a sandbox or automatic rollback system.
23
23
 
24
- After all work, use `cadence_report` to submit completed or blocked with a concrete summary of actual changes and remaining gaps, then give a short final answer.
25
- Do not call another tool after the report unless you submit a new report afterwards.
24
+ After all work, use `cadence_report` to submit completed, partial (useful outputs with remaining assigned work), or blocked (a concrete unmet prerequisite) with a concrete summary of actual changes and remaining gaps, then give a short final answer.
25
+ Readonly inspection after the report is allowed.
26
+ After an editing, shell or other effectful tool, submit a new report.
26
27
  Your report and native exit are not passing checks or delivery approval: the owner runs real checks and independent readonly Agent review.
27
28
  For knowledge assignments, update existing topic owners with source-backed facts and useful verification guidance, preserving human text; never turn speculation or raw session history into project rules.
29
+
30
+ Missing owner execution metadata is not a reason to inspect private state or invent additional approval conditions.
31
+ Use the supplied original failure context; distinguish command-local environment from the frozen check environment.
32
+ A partial or blocked report preserves progress but never satisfies dependent work or verification.
@@ -169,13 +169,18 @@ Credential-looking text in plans and research questions is shown and approved re
169
169
 
170
170
  An isolated worktree does **not** inherit ignored `node_modules`, build output, credentials or profiles.
171
171
  Investigate prerequisites during planning.
172
- If dependencies/setup are needed, include the exact commands in the plan for explicit approval.
172
+ If dependencies/setup are needed, include the exact commands and their execution placement in the plan for explicit approval: `target` for original-checkout preflight, `candidate` for preparation needed once in the stable candidate, or `worktree` for the candidate and each parallel child.
173
+ Parallel children have detached HEADs; target branch checks must not run there.
174
+ Each command is a separate process: bind any required temporary environment in that command rather than relying on an earlier export.
173
175
  No dependency/browser download or source-profile copying is implicit.
174
176
  Baseline checks are separate from acceptance checks that need newly implemented files.
175
- Failed setup, baseline, implementation, checks or review enter source-backed diagnosis when their actual operations have settled.
177
+ Failed candidate/worktree setup, baseline, implementation, checks or review enter source-backed diagnosis when their actual operations have settled.
178
+ A failed target preflight ends without dispatching an editor into the original checkout.
179
+ 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.
176
180
  Cadence can preserve partial outputs, split remaining work and choose alternative implementations within the approval; it never expands permissions or weakens acceptance.
177
181
  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.
178
- An exhausted or nonretryable model request stops the delivery with partial work preserved, rather than rerunning the entire step or launching another model just to diagnose an unavailable provider.
182
+ 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.
183
+ 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.
179
184
  An unchanged failure and identical recovery strategy cannot become an endless replay loop.
180
185
  A concrete external blocker is reported with preserved work, not a generic request to type “continue”.
181
186
  Final candidate checks must pass before merge.
@@ -232,8 +237,11 @@ Conversation response completion is distinct from workflow completion; read the
232
237
 
233
238
  ### Research scope, timing and retained results
234
239
 
235
- Each research call accepts up to eight independent questions and optional specific `roots` (default: the conversation directory).
240
+ Each research call accepts as many independent questions as the goal needs (up to 32) and optional specific `roots` (default: the conversation directory).
236
241
  The service runs as many of them at once as `CADENCE_PARALLEL` allows (default 4, at most 16) and queues the rest; set it in the service's environment to match what your model provider or local model server can serve.
242
+ Every question has its own outcome.
243
+ An answer is recorded as soon as it is given, whatever happens to the other questions; a question whose subagent failed is asked once more by itself after the others, and if it still has no answer the result says why in the provider's own words.
244
+ The investigation is complete when any question was answered.
237
245
  Provide the actual investigation directory, especially for large mounted/backup trees; do not begin by enumerating `/` or broad parent directories.
238
246
  Research tools are readonly and bounded.
239
247
  Search limits and omitted coverage are reported explicitly; a partial search does not prove that no other matching file exists.
@@ -93,7 +93,8 @@ From a clean `main` checkout on any authorized computer:
93
93
  Do not force-move or delete a release tag to repair a failed release.
94
94
  4. Follow **Actions → Publish npm**.
95
95
  A successful dispatch or artifact upload is not proof of npm publication.
96
- The final step verifies registry version/integrity, the `latest` tag and the actual downloaded tarball bytes.
96
+ The final step checks that the registry records the audited artifact's `shasum` and `integrity` for the version and that `latest` names it.
97
+ Because npm clients verify every downloaded tarball against that `integrity`, the match binds what users install to the audited bytes.
97
98
 
98
99
  The tag must name the checked-out event commit, match `package.json`, and already belong to `main`.
99
100
  Pre-release/build-metadata tags, forks, moved/deleted tags, dirty checkouts, existing versions and versions behind the observed `latest` are refused.
@@ -110,19 +111,26 @@ Releases are serialized without cancelling an in-progress publish.
110
111
  GitHub can replace a pending run when another is queued, so push one release tag at a time and inspect each run's outcome.
111
112
  There is no automatic retry of `npm publish`, version bump, unpublish, dist-tag repair or staged-package approval.
112
113
  After a failed or interrupted publish, inspect npm before retrying: the registry may have accepted the request despite a lost client reply.
113
- Confirmation makes bounded readonly observations for propagation and does not convert a failed publish command into a successful command receipt.
114
+ Confirmation makes bounded readonly metadata observations for propagation and does not convert a failed publish command into a successful command receipt.
114
115
  The live-ref/latest checks are not a transaction with other maintainers; an external publication can still race and must be investigated rather than overwritten.
115
116
 
116
- ### Delayed or unconfirmed publication
117
+ ### Delayed or pending publication
117
118
 
118
- npm can accept `npm publish` and then process the package asynchronously before its version, `latest` and tarball become publicly visible.
119
- The confirmation helper uses one monotonic observation deadline for metadata requests, body reads and polling delays; its total window, interval and unchanged per-request ceiling live beside the constants in `scripts/npm-release.mjs`.
120
- Candidate-version or tarball 404s and a lagging `latest` are retried with readonly requests only.
121
- Digest, identity, tarball URL, streamed-byte mismatches and a newer `latest` refuse immediately; other HTTP, transport and malformed-response failures are not treated as propagation.
122
- Each request is limited by the remaining total time, aborted on expiry and awaited through settlement; successful or failed reads dispose their timers.
119
+ npm acknowledges `npm publish` and then processes the package asynchronously, sometimes for longer than the confirmation window, before its version and `latest` become publicly visible.
120
+ The confirmation step polls readonly metadata within one monotonic window; the window, interval and per-request ceiling live beside the constants in `scripts/npm-release.mjs`.
121
+ A candidate-version 404 and a lagging `latest` mean npm is still processing.
122
+ Digest, identity or tarball-URL mismatches and a newer `latest` refuse immediately; other HTTP, transport, per-request timeout and malformed-response failures are not treated as propagation.
123
+ Each request is limited by the remaining window, aborted on expiry and awaited through settlement.
123
124
 
124
- The confirmation step records the original publish-step outcome separately in its failure log and job summary.
125
- A successful publish followed by an observation timeout means **publication is still unconfirmed**, not that the publish command failed or the version is safe to reuse.
126
- Keep that run's original audited artifact and digest, then independently recheck registry metadata, `latest` and downloaded bytes against that same artifact.
125
+ If the window ends while npm is still processing, a successful publish ends the job with a **pending** warning rather than a failure: no mismatch was observed, but registry visibility is not yet confirmed and the version is not safe to reuse.
126
+ After a failed or unknown publish outcome, pending still fails the job.
127
+ Confirm a pending publication later with one readonly observation of that run's audited artifact while it is retained; the digest is the run's `RELEASE_SHA256`, printed in its summary:
128
+
129
+ ```sh
130
+ gh run download <run-id> --repo abelxiaoxing/cadence -n npm-package -D <empty directory>
131
+ node scripts/npm-release.mjs check <that directory> <sha256>
132
+ ```
133
+
134
+ `check` exits 0 once the registry shows the version as `latest` with the audited digests, and 1 while it is still pending; mismatches refuse.
127
135
  Do not rerun the publish job or workflow, replay `npm publish`, move/delete its tag, or repair registry state automatically.
128
- A later matching readonly observation can confirm publication, but does not rewrite the earlier run's failed outcome; confirmation also cannot turn an originally failed publish command into a successful receipt.
136
+ A later matching observation confirms publication, but does not rewrite the earlier run's outcome or turn an originally failed publish command into a successful receipt.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.1.2",
3
+ "version": "2.1.4",
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",
@@ -382,15 +382,19 @@ class Feed {
382
382
  status:
383
383
  outcome === "completed"
384
384
  ? "done"
385
- : outcome === "rejected"
386
- ? "rejected"
385
+ : outcome === "rejected" ||
386
+ outcome === "partial" ||
387
+ outcome === "blocked"
388
+ ? outcome
387
389
  : outcome === "canceled"
388
390
  ? "cancelled"
389
391
  : "error",
390
392
  endedAt: this.now(),
391
393
  ...(outcome === "completed" ||
392
394
  outcome === "canceled" ||
393
- outcome === "rejected"
395
+ outcome === "rejected" ||
396
+ outcome === "partial" ||
397
+ outcome === "blocked"
394
398
  ? {}
395
399
  : { error: `${child.label} · ${outcome}` }),
396
400
  });
@@ -22,6 +22,8 @@ export type SubagentStatus =
22
22
  | "running"
23
23
  | "done"
24
24
  | "rejected"
25
+ | "partial"
26
+ | "blocked"
25
27
  | "error"
26
28
  | "cancelled";
27
29
  type Ended = Exclude<SubagentStatus, "running">;
@@ -56,7 +58,14 @@ export interface SubagentState {
56
58
  export const MAX_MESSAGES = 2000;
57
59
  /** Agents written into one card; more are counted, not listed. */
58
60
  export const MAX_CARD_AGENTS = 64;
59
- const ENDED = new Set(["done", "rejected", "error", "cancelled"]);
61
+ const ENDED = new Set([
62
+ "done",
63
+ "rejected",
64
+ "partial",
65
+ "blocked",
66
+ "error",
67
+ "cancelled",
68
+ ]);
60
69
 
61
70
  const record = (v: unknown): Record<string, unknown> | undefined =>
62
71
  v && typeof v === "object" && !Array.isArray(v)
@@ -266,6 +275,8 @@ const SYMBOL: Record<Ended, [string, PaintRole]> = {
266
275
  done: ["✔", "success"],
267
276
  error: ["✘", "error"],
268
277
  rejected: ["⊘", "accent"],
278
+ partial: ["◐", "accent"],
279
+ blocked: ["⊘", "accent"],
269
280
  cancelled: ["○", "muted"],
270
281
  };
271
282
  export function statusSymbol(
@@ -446,6 +457,8 @@ export function cardLines(
446
457
  card.agents.filter((a) => a.status === status).length;
447
458
  const failed = tally("error"),
448
459
  rejected = tally("rejected"),
460
+ partial = tally("partial"),
461
+ blocked = tally("blocked"),
449
462
  cancelled = tally("cancelled");
450
463
  const [symbol, role] =
451
464
  SYMBOL[
@@ -453,14 +466,18 @@ export function cardLines(
453
466
  ? "error"
454
467
  : rejected
455
468
  ? "rejected"
456
- : cancelled
457
- ? "cancelled"
458
- : "done"
469
+ : blocked
470
+ ? "blocked"
471
+ : partial
472
+ ? "partial"
473
+ : cancelled
474
+ ? "cancelled"
475
+ : "done"
459
476
  ];
460
477
  const kind = sharedKind(card.agents);
461
478
  const outcome =
462
- failed || rejected || cancelled
463
- ? ` · ${tally("done")} done${failed ? ` · ${failed} failed` : ""}${rejected ? ` · ${rejected} rejected` : ""}${
479
+ failed || rejected || partial || blocked || cancelled
480
+ ? ` · ${tally("done")} done${failed ? ` · ${failed} failed` : ""}${rejected ? ` · ${rejected} rejected` : ""}${partial ? ` · ${partial} partial` : ""}${blocked ? ` · ${blocked} blocked` : ""}${
464
481
  cancelled ? ` · ${cancelled} cancelled` : ""
465
482
  }`
466
483
  : "";
@@ -513,10 +530,12 @@ export function liveLines(f: LiveFrame, width: number, paint: Paint): string[] {
513
530
  const done = tally("done"),
514
531
  failed = tally("error"),
515
532
  rejected = tally("rejected"),
533
+ partial = tally("partial"),
534
+ blocked = tally("blocked"),
516
535
  cancelled = tally("cancelled");
517
536
  const counts = `${done ? ` · ${done} done` : ""}${
518
537
  failed ? ` · ${failed} failed` : ""
519
- }${rejected ? ` · ${rejected} rejected` : ""}${cancelled ? ` · ${cancelled} cancelled` : ""}`;
538
+ }${rejected ? ` · ${rejected} rejected` : ""}${partial ? ` · ${partial} partial` : ""}${blocked ? ` · ${blocked} blocked` : ""}${cancelled ? ` · ${cancelled} cancelled` : ""}`;
520
539
  const [spin, role] = statusSymbol(running[0], f.frame);
521
540
  const header = hinted(
522
541
  `${paint(role, spin)} ${running.length} ${noun(kind, running.length)} running${counts}`,
@@ -1,9 +1,10 @@
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 up to eight independent questions and the service runs them side by side. 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 with version:3. 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 on that step of the research summary (a step that reused an earlier answer names the identity it reused). 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. Investigate prerequisites first: worktrees do not inherit ignored dependencies. 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; only this run's confirmed merges can advance that target baseline for post-merge recovery. 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
+ 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. Investigate prerequisites first: 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; only this run's confirmed merges can advance that target baseline for post-merge recovery. 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
6
  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
+ 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.
7
8
  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, files outside the repository, or installations beyond the listed setup and policy. You cannot approve yourself. Vague acknowledgement is not consent.
8
9
  During accepted work the service owns progress, recovery and revision, and finishes without the user. Report actual cadence_status observations; do not start replacement workflows or ask for 'continue' after an individual child fails. Child failure is not delivery failure. Report recorded plan revisions as progress and lead with any recorded deviation when the run completes. Agents have no total runtime deadline; explicit command timeouts and actual closure still apply. A run stops only for a condition outside the repository; then explain that condition and the preserved outcomes, not a generic request to continue.
9
10
  For follow-up to a settled or interrupted run, inspect retained outcomes first. Partial outputs are not unexplained user edits. Unknown results must be observed and reconciled, never blindly replayed; a new delivery requires fresh approval. No automatic replay after owner restart. cadence_cancel is explicit cancellation, not navigation or exit. Worker prose is not passing checks; automatic review is never human review. Completion leaves Cadence ON and ready. Tools operate on the host; this is not a sandbox.`;
@@ -17,6 +17,7 @@ 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
21
  import {
21
22
  departure,
22
23
  NativeConnection,
@@ -25,15 +26,17 @@ import {
25
26
  import { decodeSessionId } from "./service/contracts/models.ts";
26
27
  import type { ChatTurn } from "./service/contracts/workbench.ts";
27
28
  import {
28
- decodeWorkflowPlan,
29
+ investigationId,
29
30
  readableDelivery,
30
31
  readableDeliveryRun,
31
32
  readableWorkflowPlan,
33
+ researchInput,
32
34
  type WorkflowProposal,
33
35
  type WorkflowRequest,
34
36
  type WorkflowResponse,
35
37
  type WorkflowRun,
36
38
  workflowDiagnostics,
39
+ workflowPlanInput,
37
40
  } from "./service/contracts/workflow.ts";
38
41
  import { ServiceCoordination } from "./service/coordination.ts";
39
42
  import { routeTableBrief } from "./service/project-knowledge.ts";
@@ -230,68 +233,6 @@ export function transcriptText(turn: ChatTurn | null): string {
230
233
  if (turn.notice) lines.push(turn.notice);
231
234
  return clip(lines.join("\n\n"), 48 * 1024);
232
235
  }
233
- const CHECK = Type.Object({
234
- name: Type.String(),
235
- command: Type.String(),
236
- timeoutMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 2147483647 })),
237
- });
238
- const READING = Type.Union([
239
- Type.Object({
240
- path: Type.String({ description: "Project document to read first." }),
241
- section: Type.Optional(
242
- Type.String({ description: "One heading of that document." }),
243
- ),
244
- reason: Type.String(),
245
- }),
246
- Type.Object({
247
- research: Type.String({
248
- description: "Identity of a recorded investigation to reuse.",
249
- }),
250
- reason: Type.String(),
251
- }),
252
- ]);
253
- const PLAN = Type.Object({
254
- goal: Type.String(),
255
- design: Type.String(),
256
- decisions: Type.String(),
257
- acceptance: Type.String(),
258
- version: Type.Literal(3),
259
- assumptions: Type.String({
260
- description:
261
- "What you decided on the user's behalf without asking; approval confirms it. Empty when there is none.",
262
- }),
263
- documents: Type.Array(
264
- Type.String({
265
- description: "Existing project Markdown this delivery may update.",
266
- }),
267
- { maxItems: 16 },
268
- ),
269
- reviewReads: Type.Array(READING, { maxItems: 16 }),
270
- policy: Type.Object({
271
- installs: Type.Boolean({
272
- description:
273
- "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
274
- }),
275
- }),
276
- tasks: Type.Array(
277
- Type.Object({
278
- id: Type.String(),
279
- title: Type.String(),
280
- instructions: Type.String(),
281
- writes: Type.Array(Type.String()),
282
- after: Type.Array(Type.String()),
283
- reads: Type.Array(READING, { maxItems: 16 }),
284
- }),
285
- { minItems: 1, maxItems: 16 },
286
- ),
287
- checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
288
- setup: Type.Array(CHECK, { maxItems: 4 }),
289
- baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
290
- delivery: Type.Union([
291
- Type.Literal("local-merge"),
292
- Type.Literal("working-copy"),
293
- ]),
294
- });
295
236
  /** The exact plan text, shown in full whether or not tool output is expanded.
296
237
  * Markdown needs Pi's initialized theme; plain text is the fallback. */
297
238
  function planComponent(text: string): Component {
@@ -424,7 +365,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
424
365
  context = ctx;
425
366
  };
426
367
  const summarize = (run: WorkflowRun) =>
427
- `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.childRunId ? ` · investigation ${s.childRunId}` : ""}: ${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.`;
368
+ `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.`;
428
369
  const agentDir = () => getAgentDir();
429
370
  /** The project's route table for this turn's system prompt. A turn never
430
371
  * fails because the table, or the workspace it is in, cannot be read. */
@@ -1017,21 +958,11 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1017
958
  name: "cadence_research",
1018
959
  label: "Investigate project",
1019
960
  description:
1020
- "Delegate up to eight focused, independent readonly investigations; the service runs as many at once as this machine is configured for. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
1021
- parameters: Type.Object({
1022
- goal: Type.String(),
1023
- questions: Type.Array(Type.String(), { minItems: 1, maxItems: 8 }),
1024
- roots: Type.Optional(
1025
- Type.Array(
1026
- Type.String({
1027
- description:
1028
- "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees.",
1029
- }),
1030
- { minItems: 1, maxItems: 8 },
1031
- ),
1032
- ),
1033
- }),
961
+ "Delegate focused, independent readonly investigations, as many as the goal needs; the service runs as many at once as this machine is configured for and queues the rest. Each answer is recorded under its investigation identity. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
962
+ parameters: RESEARCH_PARAMETERS,
1034
963
  async execute(_id, input, signal, update, ctx) {
964
+ // Refused by field name before anything is asked of the service.
965
+ const asked = researchInput(input);
1035
966
  return changing(ctx, async (claim) => {
1036
967
  active(ctx);
1037
968
  await connect(ctx);
@@ -1047,7 +978,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1047
978
  try {
1048
979
  response = await request(
1049
980
  ctx,
1050
- { action: "research", ...input, model },
981
+ { action: "research", ...asked, model },
1051
982
  commandId,
1052
983
  () => {
1053
984
  // Retain the attempted identity before transport: a lost reply is
@@ -1112,15 +1043,16 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1112
1043
  label: "Propose implementation plan",
1113
1044
  description:
1114
1045
  "Publish a readable delivery agreement: goal, acceptance, explicit decisions, your assumptions, initial route and assignments, what each reads first, checks, setup, documents to update and delivery policy. After one approval the service revises the route on its own and finishes without further confirmation. Does not execute.",
1115
- parameters: PLAN,
1046
+ parameters: PLAN_PARAMETERS,
1116
1047
  async execute(_id, input, _signal, _update, ctx) {
1048
+ // Refused by field name before anything is asked of the service.
1049
+ const plan = workflowPlanInput(input);
1117
1050
  return changing(ctx, async (claim) => {
1118
1051
  active(ctx);
1119
1052
  await connect(ctx);
1120
1053
  claim.assertCurrent();
1121
1054
  permission = undefined;
1122
1055
  const notice = await requireSettledRun(ctx, claim);
1123
- const plan = decodeWorkflowPlan(input);
1124
1056
  const response = await request(
1125
1057
  ctx,
1126
1058
  {
@@ -1,10 +1,20 @@
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
4
 
5
+ /** The parameters of the two tools a coordinator calls, declared once for the
6
+ * native extension and the browser coordinator. They state shape only: counts,
7
+ * sizes and references are checked by the service, which refuses naming the
8
+ * field (`workflowPlanInput`, `researchInput`), so a call is never rejected
9
+ * before the service has seen it for a bound the model could not know. */
4
10
  const CHECK = Type.Object({
5
11
  name: Type.String(),
6
12
  command: Type.String(),
7
- timeoutMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 2147483647 })),
13
+ timeoutMs: Type.Optional(
14
+ Type.Integer({
15
+ description: "Milliseconds, from 100. Leave out for no timeout.",
16
+ }),
17
+ ),
8
18
  });
9
19
  const READING = Type.Union([
10
20
  Type.Object({
@@ -16,48 +26,116 @@ const READING = Type.Union([
16
26
  }),
17
27
  Type.Object({
18
28
  research: Type.String({
19
- description: "Identity of a recorded investigation to reuse.",
29
+ description:
30
+ 'A recorded investigation: the "investigation" value of a completed research step.',
20
31
  }),
21
32
  reason: Type.String(),
22
33
  }),
23
34
  ]);
24
- const PLAN = Type.Object({
35
+ export const RESEARCH_PARAMETERS = Type.Object({
25
36
  goal: Type.String(),
26
- design: Type.String(),
27
- decisions: Type.String(),
28
- acceptance: Type.String(),
29
- version: Type.Literal(3),
30
- assumptions: Type.String({
31
- description:
32
- "What you decided on the user's behalf without asking; approval confirms it. Empty when there is none.",
33
- }),
34
- documents: Type.Array(
37
+ questions: Type.Array(
35
38
  Type.String({
36
- description: "Existing project Markdown this delivery may update.",
39
+ description: "One focused, independent question.",
37
40
  }),
38
- { maxItems: 16 },
41
+ {
42
+ description:
43
+ "Split independent questions freely; the service runs as many at once as this machine is configured for and queues the rest.",
44
+ },
45
+ ),
46
+ roots: Type.Optional(
47
+ Type.Array(
48
+ Type.String({
49
+ description:
50
+ "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees.",
51
+ }),
52
+ ),
53
+ ),
54
+ });
55
+ export const PLAN_PARAMETERS = Type.Object({
56
+ goal: Type.String(),
57
+ design: Type.String({ description: "The initial technical route." }),
58
+ decisions: Type.Optional(
59
+ Type.String({ description: "Explicit decisions and non-goals." }),
39
60
  ),
40
- reviewReads: Type.Array(READING, { maxItems: 16 }),
41
- policy: Type.Object({
42
- installs: Type.Boolean({
61
+ acceptance: Type.String(),
62
+ assumptions: Type.Optional(
63
+ Type.String({
43
64
  description:
44
- "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
65
+ "What you decided on the user's behalf without asking; approval confirms it. Leave out when there is none.",
45
66
  }),
46
- }),
67
+ ),
68
+ documents: Type.Optional(
69
+ Type.Array(
70
+ Type.String({
71
+ description: "Existing project Markdown this delivery may update.",
72
+ }),
73
+ ),
74
+ ),
75
+ reviewReads: Type.Optional(
76
+ Type.Array(READING, {
77
+ description: "What the independent review reads first.",
78
+ }),
79
+ ),
80
+ policy: Type.Optional(
81
+ Type.Object({
82
+ installs: Type.Optional(
83
+ Type.Boolean({
84
+ description:
85
+ "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
86
+ }),
87
+ ),
88
+ }),
89
+ ),
47
90
  tasks: Type.Array(
48
91
  Type.Object({
49
- id: Type.String(),
92
+ id: Type.String({
93
+ description:
94
+ "Lowercase letters, digits and hyphens, starting with a letter.",
95
+ }),
50
96
  title: Type.String(),
51
- instructions: Type.String(),
97
+ instructions: Type.String({ description: "At most 8KiB." }),
52
98
  writes: Type.Array(Type.String()),
53
- after: Type.Array(Type.String()),
54
- reads: Type.Array(READING, { maxItems: 16 }),
99
+ after: Type.Optional(
100
+ Type.Array(Type.String(), {
101
+ description:
102
+ "Ids of the assignments this one really depends on. Leave out when it depends on none.",
103
+ }),
104
+ ),
105
+ reads: Type.Optional(
106
+ Type.Array(READING, {
107
+ description: "The few things this assignment should read first.",
108
+ }),
109
+ ),
55
110
  }),
56
- { minItems: 1, maxItems: 16 },
111
+ { description: "One to 16 assignments." },
57
112
  ),
58
- checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
59
- setup: Type.Array(CHECK, { maxItems: 4 }),
60
- baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
113
+ checks: Type.Array(CHECK, {
114
+ description: "The real acceptance commands: at least one, at most 16.",
115
+ }),
116
+ setup: Type.Optional(
117
+ Type.Array(
118
+ Type.Object({
119
+ ...CHECK.properties,
120
+ placement: Type.Union(
121
+ [
122
+ Type.Literal("target"),
123
+ Type.Literal("candidate"),
124
+ Type.Literal("worktree"),
125
+ ],
126
+ {
127
+ description:
128
+ "target: preflight once in the original checkout before creating worktrees; candidate: once in the stable candidate; worktree: prepare the candidate and every detached child. Target branch checks belong to target, never worktree. Commands do not export environment into later processes.",
129
+ },
130
+ ),
131
+ }),
132
+ {
133
+ description:
134
+ "Explicit preparation commands with their execution placement, at most four. Run in target, candidate, then worktree stages, preserving order within each stage.",
135
+ },
136
+ ),
137
+ ),
138
+ baselineChecks: Type.Optional(Type.Array(CHECK)),
61
139
  delivery: Type.Union([
62
140
  Type.Literal("local-merge"),
63
141
  Type.Literal("working-copy"),
@@ -85,7 +163,7 @@ export function createCoordinatorTools() {
85
163
  if (
86
164
  !reply ||
87
165
  typeof reply !== "object" ||
88
- Buffer.byteLength(JSON.stringify(reply)) > 65536
166
+ Buffer.byteLength(JSON.stringify(reply)) > LIMITS.coordinatorBytes
89
167
  )
90
168
  return closed();
91
169
  const p = pending.get(reply.id);
@@ -96,34 +174,29 @@ export function createCoordinatorTools() {
96
174
  content: [{ type: "text", text: reply.text }],
97
175
  details: undefined,
98
176
  });
99
- else p.reject(new Error("Coordinator refused this request"));
177
+ // The service did nothing; its fixed code says why it could not.
178
+ else
179
+ p.reject(
180
+ new Error(
181
+ typeof reply.code === "string" && /^[a-z-]{1,40}$/.test(reply.code)
182
+ ? `The service refused this call (${reply.code}); nothing was started or published.`
183
+ : "The service refused this call; nothing was started or published.",
184
+ ),
185
+ );
100
186
  };
101
187
  process.on("message", receive);
102
188
  const tools = [
103
189
  {
104
190
  name: "cadence_research",
105
191
  description:
106
- "Investigate bounded project questions with readonly subagents; returns recorded evidence. Never edits.",
107
- parameters: Type.Object({
108
- goal: Type.String(),
109
- // Split independent questions freely; the owner bounds how many run at once.
110
- questions: Type.Array(Type.String(), { minItems: 1, maxItems: 8 }),
111
- roots: Type.Optional(
112
- Type.Array(
113
- Type.String({
114
- description:
115
- "Specific investigation directories; defaults to project cwd. Avoid filesystem roots and broad parent trees.",
116
- }),
117
- { minItems: 1, maxItems: 8 },
118
- ),
119
- ),
120
- }),
192
+ "Investigate focused, independent project questions with readonly subagents, as many as the goal needs; returns each question's recorded answer and its investigation identity. Never edits.",
193
+ parameters: RESEARCH_PARAMETERS,
121
194
  },
122
195
  {
123
196
  name: "cadence_plan",
124
197
  description:
125
- "Publish a complete proposal after decisions are aligned. This never authorizes execution. The user sees an exact plan card.",
126
- parameters: PLAN,
198
+ "Publish a complete proposal after decisions are aligned. This never authorizes execution. The user sees an exact plan card. goal, design, decisions, assumptions and acceptance together fit 32KiB, because every worker is given them.",
199
+ parameters: PLAN_PARAMETERS,
127
200
  },
128
201
  {
129
202
  name: "cadence_status",
@@ -138,8 +211,10 @@ export function createCoordinatorTools() {
138
211
  if (retiring) throw new Error("Coordinator closed");
139
212
  if (signal?.aborted) throw new Error("Coordinator canceled");
140
213
  const request = { id: ++counter, name: tool.name, args };
141
- if (Buffer.byteLength(JSON.stringify(request)) > 65536)
142
- throw new Error("Coordinator request exceeds bound");
214
+ if (Buffer.byteLength(JSON.stringify(request)) > LIMITS.coordinatorBytes)
215
+ throw new Error(
216
+ `This call is larger than ${LIMITS.coordinatorBytes} bytes and was not sent; nothing happened.`,
217
+ );
143
218
  const original = chain.then(
144
219
  () =>
145
220
  new Promise((resolve, reject) => {