@abelxiaoxing/cadence 2.1.13 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.1.13",
3
+ "version": "2.2.0",
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; 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.
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,66 @@ 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.Object(
105
+ { question: Type.String(), option: Type.String() },
106
+ {
107
+ description:
108
+ "Only relevant for this earlier question and selected option.",
109
+ },
110
+ ),
111
+ ),
112
+ }),
113
+ ),
114
+ });
55
115
  export const PLAN_PARAMETERS = Type.Object({
56
116
  goal: Type.String(),
57
117
  design: Type.String({ description: "The initial technical route." }),
@@ -186,6 +246,18 @@ export function createCoordinatorTools() {
186
246
  };
187
247
  process.on("message", receive);
188
248
  const tools = [
249
+ {
250
+ name: "cadence_knowledge",
251
+ description:
252
+ "Read current checkout preparation facts, a project heading, a literal in one source file, or a retained investigation with its citations rechecked.",
253
+ parameters: KNOWLEDGE_PARAMETERS,
254
+ },
255
+ {
256
+ name: "cadence_design",
257
+ description:
258
+ "Show all material product choices, recommendations, tradeoffs and affected acceptance together. End this turn after publication. Only the user submits design choices.",
259
+ parameters: DESIGN_PARAMETERS,
260
+ },
189
261
  {
190
262
  name: "cadence_research",
191
263
  description:
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "103e212eee402600c29002528ccc3808b6fbe11ccee275a4d5f2a3d52576c520",
5
+ "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243",
6
6
  } as const;
@@ -0,0 +1,217 @@
1
+ /** One batch of product decisions, shared by the terminal, browser and owner. */
2
+ import {
3
+ bool,
4
+ ContractError,
5
+ canonicalJson,
6
+ closed,
7
+ decodeId,
8
+ integer,
9
+ list,
10
+ text,
11
+ } from "./core.ts";
12
+
13
+ export interface DesignQuestion {
14
+ id: string;
15
+ question: string;
16
+ options: { id: string; label: string; cost: string }[];
17
+ recommended: string;
18
+ reason: string;
19
+ acceptance: string;
20
+ when?: { question: string; option: string };
21
+ }
22
+ export type DesignAnswer =
23
+ | { question: string; option: string }
24
+ | { question: string; other: string };
25
+ export interface DesignDraft {
26
+ revision: number;
27
+ id: string;
28
+ questions: DesignQuestion[];
29
+ answers: DesignAnswer[];
30
+ submitted: boolean;
31
+ }
32
+ const label = (v: unknown) => text(v, 1024, true);
33
+ const key = (v: unknown) => {
34
+ const s = text(v, 48, true);
35
+ if (!/^[a-z][a-z0-9-]*$/u.test(s))
36
+ throw new Error("id: use lowercase letters, digits and hyphens");
37
+ return s;
38
+ };
39
+ export function designQuestions(input: unknown): DesignQuestion[] {
40
+ const { questions } = closed(input, ["questions"]);
41
+ 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) };
56
+ });
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");
76
+ seen.set(id, ids);
77
+ return {
78
+ id,
79
+ question: label(q.question),
80
+ options,
81
+ recommended,
82
+ reason: label(q.reason),
83
+ acceptance: label(q.acceptance),
84
+ ...(when ? { when } : {}),
85
+ };
86
+ });
87
+ if (!rows.length)
88
+ throw new Error("questions: supply a material product decision");
89
+ canonicalJson(rows, 24 * 1024);
90
+ return rows;
91
+ }
92
+ export function designAnswers(v: unknown): DesignAnswer[] {
93
+ return list(v, 12, (raw) => {
94
+ const other = Object.hasOwn(raw ?? {}, "other");
95
+ const a = closed(raw, ["question", other ? "other" : "option"]);
96
+ const question = key(a.question);
97
+ return other
98
+ ? { question, other: label(a.other) }
99
+ : { question, option: key(a.option) };
100
+ });
101
+ }
102
+ export function available(q: DesignQuestion, answers: DesignAnswer[]) {
103
+ const dep = q.when;
104
+ return (
105
+ !dep ||
106
+ answers.some(
107
+ (a) =>
108
+ a.question === dep.question && "option" in a && a.option === dep.option,
109
+ )
110
+ );
111
+ }
112
+ /** Recompute in dependency order. Unrelated answers survive edits. */
113
+ export function selectDesign(
114
+ questions: DesignQuestion[],
115
+ choices: DesignAnswer[],
116
+ fill = false,
117
+ ) {
118
+ const answers: DesignAnswer[] = [];
119
+ const indexed = new Map(choices.map((a) => [a.question, a]));
120
+ if (
121
+ indexed.size !== choices.length ||
122
+ choices.some((a) => !questions.some((q) => q.id === a.question))
123
+ )
124
+ throw new ContractError("invalid");
125
+ for (const q of questions) {
126
+ if (!available(q, answers)) continue;
127
+ const a = indexed.get(q.id);
128
+ if (a && "option" in a && !q.options.some((o) => o.id === a.option))
129
+ throw new ContractError("invalid");
130
+ if (a) answers.push(a);
131
+ else if (fill) answers.push({ question: q.id, option: q.recommended });
132
+ }
133
+ return answers;
134
+ }
135
+ export function decodeDesign(v: unknown): DesignDraft {
136
+ const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
137
+ const questions = designQuestions({ questions: o.questions });
138
+ const submitted = bool(o.submitted);
139
+ const answers = designAnswers(o.answers);
140
+ if (
141
+ canonicalJson(selectDesign(questions, answers, submitted)) !==
142
+ canonicalJson(answers)
143
+ )
144
+ throw new ContractError("invalid");
145
+ return {
146
+ id: decodeId(o.id),
147
+ revision: integer(o.revision, 1),
148
+ questions,
149
+ answers,
150
+ submitted,
151
+ };
152
+ }
153
+ export function newDesign(
154
+ id: string,
155
+ input: unknown,
156
+ previous?: DesignDraft,
157
+ ): DesignDraft {
158
+ const questions = designQuestions(input);
159
+ const retained =
160
+ previous?.answers.filter((a) => {
161
+ const before = previous.questions.find((q) => q.id === a.question);
162
+ const after = questions.find((q) => q.id === a.question);
163
+ return before && after && canonicalJson(before) === canonicalJson(after);
164
+ }) ?? [];
165
+ return {
166
+ id,
167
+ revision: 1,
168
+ questions,
169
+ answers: selectDesign(questions, retained),
170
+ submitted: false,
171
+ };
172
+ }
173
+ export function answerText(q: DesignQuestion, a?: DesignAnswer) {
174
+ return (
175
+ a &&
176
+ ("other" in a ? a.other : q.options.find((o) => o.id === a.option)?.label)
177
+ );
178
+ }
179
+ export function designSummary(d: DesignDraft) {
180
+ return d.questions
181
+ .filter((q) => available(q, d.answers))
182
+ .map(
183
+ (q) =>
184
+ `- ${q.question} — ${
185
+ answerText(
186
+ q,
187
+ d.answers.find((a) => a.question === q.id),
188
+ ) ?? "…"
189
+ }\n Acceptance: ${q.acceptance}`,
190
+ )
191
+ .join("\n");
192
+ }
193
+ /** The turn retains its visible decisions where they fit. The owner keeps
194
+ * the full revision and exposes it to the coordinator in either case. */
195
+ export function designMessage(d: DesignDraft, maximum: number) {
196
+ const summary = designSummary(d);
197
+ return new TextEncoder().encode(summary).length <= maximum
198
+ ? summary
199
+ : `Submit design ${d.id}, revision ${d.revision}. Read the confirmed decisions in cadence_status and publish the implementation plan.`;
200
+ }
201
+ export const recommendsDesign = (s: string) =>
202
+ /^(?:按你推荐的来|采用全部推荐|use (?:all |your )?recommendations)[。.!!]?$/iu.test(
203
+ s.trim(),
204
+ );
205
+
206
+ export function reviseDesign(
207
+ d: DesignDraft,
208
+ answers: DesignAnswer[],
209
+ submit: boolean,
210
+ ): DesignDraft {
211
+ return {
212
+ ...d,
213
+ revision: d.revision + 1,
214
+ answers: selectDesign(d.questions, answers, submit),
215
+ submitted: submit,
216
+ };
217
+ }