@alterset/alterspec-client 0.9.0 → 0.11.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/dist/cli.js CHANGED
@@ -333,24 +333,31 @@ import { z as z3 } from "zod";
333
333
  var CODE = "[A-Z]{2,6}";
334
334
  var NAME = "[A-Z0-9]+(?:-[A-Z0-9]+)*";
335
335
  var CHANNEL_CODE = "[A-Z]{2,5}";
336
+ var DRAFT_NUMBER = "T\\d[A-Z0-9]{3}";
337
+ var N2 = `(?:\\d{2}|${DRAFT_NUMBER})`;
338
+ var N3 = `(?:\\d{3}|${DRAFT_NUMBER})`;
339
+ var CAPABILITY_ID = `CAP-${CODE}-${N3}`;
340
+ var SCREEN_ID = `SCR-${CODE}-${N2}`;
341
+ var APP_RULE_ID = `RULE-${N3}`;
342
+ var DECISION_ID = `DEC-${N3}`;
336
343
  var ID_PATTERNS = {
337
344
  app: "^APP$",
338
345
  module: `^MOD-${CODE}$`,
339
- capability: `^CAP-${CODE}-\\d{3}$`,
340
- screen: `^SCR-${CODE}-\\d{2}$`,
346
+ capability: `^${CAPABILITY_ID}$`,
347
+ screen: `^${SCREEN_ID}$`,
341
348
  role: `^ROLE-${NAME}$`,
342
349
  persona: `^PER-${NAME}$`,
343
350
  entity: `^ENT-${NAME}$`,
344
- rule: `^RULE-(?:${CODE}-)?\\d{3}$`,
345
- flow: "^FLOW-\\d{3}$",
351
+ rule: `^RULE-(?:${CODE}-)?${N3}$`,
352
+ flow: `^FLOW-${N3}$`,
346
353
  event: `^EVT-${NAME}$`,
347
- decision: "^DEC-\\d{3}$",
348
- change: "^CHG-\\d{3}$",
354
+ decision: `^${DECISION_ID}$`,
355
+ change: `^CHG-${N3}$`,
349
356
  integration: `^INT-${NAME}$`,
350
- nfr: "^NFR-\\d{3}$",
351
- acceptance: `^CAP-${CODE}-\\d{3}-AC-\\d{2}$`,
357
+ nfr: `^NFR-${N3}$`,
358
+ acceptance: `^${CAPABILITY_ID}-AC-\\d{2}$`,
352
359
  screenAction: "^A\\d{2}$",
353
- experience: `^UX-SCR-${CODE}-\\d{2}-${CHANNEL_CODE}$`
360
+ experience: `^UX-${SCREEN_ID}-${CHANNEL_CODE}$`
354
361
  };
355
362
  var ID_REGEX = Object.fromEntries(
356
363
  Object.entries(ID_PATTERNS).map(([k, p]) => [k, new RegExp(p)])
@@ -382,6 +389,9 @@ var codeInId = (id) => /^(?:CAP|SCR|RULE)-([A-Z]{2,6})-/.exec(id)?.[1];
382
389
  function idKind(id) {
383
390
  return Object.keys(ID_REGEX).find((k) => ID_REGEX[k].test(id));
384
391
  }
392
+ var DRAFT = new RegExp(
393
+ `^(?:CHG|FLOW|DEC|NFR|RULE|(?:CAP|SCR|RULE)-${CODE}|UX-SCR-${CODE})-${DRAFT_NUMBER}(?:-|$)`
394
+ );
385
395
 
386
396
  // ../src/schemas/common.ts
387
397
  var Status = z4.enum(["draft", "ready", "signed_off"], {
@@ -452,6 +462,11 @@ var ChangeSchema = z5.object({
452
462
  * rewritten, so a channel added later gives an old change no task.
453
463
  */
454
464
  tracks: z5.record(TrackCode, z5.array(z5.string())).optional(),
465
+ /**
466
+ * In a team project: the draft IDs the change and what it creates carried until the sign-off numbered them
467
+ * (draft → final). Written by the CLI at sign-off.
468
+ */
469
+ drafted_as: z5.record(z5.string(), z5.string()).optional(),
455
470
  /** The first 16 hex of the sha256 of the change's `delta.json`, written with it at sign-off, never rewritten. */
456
471
  delta: z5.string().regex(/^[0-9a-f]{16}$/).optional()
457
472
  }).strict().superRefine((c, ctx) => {
@@ -554,6 +569,9 @@ var patternsPath = (code) => `${surfaceDir(code)}/patterns.md`;
554
569
  var designSystemPath = (code) => `${surfaceDir(code)}/design-system.md`;
555
570
  var OPERATIONS_FILE = "_generated/operations.md";
556
571
  var INDEX_FILE = "_generated/index.json";
572
+ var CONTRACT = new RegExp(
573
+ `^modules/[^/]+/screens/(?<screen>${SCREEN_ID})/experience/(?<code>[a-z]{2,5})\\.md$`
574
+ );
557
575
  var changesDir = (mod) => mod ? `${moduleDir(mod)}/${CHANGES_DIR}` : CHANGES_DIR;
558
576
  var archiveDir = (mod) => `${changesDir(mod)}/archive`;
559
577
  var CHANGE_PREFIX = String.raw`^(?:${MODULES_DIR}\/[^/]+\/)?${CHANGES_DIR}\/`;
@@ -576,6 +594,7 @@ var slug = (text) => text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase(
576
594
  var shardDir = (path) => `${SHARDS_DIR}/${path.replace(/\.md$/, "")}`;
577
595
  var itemShardName = (key) => `${key.startsWith("term:") ? slug(key.slice(5)) : key}.md`;
578
596
  var itemShardPath = (path, key) => `${shardDir(path)}/${itemShardName(key)}`;
597
+ var FRONT_MATTER_SHARD = "00-front-matter.yaml";
579
598
  var isSectionShard = (name, heading) => new RegExp(`^\\d{2}-${slug(heading)}\\.md$`).test(name);
580
599
 
581
600
  // ../src/export/read.ts
@@ -773,6 +792,242 @@ function criterionParts(chunk) {
773
792
  };
774
793
  }
775
794
 
795
+ // src/questions.ts
796
+ import { z as z7 } from "zod";
797
+
798
+ // src/mcp.ts
799
+ import { createInterface } from "readline";
800
+ var isRequest = (m) => m.method !== void 0 && m.id !== void 0;
801
+ async function callTool(session, name, args = {}) {
802
+ const res = await session.fetch("/mcp", {
803
+ method: "POST",
804
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
805
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } })
806
+ });
807
+ const text = await res.text();
808
+ if (!res.ok)
809
+ throw new DispatcherError(`HTTP_${res.status}`, `The dispatcher answered ${res.status}.`, res.status);
810
+ const answer = messagesOf(res.headers.get("content-type") ?? "", text)[0];
811
+ if (!answer?.result)
812
+ throw new DispatcherError(
813
+ "MCP_ERROR",
814
+ answer?.error?.message ?? `The dispatcher gave no answer to ${name}.`
815
+ );
816
+ const out = answer.result.structuredContent ?? {};
817
+ if (answer.result.isError) {
818
+ const err = out.error;
819
+ throw new DispatcherError(
820
+ err?.code ?? "TOOL_ERROR",
821
+ err?.message ?? answer.result.content?.map((c) => c.text ?? "").join("\n") ?? `${name} failed.`
822
+ );
823
+ }
824
+ return out;
825
+ }
826
+ function messagesOf(contentType, text) {
827
+ if (!text.trim()) return [];
828
+ if (!contentType.includes("text/event-stream")) return [JSON.parse(text)];
829
+ const out = [];
830
+ for (const event of text.split(/\r?\n\r?\n/)) {
831
+ const data = event.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
832
+ if (data.trim()) out.push(JSON.parse(data));
833
+ }
834
+ return out;
835
+ }
836
+ function runProxy(opts) {
837
+ const { session, input, output, version } = opts;
838
+ const log = opts.log ?? ((line) => process.stderr.write(`alterspec-client: ${line}
839
+ `));
840
+ let protocolVersion;
841
+ const pending = /* @__PURE__ */ new Set();
842
+ const send = (message) => void output.write(JSON.stringify(message) + "\n");
843
+ const result = (id, value) => send({ jsonrpc: "2.0", id, result: value });
844
+ const error = (id, message, code = -32e3) => send({ jsonrpc: "2.0", id, error: { code, message } });
845
+ function refused(m, e) {
846
+ if (!isRequest(m)) return;
847
+ const id = m.id;
848
+ switch (m.method) {
849
+ case "initialize":
850
+ return result(id, {
851
+ protocolVersion: m.params?.protocolVersion ?? "2025-06-18",
852
+ capabilities: { tools: {} },
853
+ serverInfo: { name: "alterspec-client", version },
854
+ instructions: e.advice
855
+ });
856
+ case "ping":
857
+ return result(id, {});
858
+ case "tools/list":
859
+ return result(id, {
860
+ tools: [
861
+ {
862
+ name: "whoami",
863
+ description: "Who you are to the dispatcher. Your SSH key is refused: this says what to do.",
864
+ inputSchema: { type: "object", properties: {} }
865
+ }
866
+ ]
867
+ });
868
+ case "tools/call":
869
+ return result(id, {
870
+ content: [{ type: "text", text: e.advice }],
871
+ structuredContent: {
872
+ error: { code: e.code, message: e.advice },
873
+ key: { line: e.key.line, fingerprint: e.key.fingerprint }
874
+ },
875
+ isError: true
876
+ });
877
+ default:
878
+ return error(id, e.advice);
879
+ }
880
+ }
881
+ async function forward(m) {
882
+ try {
883
+ const headers = {
884
+ "content-type": "application/json",
885
+ accept: "application/json, text/event-stream"
886
+ };
887
+ if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
888
+ const res = await session.fetch("/mcp", { method: "POST", headers, body: JSON.stringify(m) });
889
+ const text = await res.text();
890
+ if (!res.ok && res.status !== 202) {
891
+ let message = `The dispatcher answered ${res.status}.`;
892
+ try {
893
+ message = JSON.parse(text).error?.message ?? message;
894
+ } catch {
895
+ }
896
+ if (isRequest(m)) error(m.id, message);
897
+ return;
898
+ }
899
+ for (const answer of messagesOf(res.headers.get("content-type") ?? "", text)) {
900
+ const pv = answer.result?.protocolVersion;
901
+ if (m.method === "initialize" && typeof pv === "string") protocolVersion = pv;
902
+ send(answer);
903
+ }
904
+ } catch (e) {
905
+ if (e instanceof KeyRefused) {
906
+ log(e.advice.split("\n")[0]);
907
+ return refused(m, e);
908
+ }
909
+ const message = e instanceof DispatcherError ? e.message : `The client failed: ${e.message}`;
910
+ log(message);
911
+ if (!isRequest(m)) return;
912
+ if (m.method === "tools/call")
913
+ return result(m.id, { content: [{ type: "text", text: message }], isError: true });
914
+ error(m.id, message);
915
+ }
916
+ }
917
+ return new Promise((resolve3) => {
918
+ const lines = createInterface({ input, crlfDelay: Infinity });
919
+ lines.on("line", (line) => {
920
+ if (!line.trim()) return;
921
+ let m;
922
+ try {
923
+ m = JSON.parse(line);
924
+ } catch {
925
+ return error(null, "Parse error: not a JSON-RPC message.", -32700);
926
+ }
927
+ const p = forward(m).finally(() => pending.delete(p));
928
+ pending.add(p);
929
+ });
930
+ lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve3()));
931
+ });
932
+ }
933
+
934
+ // src/questions.ts
935
+ var AnswerSchema = z7.object({
936
+ developer: z7.string(),
937
+ at: z7.string(),
938
+ text: z7.string(),
939
+ verdict: z7.enum(["confirmed", "corrected"]).nullish(),
940
+ change: z7.string().nullish()
941
+ });
942
+ var QuestionSchema = z7.object({
943
+ id: z7.string(),
944
+ task: z7.string().nullish(),
945
+ item: z7.string().nullish(),
946
+ developer: z7.string(),
947
+ at: z7.string(),
948
+ question: z7.string(),
949
+ outcome: z7.enum(["spec", "assumed", "open"]),
950
+ status: z7.enum(["open", "answered"]),
951
+ cites: z7.array(z7.string()).default([]),
952
+ answer: z7.string().nullish(),
953
+ assumption: z7.string().nullish(),
954
+ corrected: z7.boolean().optional(),
955
+ answers: z7.array(AnswerSchema).default([])
956
+ });
957
+ var QuestionsError = class extends Error {
958
+ };
959
+ var PART2 = /^(.+?)(?:-AC-\d+|\.A\d+|#[\w-]+)$/;
960
+ function missingCites(x, refs) {
961
+ const held = (ref) => {
962
+ if (x.sources.has(ref)) return true;
963
+ const owner = PART2.exec(ref)?.[1];
964
+ if (owner && x.sources.has(owner)) {
965
+ if (ref.includes("#")) return true;
966
+ const text = x.read(x.fileOf(owner) ?? "") ?? "";
967
+ const action = /\.(A\d+)$/.exec(ref)?.[1];
968
+ return action ? new RegExp(`\\bid: ${action}\\b`).test(text) : text.includes(ref);
969
+ }
970
+ return /[/.]/.test(ref) && !ref.includes("..") && !ref.startsWith("/") && x.has(ref);
971
+ };
972
+ return refs.filter((r) => !held(r));
973
+ }
974
+ async function listQuestions(session, filter = {}) {
975
+ const answer = await callTool(session, "questions", {
976
+ ...filter.task ? { task: filter.task } : filter.about ? { about: filter.about } : { mine: true },
977
+ ...filter.open ? { status: "open" } : {}
978
+ });
979
+ const parsed = z7.array(QuestionSchema).safeParse(answer.questions ?? []);
980
+ if (!parsed.success)
981
+ throw new QuestionsError("The dispatcher\u2019s questions are not in a form this client reads.");
982
+ return parsed.data;
983
+ }
984
+ async function taskQuestions(session, task) {
985
+ try {
986
+ return await listQuestions(session, { task });
987
+ } catch {
988
+ return void 0;
989
+ }
990
+ }
991
+ var holding = (q) => q.answers.at(-1);
992
+ var isCorrected = (q) => q.corrected ?? holding(q)?.verdict === "corrected";
993
+ function sortQuestions(questions) {
994
+ const rank = (q) => isCorrected(q) ? 0 : q.status === "open" ? 1 : 2;
995
+ return [...questions].sort((a, b) => rank(a) - rank(b));
996
+ }
997
+ var one = (text) => text.replace(/\s+/g, " ").trim();
998
+ function questionLines(q) {
999
+ const about = [q.task, q.item].filter(Boolean).join(" ");
1000
+ const last = holding(q);
1001
+ const state = isCorrected(q) ? "ASSUMPTION CORRECTED" : last ? q.outcome === "assumed" ? "assumption confirmed" : "answered by the product side" : q.outcome === "spec" ? "answered from the spec" : q.outcome === "assumed" ? "open, working on an assumption" : "open, waiting for the product side";
1002
+ const lines = [`- ${q.id} (${state}${about ? `; ${about}` : ""}): ${one(q.question)}`];
1003
+ if (q.outcome === "assumed" && q.assumption) lines.push(` - Assumed: ${one(q.assumption)}`);
1004
+ if (q.outcome === "spec" && q.answer)
1005
+ lines.push(` - From the spec: ${one(q.answer)}${q.cites.length ? ` (${q.cites.join(", ")})` : ""}`);
1006
+ if (last)
1007
+ lines.push(
1008
+ ` - Product side (${last.developer}, ${last.at.slice(0, 10)}): ${one(last.text)}${last.change ? ` It comes into the spec with ${last.change}.` : ""}`
1009
+ );
1010
+ return lines;
1011
+ }
1012
+ function questionsText(questions) {
1013
+ if (!questions.length) return "No questions.\n";
1014
+ return sortQuestions(questions).flatMap(questionLines).join("\n") + "\n";
1015
+ }
1016
+ function questionsSection(questions) {
1017
+ if (!questions.length) return [];
1018
+ const sorted = sortQuestions(questions);
1019
+ const corrected = sorted.filter(isCorrected).length;
1020
+ const open = sorted.filter((q) => q.status === "open").length;
1021
+ return [
1022
+ `## Questions (${open} open${corrected ? `, ${corrected} corrected` : ""})`,
1023
+ "",
1024
+ corrected ? "A corrected assumption is rework: what was built on it follows the product side\u2019s answer before the task is done." : "What was asked about this task. An open one on an assumption may still be corrected; an item waiting for an answer stays uncovered.",
1025
+ "",
1026
+ ...sorted.flatMap(questionLines),
1027
+ ""
1028
+ ];
1029
+ }
1030
+
776
1031
  // src/context.ts
777
1032
  var ContextError = class extends Error {
778
1033
  };
@@ -973,7 +1228,7 @@ function whereUsed(x, objects, entries, changed) {
973
1228
  }
974
1229
  return out;
975
1230
  }
976
- function taskContext(x, task, exportDir2, state = {}) {
1231
+ function taskContext(x, task, exportDir2, state = {}, questions) {
977
1232
  const change = x.work.changes.find((c) => c.id === task.change);
978
1233
  if (!change) throw new ContextError(`${task.change} is not in this export's work.json: pull the export.`);
979
1234
  const work = change.tasks.find((t) => t.track === task.track);
@@ -990,6 +1245,7 @@ function taskContext(x, task, exportDir2, state = {}) {
990
1245
  const items = work.items;
991
1246
  const ctx = {
992
1247
  task: task.id,
1248
+ ...questions ? { questions } : {},
993
1249
  ...items ? {
994
1250
  checklist: {
995
1251
  items: items.map((item) => {
@@ -1153,6 +1409,7 @@ function renderContext(c) {
1153
1409
  ];
1154
1410
  if (c.after.length) out.push("", `Waits for: ${c.after.map((a) => `${a.change}/${a.track}`).join(", ")}.`);
1155
1411
  out.push("");
1412
+ if (c.questions?.length) out.push(...questionsSection(c.questions));
1156
1413
  if (!c.checklist)
1157
1414
  out.push("This export has no checklist (work.json format 1): the task\u2019s progress is its status only.");
1158
1415
  else {
@@ -1608,6 +1865,11 @@ function buildClientPlan(version) {
1608
1865
  content: f.content,
1609
1866
  policy: "wrapper"
1610
1867
  })),
1868
+ ...assetFiles("agents").map((f) => ({
1869
+ path: `.claude/agents/${f.rel}`,
1870
+ content: f.content,
1871
+ policy: "wrapper"
1872
+ })),
1611
1873
  ...assetFiles("prompts").map((f) => ({
1612
1874
  path: `${PROMPTS_DIR}/${f.rel}`,
1613
1875
  content: f.content,
@@ -1728,140 +1990,307 @@ function initClient(root, opts, version) {
1728
1990
  return { config, mcp, hook, approval, ignore, files };
1729
1991
  }
1730
1992
 
1731
- // src/mcp.ts
1732
- import { createInterface } from "readline";
1733
- var isRequest = (m) => m.method !== void 0 && m.id !== void 0;
1734
- async function callTool(session, name, args = {}) {
1735
- const res = await session.fetch("/mcp", {
1736
- method: "POST",
1737
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
1738
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } })
1739
- });
1740
- const text = await res.text();
1741
- if (!res.ok)
1742
- throw new DispatcherError(`HTTP_${res.status}`, `The dispatcher answered ${res.status}.`, res.status);
1743
- const answer = messagesOf(res.headers.get("content-type") ?? "", text)[0];
1744
- if (!answer?.result)
1745
- throw new DispatcherError(
1746
- "MCP_ERROR",
1747
- answer?.error?.message ?? `The dispatcher gave no answer to ${name}.`
1748
- );
1749
- const out = answer.result.structuredContent ?? {};
1750
- if (answer.result.isError) {
1751
- const err = out.error;
1752
- throw new DispatcherError(
1753
- err?.code ?? "TOOL_ERROR",
1754
- err?.message ?? answer.result.content?.map((c) => c.text ?? "").join("\n") ?? `${name} failed.`
1993
+ // ../src/lib/names.ts
1994
+ var normalizeName = (s) => s.toLowerCase().replace(/[_\-./]+/g, " ").replace(/[^\p{L}\p{N} ]+/gu, "").replace(/\s+/g, " ").trim();
1995
+ function aliasGroups(glossary) {
1996
+ const groups = glossary.map(
1997
+ (g) => new Set([g.term, ...g.forbidden ?? []].map(normalizeName))
1998
+ );
1999
+ return (name) => {
2000
+ const n = normalizeName(name);
2001
+ const out = /* @__PURE__ */ new Set([n]);
2002
+ for (const g of groups) if (g.has(n)) for (const x of g) out.add(x);
2003
+ return out;
2004
+ };
2005
+ }
2006
+
2007
+ // src/lookup.ts
2008
+ var ID_KINDS = [
2009
+ "acceptance",
2010
+ "screenAction",
2011
+ "experience",
2012
+ "capability",
2013
+ "screen",
2014
+ "entity",
2015
+ "rule",
2016
+ "event",
2017
+ "decision",
2018
+ "role",
2019
+ "persona",
2020
+ "flow",
2021
+ "integration",
2022
+ "nfr",
2023
+ "module"
2024
+ ];
2025
+ var READ = {
2026
+ capability: [
2027
+ "Acceptance criteria",
2028
+ "Alternative and exception flows",
2029
+ "Permissions and data visibility",
2030
+ "Main flow"
2031
+ ],
2032
+ entity: ["Attributes", "Lifecycle"],
2033
+ screen: ["Displayed data", "Actions", "Business states", "Per-role differences"],
2034
+ experience: ["Interactions", "Validation messages", "Loading and errors"],
2035
+ flow: ["Steps"]
2036
+ };
2037
+ var SILENCE = ["Out of scope", "Open questions"];
2038
+ var VIEWS = [
2039
+ ["_generated/role-matrix.md", "who may perform a capability, and with which scope"],
2040
+ ["_generated/visibility.md", "which states of a record a role sees"],
2041
+ ["_generated/rule-matrix.md", "where a rule is enforced, what triggers it, which criteria cover it"],
2042
+ ["_generated/channel-matrix.md", "on which channel and screen a capability is performed"],
2043
+ ["_generated/navigation.md", "how a screen is reached and where its actions lead"],
2044
+ ["_generated/traceability.md", "the order of a flow\u2019s steps and what joins them"],
2045
+ ["_generated/operations.md", "what other systems may do"]
2046
+ ];
2047
+ var NEIGHBOURS = 15;
2048
+ var ORDER = ["rule", "decision", "capability", "entity", "screen", "experience", "event", "role"];
2049
+ var ownerOf = (id) => /^(.+)-AC-\d+$/.exec(id)?.[1] ?? /^(.+)\.A\d+$/.exec(id)?.[1] ?? id.replace(/#.*$/, "");
2050
+ var screenOfUx = (id) => /^UX-(SCR-.+)-[A-Z]{2,5}$/.exec(id)?.[1];
2051
+ function lookup(x, opts) {
2052
+ const index = x.index() ?? {};
2053
+ const caps = index.capabilities ?? [];
2054
+ const screens = index.screens ?? [];
2055
+ const entities = index.entities ?? [];
2056
+ const rules = index.rules ?? [];
2057
+ const events = index.events ?? [];
2058
+ const decisions = index.decisions ?? [];
2059
+ const text = [...opts.refs ?? [], opts.question ?? ""].join(" ");
2060
+ const about = /* @__PURE__ */ new Map();
2061
+ const missing = [];
2062
+ const add = (id, more = {}) => {
2063
+ const owner = ownerOf(id);
2064
+ if (!x.sources.has(owner)) {
2065
+ if (!missing.includes(id)) missing.push(id);
2066
+ return;
2067
+ }
2068
+ const a = about.get(owner) ?? { id: owner, ...titleOf(x, owner) ? { title: titleOf(x, owner) } : {} };
2069
+ if (owner !== id) a.focus = [.../* @__PURE__ */ new Set([...a.focus ?? [], id])];
2070
+ about.set(owner, { ...a, ...more });
2071
+ };
2072
+ for (const id of idsIn(text, ID_KINDS)) add(id);
2073
+ for (const m of text.matchAll(/(?<![\w-])(UX-SCR-[A-Z0-9-]+#[\w-]+|SCR-[A-Z0-9-]+\.A\d+)/g)) add(m[1]);
2074
+ const aliases = aliasGroups(index.glossary ?? []);
2075
+ const names = /* @__PURE__ */ new Map();
2076
+ const name = (said2, id) => {
2077
+ for (const n of aliases(said2))
2078
+ if (n.length > 2 && !names.has(n))
2079
+ names.set(n, { id, ...n === normalizeName(said2) ? {} : { said: n } });
2080
+ };
2081
+ for (const list2 of [entities, screens, caps, rules, events, index.roles ?? [], index.personas ?? []])
2082
+ for (const o of list2) name(o.title, o.id);
2083
+ for (const g of index.glossary ?? []) name(g.term, `term:${g.term}`);
2084
+ const spoken = ` ${normalizeName(text.replace(/\b[A-Z]+(?:-[A-Z0-9]+)+\b/g, " "))} `;
2085
+ for (const [n, hit] of [...names].sort((a, b) => b[0].length - a[0].length))
2086
+ if (new RegExp(` ${n}(?:s|es)? `).test(spoken) && !about.has(hit.id))
2087
+ add(hit.id, hit.said ? { said: hit.said } : {});
2088
+ for (const ref of opts.refs ?? [])
2089
+ if (!idsIn(ref, ID_KINDS).length && !/#/.test(ref) && !names.has(normalizeName(ref))) {
2090
+ const plural = normalizeName(ref).replace(/e?s$/, "");
2091
+ if (!names.has(plural) && !missing.includes(ref)) missing.push(ref);
2092
+ }
2093
+ const said = (word) => {
2094
+ const w = normalizeName(word);
2095
+ return w.length > 3 && new RegExp(` ${w.replace(/e$/, "")}(?:e|es|ed|d|s|ing)? `).test(spoken);
2096
+ };
2097
+ for (const c of caps) {
2098
+ if (about.has(c.id)) continue;
2099
+ const [verb, ...rest] = normalizeName(c.title).split(" ");
2100
+ const labels = screens.flatMap(
2101
+ (sc) => (sc.actions ?? []).filter((act) => act.capability === c.id).map((act) => act.label ?? "")
1755
2102
  );
2103
+ const word = [verb, ...labels].find(said);
2104
+ if (!word) continue;
2105
+ const near = c.roles?.some((r) => about.has(r.role)) || c.entities?.some((e) => about.has(e.entity)) || rest.some(said);
2106
+ if (near) add(c.id, { said: normalizeName(word) });
1756
2107
  }
1757
- return out;
1758
- }
1759
- function messagesOf(contentType, text) {
1760
- if (!text.trim()) return [];
1761
- if (!contentType.includes("text/event-stream")) return [JSON.parse(text)];
1762
- const out = [];
1763
- for (const event of text.split(/\r?\n\r?\n/)) {
1764
- const data = event.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
1765
- if (data.trim()) out.push(JSON.parse(data));
2108
+ if (opts.item) add(opts.item);
2109
+ if (!about.size && opts.task) {
2110
+ const task = x.work.changes.find((c) => c.id === opts.task.change)?.tasks.find((t) => t.track === opts.task.track);
2111
+ for (const key of task?.objects ?? []) if (x.sources.has(key) && !key.startsWith("file:")) add(key);
1766
2112
  }
1767
- return out;
1768
- }
1769
- function runProxy(opts) {
1770
- const { session, input, output, version } = opts;
1771
- const log = opts.log ?? ((line) => process.stderr.write(`alterspec-client: ${line}
1772
- `));
1773
- let protocolVersion;
1774
- const pending = /* @__PURE__ */ new Set();
1775
- const send = (message) => void output.write(JSON.stringify(message) + "\n");
1776
- const result = (id, value) => send({ jsonrpc: "2.0", id, result: value });
1777
- const error = (id, message, code = -32e3) => send({ jsonrpc: "2.0", id, error: { code, message } });
1778
- function refused(m, e) {
1779
- if (!isRequest(m)) return;
1780
- const id = m.id;
1781
- switch (m.method) {
1782
- case "initialize":
1783
- return result(id, {
1784
- protocolVersion: m.params?.protocolVersion ?? "2025-06-18",
1785
- capabilities: { tools: {} },
1786
- serverInfo: { name: "alterspec-client", version },
1787
- instructions: e.advice
1788
- });
1789
- case "ping":
1790
- return result(id, {});
1791
- case "tools/list":
1792
- return result(id, {
1793
- tools: [
1794
- {
1795
- name: "whoami",
1796
- description: "Who you are to the dispatcher. Your SSH key is refused: this says what to do.",
1797
- inputSchema: { type: "object", properties: {} }
1798
- }
1799
- ]
2113
+ const links = (id) => {
2114
+ const out = [];
2115
+ const cap = caps.find((c) => c.id === id);
2116
+ if (cap) {
2117
+ for (const r of cap.rules ?? []) out.push({ id: r, why: `a rule of ${id}` });
2118
+ for (const e of cap.entities ?? [])
2119
+ out.push({ id: e.entity, why: `${id} works with it${e.ops?.length ? ` (${e.ops.join("")})` : ""}` });
2120
+ for (const e of cap.events?.emits ?? []) out.push({ id: e, why: `emitted by ${id}` });
2121
+ for (const e of cap.events?.consumes ?? []) out.push({ id: e, why: `starts or informs ${id}` });
2122
+ for (const r of cap.roles ?? [])
2123
+ out.push({ id: r.role, why: `performs ${id}${r.scope ? `, scope ${r.scope}` : ""}` });
2124
+ for (const d of cap.depends_on ?? []) out.push({ id: d, why: `${id} depends on it` });
2125
+ }
2126
+ for (const s of screens) {
2127
+ const acts = (s.actions ?? []).filter((a) => a.capability === id);
2128
+ if (acts.length)
2129
+ out.push({
2130
+ id: s.id,
2131
+ why: `performs ${id} (${acts.map((a) => `${a.id}${a.label ? ` ${a.label}` : ""}`).join(", ")})`
1800
2132
  });
1801
- case "tools/call":
1802
- return result(id, {
1803
- content: [{ type: "text", text: e.advice }],
1804
- structuredContent: {
1805
- error: { code: e.code, message: e.advice },
1806
- key: { line: e.key.line, fingerprint: e.key.fingerprint }
1807
- },
1808
- isError: true
2133
+ if (s.id === id) {
2134
+ for (const a of s.actions ?? [])
2135
+ if (a.capability) out.push({ id: a.capability, why: `${id}.${a.id} performs it` });
2136
+ for (const f of s.fields ?? []) out.push({ id: f.entity, why: `shown on ${id}` });
2137
+ } else if ((s.fields ?? []).some((f) => f.entity === id)) out.push({ id: s.id, why: `shows ${id}` });
2138
+ }
2139
+ for (const r of rules) {
2140
+ const guards = (r.guards ?? []).filter((g) => g.entity === id);
2141
+ if (r.id === id) {
2142
+ for (const c of caps) if (c.rules?.includes(id)) out.push({ id: c.id, why: `applies ${id}` });
2143
+ for (const e of /* @__PURE__ */ new Set([...r.entities ?? [], ...(r.guards ?? []).map((g) => g.entity)]))
2144
+ out.push({ id: e, why: `${id} is about it` });
2145
+ } else if (guards.length)
2146
+ out.push({
2147
+ id: r.id,
2148
+ why: `guards ${id} on ${guards.flatMap((g) => g.on ?? []).join(", ") || "it"}`
1809
2149
  });
1810
- default:
1811
- return error(id, e.advice);
2150
+ else if (r.entities?.includes(id)) out.push({ id: r.id, why: `is about ${id}` });
1812
2151
  }
1813
- }
1814
- async function forward(m) {
1815
- try {
1816
- const headers = {
1817
- "content-type": "application/json",
1818
- accept: "application/json, text/event-stream"
1819
- };
1820
- if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
1821
- const res = await session.fetch("/mcp", { method: "POST", headers, body: JSON.stringify(m) });
1822
- const text = await res.text();
1823
- if (!res.ok && res.status !== 202) {
1824
- let message = `The dispatcher answered ${res.status}.`;
1825
- try {
1826
- message = JSON.parse(text).error?.message ?? message;
1827
- } catch {
1828
- }
1829
- if (isRequest(m)) error(m.id, message);
1830
- return;
1831
- }
1832
- for (const answer of messagesOf(res.headers.get("content-type") ?? "", text)) {
1833
- const pv = answer.result?.protocolVersion;
1834
- if (m.method === "initialize" && typeof pv === "string") protocolVersion = pv;
1835
- send(answer);
1836
- }
1837
- } catch (e) {
1838
- if (e instanceof KeyRefused) {
1839
- log(e.advice.split("\n")[0]);
1840
- return refused(m, e);
1841
- }
1842
- const message = e instanceof DispatcherError ? e.message : `The client failed: ${e.message}`;
1843
- log(message);
1844
- if (!isRequest(m)) return;
1845
- if (m.method === "tools/call")
1846
- return result(m.id, { content: [{ type: "text", text: message }], isError: true });
1847
- error(m.id, message);
2152
+ const ent = entities.find((e) => e.id === id);
2153
+ for (const a of ent?.attributes ?? [])
2154
+ if (a.references) out.push({ id: a.references, why: `${id}.${a.name} refers to it` });
2155
+ for (const e of entities)
2156
+ if (e.id !== id && e.attributes?.some((a) => a.references === id))
2157
+ out.push({ id: e.id, why: `refers to ${id}` });
2158
+ for (const c of caps) {
2159
+ if (c.id === id) continue;
2160
+ if (c.entities?.some((e) => e.entity === id)) out.push({ id: c.id, why: `works with ${id}` });
2161
+ if (c.events?.emits?.includes(id)) out.push({ id: c.id, why: `emits ${id}` });
2162
+ if (c.events?.consumes?.includes(id)) out.push({ id: c.id, why: `consumes ${id}` });
2163
+ if (c.roles?.some((r) => r.role === id)) out.push({ id: c.id, why: `${id} performs it` });
2164
+ if (c.depends_on?.includes(id)) out.push({ id: c.id, why: `depends on ${id}` });
1848
2165
  }
1849
- }
1850
- return new Promise((resolve3) => {
1851
- const lines = createInterface({ input, crlfDelay: Infinity });
1852
- lines.on("line", (line) => {
1853
- if (!line.trim()) return;
1854
- let m;
1855
- try {
1856
- m = JSON.parse(line);
1857
- } catch {
1858
- return error(null, "Parse error: not a JSON-RPC message.", -32700);
2166
+ for (const e of events.find((v) => v.id === id)?.entities ?? [])
2167
+ out.push({ id: e, why: `${id} is about it` });
2168
+ for (const d of decisions) {
2169
+ if (d.id === id) for (const a of d.affects ?? []) out.push({ id: a, why: `${id} affects it` });
2170
+ else if (d.affects?.includes(id)) out.push({ id: d.id, why: `decides about ${id}` });
2171
+ }
2172
+ const scr = screenOfUx(id);
2173
+ if (scr) out.push({ id: scr, why: `${id} is its design` });
2174
+ for (const s of x.sources.keys())
2175
+ if (screenOfUx(s) === id) out.push({ id: s, why: `the design of ${id}` });
2176
+ if (!x.index()) {
2177
+ const file = x.fileOf(id);
2178
+ for (const n of idsIn(frontMatterOf(file && x.read(file) || ""), ID_KINDS))
2179
+ if (n !== id) out.push({ id: n, why: `named by ${id}` });
2180
+ }
2181
+ return out.filter((l) => x.sources.has(l.id));
2182
+ };
2183
+ const isDoc = (id) => {
2184
+ const file = x.fileOf(id);
2185
+ return !!file && x.has(`${shardDir(file)}/${FRONT_MATTER_SHARD}`);
2186
+ };
2187
+ const pathOf = (id) => {
2188
+ const file = x.fileOf(id);
2189
+ if (!file) return void 0;
2190
+ return isDoc(id) ? `${shardDir(file)}/${FRONT_MATTER_SHARD}` : x.itemShard(file, id) ?? file;
2191
+ };
2192
+ const resolved = [...about.keys()];
2193
+ const read = resolved.flatMap((id) => {
2194
+ const file = x.fileOf(id);
2195
+ const a = about.get(id);
2196
+ if (!file) return [];
2197
+ if (!isDoc(id)) return [{ id, ...a.title ? { title: a.title } : {}, at: pathOf(id), shards: [] }];
2198
+ const folder = `${shardDir(file)}/`;
2199
+ const kind = idKind(id);
2200
+ const sections = (kind && READ[kind]) ?? [];
2201
+ return [
2202
+ {
2203
+ id,
2204
+ ...a.title ? { title: a.title } : {},
2205
+ at: folder,
2206
+ shards: [
2207
+ FRONT_MATTER_SHARD,
2208
+ ...sections.flatMap((h) => x.sectionShard(file, h)?.slice(folder.length) ?? [])
2209
+ ]
1859
2210
  }
1860
- const p = forward(m).finally(() => pending.delete(p));
1861
- pending.add(p);
1862
- });
1863
- lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve3()));
2211
+ ];
2212
+ });
2213
+ const check = /* @__PURE__ */ new Map();
2214
+ const must = (path, why) => {
2215
+ if (path && x.has(path) && !check.has(path)) check.set(path, why);
2216
+ };
2217
+ const hop = new Map(resolved.map((id) => [id, links(id)]));
2218
+ for (const id of resolved) {
2219
+ const file = x.fileOf(id);
2220
+ if (isDoc(id)) {
2221
+ must(pathOf(id), `the facts of ${id}`);
2222
+ for (const h of SILENCE) must(x.sectionShard(file, h), `${id}: ${h.toLowerCase()}`);
2223
+ } else must(pathOf(id), id.startsWith("term:") ? `what "${id.slice(5)}" means` : `${id} itself`);
2224
+ }
2225
+ for (const id of resolved)
2226
+ for (const l of hop.get(id)) if (idKind(l.id) === "rule") must(pathOf(l.id), `${l.id}: ${l.why}`);
2227
+ const behind = new Set(
2228
+ resolved.filter((id) => ["capability", "screen"].includes(idKind(id) ?? "")).flatMap((id) => hop.get(id).map((l) => l.id))
2229
+ );
2230
+ for (const d of decisions)
2231
+ if (d.affects?.some((a) => resolved.includes(a))) must(pathOf(d.id), `${d.id} decides about it`);
2232
+ for (const d of decisions)
2233
+ if (d.affects?.some((a) => behind.has(a) && ["entity", "rule"].includes(idKind(a) ?? "")))
2234
+ must(pathOf(d.id), `${d.id} decides about ${d.affects.find((a) => behind.has(a))}`);
2235
+ for (const id of resolved) {
2236
+ const last = x.sources.get(id)?.changed_by?.at(-1);
2237
+ must(last && x.proposalPath(last), `why ${id} is as it is (${last}, the last change of it)`);
2238
+ }
2239
+ must("_generated/open-items.md", "what the spec itself holds open");
2240
+ const seen = new Set(resolved);
2241
+ const neighbours = resolved.flatMap((id) => hop.get(id)).filter((l) => !seen.has(l.id) && seen.add(l.id)).map((l) => ({ id: l.id, path: pathOf(l.id) ?? "", why: l.why })).filter((l) => l.path && !check.has(l.path)).sort((a, b) => {
2242
+ const rank = (id) => (ORDER.indexOf(idKind(id)) + 1 || ORDER.length + 1) - 1;
2243
+ return rank(a.id) - rank(b.id);
2244
+ }).slice(0, NEIGHBOURS);
2245
+ return {
2246
+ about: [...about.values()],
2247
+ missing,
2248
+ read,
2249
+ check: [...check].map(([path, why]) => ({ path, why })),
2250
+ neighbours,
2251
+ views: VIEWS.filter(([p]) => x.has(p)).map(([path, why]) => ({ path, why }))
2252
+ };
2253
+ }
2254
+ function unread(x, found, opened) {
2255
+ const dir = x.dir.replace(/\/+$/, "");
2256
+ const given = opened.map(
2257
+ (o) => (o.startsWith(`${dir}/`) ? o.slice(dir.length + 1) : o).replace(/^\.\//, "")
2258
+ );
2259
+ const covers = (path) => given.some((g) => {
2260
+ if (g === path || path.endsWith(`/${g}`)) return true;
2261
+ if (g.endsWith(".md") && path.startsWith(`${shardDir(g)}/`)) return true;
2262
+ const file = x.sources.has(g) ? x.fileOf(g) : void 0;
2263
+ return !!file && (path.startsWith(`${shardDir(file)}/`) || path === file);
1864
2264
  });
2265
+ return found.check.filter((c) => !covers(c.path));
2266
+ }
2267
+ function renderLookup(l) {
2268
+ const out = [];
2269
+ if (!l.about.length)
2270
+ out.push(
2271
+ "The question names nothing the export holds: no ID, glossary term or title of it. Rephrase it in the",
2272
+ "export\u2019s terms (glossary.md), or it is about something the product doesn\u2019t have."
2273
+ );
2274
+ else
2275
+ out.push(
2276
+ `About: ${l.about.map(
2277
+ (a) => `${a.id}${a.title && !a.id.startsWith("term:") ? ` ${a.title}` : ""}${a.said ? ` (said as "${a.said}")` : ""}${a.focus ? ` [${a.focus.join(", ")}]` : ""}`
2278
+ ).join("; ")}`
2279
+ );
2280
+ if (l.missing.length) out.push(`Not in the export: ${l.missing.join(", ")}`);
2281
+ if (l.read.length)
2282
+ out.push(
2283
+ "",
2284
+ "Read first:",
2285
+ ...l.read.map((r) => `- ${r.id}: ${r.at}${r.shards.length ? ` ${r.shards.join(", ")}` : ""}`)
2286
+ );
2287
+ if (l.check.length)
2288
+ out.push("", "Open before calling the export silent:", ...l.check.map((c) => `- ${c.path} (${c.why})`));
2289
+ if (l.neighbours.length)
2290
+ out.push("", "Neighbours, when one bears on it:", ...l.neighbours.map((n) => `- ${n.path} (${n.why})`));
2291
+ if (l.views.length)
2292
+ out.push("", "Views, by the kind of question:", ...l.views.map((v) => `- ${v.path}: ${v.why}`));
2293
+ return out.join("\n") + "\n";
1865
2294
  }
1866
2295
 
1867
2296
  // src/open.ts
@@ -2061,10 +2490,10 @@ program.command("init").description(
2061
2490
  `${MCP_JSON} (server "dispatcher"): ${r.mcp}`,
2062
2491
  `${CLAUDE_SETTINGS} (progress hook after git commit): ${r.hook}`,
2063
2492
  `${CLAUDE_LOCAL_SETTINGS} (the "dispatcher" server approved for you): ${r.approval}`,
2064
- `Skills and ${PROMPTS_DIR}/: ${f.created.length} created, ${f.updated.length} updated, ${f.unchanged.length} unchanged${f.removed.length ? `, ${f.removed.length} removed` : ""}.`,
2493
+ `Skills, the answerer agent and ${PROMPTS_DIR}/: ${f.created.length} created, ${f.updated.length} updated, ${f.unchanged.length} unchanged${f.removed.length ? `, ${f.removed.length} removed` : ""}.`,
2065
2494
  ...f.conflicts.map((p) => `Kept your modified ${p}; --force replaces it.`),
2066
2495
  "",
2067
- "Commit .mcp.json, .claude/settings.json, .claude/skills/alterspec-* and .alterspec-client/, so task worktrees have them too.",
2496
+ "Commit .mcp.json, .claude/settings.json, .claude/skills/alterspec-*, .claude/agents/alterspec-* and .alterspec-client/, so task worktrees have them too.",
2068
2497
  ...ignoreLines(r.ignore),
2069
2498
  "The dispatcher's tools appear in the next Claude Code session."
2070
2499
  ];
@@ -2119,7 +2548,13 @@ program.command("context").description("print a task\u2019s brief, assembled fro
2119
2548
  const dir = exportDir(loaded);
2120
2549
  const x = readExport(dir);
2121
2550
  const task = parseTask(id);
2122
- const ctx = taskContext(x, task, dir, await coveredState(loaded, task));
2551
+ const ctx = taskContext(
2552
+ x,
2553
+ task,
2554
+ dir,
2555
+ await coveredState(loaded, task),
2556
+ await taskQuestions(sessionOf(loaded), task.id)
2557
+ );
2123
2558
  process.stdout.write(
2124
2559
  opts.stats ? contextStats(renderContext(ctx)) : opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx)
2125
2560
  );
@@ -2163,6 +2598,52 @@ program.command("worktree").description("create the task\u2019s branch task/<chg
2163
2598
  process.stdout.write(JSON.stringify(wt, null, 2) + "\n");
2164
2599
  })
2165
2600
  );
2601
+ program.command("lookup").description(
2602
+ "where in the export a question is answered: what to read first, and what before calling it silent"
2603
+ ).argument("[ref...]", "IDs and terms the question is about").option("--question <text>", "the question, in full").option("--task <task>", "the task it came up in, e.g. CHG-012/BE").option("--item <item>", "the checklist item it concerns").option("--unread <path...>", "the paths that were opened: print what must still be, and exit 1 when any").option("--json", "print it as JSON").action(
2604
+ run(
2605
+ (refs, opts) => {
2606
+ const x = readExport(exportDir(loadConfig()));
2607
+ const found = lookup(x, {
2608
+ refs,
2609
+ ...opts.question ? { question: opts.question } : {},
2610
+ ...opts.task ? { task: parseTask(opts.task) } : {},
2611
+ ...opts.item ? { item: opts.item } : {}
2612
+ });
2613
+ if (opts.unread) {
2614
+ const left = unread(x, found, opts.unread);
2615
+ if (left.length)
2616
+ throw new Error(
2617
+ `Not opened yet:
2618
+ ${left.map((c) => `- ${c.path} (${c.why})`).join("\n")}
2619
+ The export isn\u2019t silent until these are read.`
2620
+ );
2621
+ process.stdout.write("Everything that had to be opened was.\n");
2622
+ } else process.stdout.write(opts.json ? JSON.stringify(found, null, 2) + "\n" : renderLookup(found));
2623
+ }
2624
+ )
2625
+ );
2626
+ program.command("cites").description("check that every reference is an ID or a path the export holds").argument("<ref...>", "IDs (RULE-PRC-001, CAP-PRC-001-AC-02) and export paths").action(
2627
+ run((refs) => {
2628
+ const missing = missingCites(readExport(exportDir(loadConfig())), refs);
2629
+ if (missing.length)
2630
+ throw new Error(
2631
+ `Not in the export: ${missing.join(", ")}. An answer that cites them is not from the spec.`
2632
+ );
2633
+ process.stdout.write(`All ${refs.length} in the export.
2634
+ `);
2635
+ })
2636
+ );
2637
+ program.command("questions").description("print the questions the dispatcher keeps: a task\u2019s, or without a task your own").argument("[task]", "the task, e.g. CHG-012/BE").option("--open", "only the ones still open").option("--about <id...>", "everyone\u2019s questions that name these IDs").option("--json", "print them as JSON").action(
2638
+ run(async (id, opts) => {
2639
+ const questions = await listQuestions(sessionOf(loadConfig()), {
2640
+ ...id ? { task: parseTask(id).id } : {},
2641
+ ...opts.about ? { about: opts.about } : {},
2642
+ ...opts.open ? { open: true } : {}
2643
+ });
2644
+ process.stdout.write(opts.json ? JSON.stringify(questions, null, 2) + "\n" : questionsText(questions));
2645
+ })
2646
+ );
2166
2647
  program.command("merged").description("print the commit on origin/<main> that brought the task in").argument("<task>", "the task, e.g. CHG-012/BE").action(
2167
2648
  run((id) => {
2168
2649
  const loaded = loadConfig();