arkaik-mcp 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +747 -191
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -32,7 +32,7 @@ function startServer(options) {
32
32
  const respondError = (id, code, message) => {
33
33
  send({ jsonrpc: "2.0", id, error: { code, message } });
34
34
  };
35
- const handleToolCall = (id, params) => {
35
+ const handleToolCall = async (id, params) => {
36
36
  const name = params.name;
37
37
  if (typeof name !== "string") {
38
38
  respondError(id, JSONRPC_INVALID_PARAMS, "tools/call requires a string `name`.");
@@ -45,7 +45,7 @@ function startServer(options) {
45
45
  }
46
46
  const args = typeof params.arguments === "object" && params.arguments !== null && !Array.isArray(params.arguments) ? params.arguments : {};
47
47
  try {
48
- const result = handler(args);
48
+ const result = await handler(args);
49
49
  respond(id, { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] });
50
50
  } catch (error51) {
51
51
  if (error51 instanceof ToolError) {
@@ -56,6 +56,7 @@ function startServer(options) {
56
56
  }
57
57
  }
58
58
  };
59
+ const inFlight = /* @__PURE__ */ new Set();
59
60
  const handle = (message) => {
60
61
  const id = message.id ?? null;
61
62
  switch (message.method) {
@@ -78,9 +79,13 @@ function startServer(options) {
78
79
  case "tools/list":
79
80
  respond(id, { tools: options.tools });
80
81
  return;
81
- case "tools/call":
82
- handleToolCall(id, message.params ?? {});
82
+ case "tools/call": {
83
+ const settled = handleToolCall(id, message.params ?? {}).finally(() => {
84
+ inFlight.delete(settled);
85
+ });
86
+ inFlight.add(settled);
83
87
  return;
88
+ }
84
89
  default:
85
90
  if (message.id !== void 0) {
86
91
  respondError(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: ${message.method ?? "(none)"}`);
@@ -100,7 +105,9 @@ function startServer(options) {
100
105
  }
101
106
  handle(message);
102
107
  });
103
- lines.on("close", () => resolvePromise());
108
+ lines.on("close", () => {
109
+ void Promise.allSettled([...inFlight]).then(() => resolvePromise());
110
+ });
104
111
  });
105
112
  }
106
113
  function asObject(value) {
@@ -14625,7 +14632,7 @@ function date4(params) {
14625
14632
  config(en_default());
14626
14633
 
14627
14634
  // ../schema/src/ids.ts
14628
- var SPECIES_IDS = ["flow", "view", "data-model", "api-endpoint"];
14635
+ var SPECIES_IDS = ["flow", "view", "data-model", "api-endpoint", "acceptance"];
14629
14636
  var STATUS_IDS = [
14630
14637
  "idea",
14631
14638
  "backlog",
@@ -14637,12 +14644,49 @@ var STATUS_IDS = [
14637
14644
  "blocked"
14638
14645
  ];
14639
14646
  var PLATFORM_IDS = ["web", "ios", "android"];
14640
- var EDGE_TYPE_IDS = ["composes", "calls", "displays", "queries"];
14647
+ var EDGE_TYPE_IDS = ["composes", "calls", "displays", "queries", "covers"];
14648
+ var VALUE_TIER_IDS = ["functional", "emotional", "life-changing", "social-impact"];
14649
+ var VALUE_IDS = [
14650
+ // functional (14)
14651
+ "saves-time",
14652
+ "simplifies",
14653
+ "makes-money",
14654
+ "reduces-risk",
14655
+ "organizes",
14656
+ "integrates",
14657
+ "connects",
14658
+ "reduces-effort",
14659
+ "avoids-hassles",
14660
+ "reduces-cost",
14661
+ "quality",
14662
+ "variety",
14663
+ "sensory-appeal",
14664
+ "informs",
14665
+ // emotional (10)
14666
+ "reduces-anxiety",
14667
+ "rewards-me",
14668
+ "nostalgia",
14669
+ "design-aesthetics",
14670
+ "badge-value",
14671
+ "wellness",
14672
+ "therapeutic-value",
14673
+ "fun-entertainment",
14674
+ "attractiveness",
14675
+ "provides-access",
14676
+ // life-changing (5)
14677
+ "provides-hope",
14678
+ "self-actualization",
14679
+ "motivation",
14680
+ "heirloom",
14681
+ "affiliation-belonging",
14682
+ // social-impact (1)
14683
+ "self-transcendence"
14684
+ ];
14641
14685
 
14642
14686
  // ../schema/src/enums.ts
14643
14687
  var SpeciesSchema = external_exports.enum(SPECIES_IDS).meta({
14644
14688
  id: "Species",
14645
- description: "The species of a node. flow = ordered sequence of views/sub-flows. view = reusable page or screen. data-model = data entity/table. api-endpoint = API endpoint."
14689
+ description: "The species of a node. flow = ordered sequence of views/sub-flows. view = reusable page or screen. data-model = data entity/table. api-endpoint = API endpoint. acceptance = a testable promise (one Given/When/Then) with per-platform status."
14646
14690
  });
14647
14691
  var StatusSchema = external_exports.enum(STATUS_IDS).meta({
14648
14692
  id: "Status",
@@ -14654,7 +14698,15 @@ var PlatformSchema = external_exports.enum(PLATFORM_IDS).meta({
14654
14698
  });
14655
14699
  var EdgeTypeSchema = external_exports.enum(EDGE_TYPE_IDS).meta({
14656
14700
  id: "EdgeType",
14657
- description: "composes = structural hierarchy (flow\u2194view). calls = view/flow \u2192 api-endpoint. displays = view \u2192 data-model. queries = api-endpoint \u2192 data-model."
14701
+ description: "composes = structural hierarchy (flow\u2194view). calls = view/flow \u2192 api-endpoint, or api-endpoint \u2192 api-endpoint (endpoint fan-out to internal/external APIs). displays = view \u2192 data-model. queries = api-endpoint \u2192 data-model. covers = acceptance \u2192 view/flow (which surface the acceptance is proven on)."
14702
+ });
14703
+ var ValueTierSchema = external_exports.enum(VALUE_TIER_IDS).meta({
14704
+ id: "ValueTier",
14705
+ description: "Bain value pyramid tier."
14706
+ });
14707
+ var ValueSchema = external_exports.enum(VALUE_IDS).meta({
14708
+ id: "Value",
14709
+ description: "A Bain B2C Elements-of-Value element served by an acceptance (spec \xA73.2)."
14658
14710
  });
14659
14711
 
14660
14712
  // ../schema/src/id-gen.ts
@@ -14662,7 +14714,8 @@ var SPECIES_PREFIXES = {
14662
14714
  flow: "F-",
14663
14715
  view: "V-",
14664
14716
  "data-model": "DM-",
14665
- "api-endpoint": "API-"
14717
+ "api-endpoint": "API-",
14718
+ acceptance: "AC-"
14666
14719
  };
14667
14720
  function kebabCase(input) {
14668
14721
  return input.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -14716,6 +14769,25 @@ var PlaylistEntrySchema = external_exports.lazy(
14716
14769
  id: "PlaylistEntry",
14717
14770
  description: "An entry in a flow's playlist. Discriminated union on 'type'."
14718
14771
  });
14772
+ function collectPlaylistNodeRefs(entries) {
14773
+ const refs = [];
14774
+ for (const entry of entries) {
14775
+ if (!entry) continue;
14776
+ if (entry.type === "view") {
14777
+ refs.push(entry.view_id);
14778
+ } else if (entry.type === "flow") {
14779
+ refs.push(entry.flow_id);
14780
+ } else if (entry.type === "condition") {
14781
+ refs.push(...collectPlaylistNodeRefs(entry.if_true ?? []));
14782
+ refs.push(...collectPlaylistNodeRefs(entry.if_false ?? []));
14783
+ } else if (entry.type === "junction") {
14784
+ for (const branch of entry.cases ?? []) {
14785
+ refs.push(...collectPlaylistNodeRefs(branch.entries ?? []));
14786
+ }
14787
+ }
14788
+ }
14789
+ return refs;
14790
+ }
14719
14791
  var FlowPlaylistSchema = external_exports.object({
14720
14792
  entries: external_exports.array(PlaylistEntrySchema)
14721
14793
  }).meta({ id: "FlowPlaylist" });
@@ -15070,7 +15142,13 @@ var NodeMetadataSchema = external_exports.object({
15070
15142
  platformNotes: PlatformNotesMapSchema.optional(),
15071
15143
  platformStatuses: PlatformStatusMapSchema.optional(),
15072
15144
  platformScreenshots: PlatformScreenshotsMapSchema.optional(),
15073
- refs: external_exports.array(RefSchema).optional().meta({ description: "Typed external references on the node." })
15145
+ refs: external_exports.array(RefSchema).optional().meta({ description: "Typed external references on the node." }),
15146
+ gherkin: external_exports.string().optional().meta({
15147
+ description: "Acceptance nodes only: exactly one Given/When/Then scenario (the How). A second scenario is a second acceptance node."
15148
+ }),
15149
+ values: external_exports.array(ValueSchema).optional().meta({
15150
+ description: "Acceptance nodes only: 1..n Bain value elements served (the Why)."
15151
+ })
15074
15152
  }).catchall(external_exports.unknown()).meta({ id: "NodeMetadata", description: "Optional metadata for a node." });
15075
15153
  var NodeSchema = external_exports.object({
15076
15154
  id: external_exports.string().meta({ description: "Unique node ID. Convention: prefix with species \u2014 F- (flow), V- (view), DM- (data-model), API- (api-endpoint)." }),
@@ -15261,10 +15339,15 @@ var VALID_EDGE_SEMANTICS = {
15261
15339
  ],
15262
15340
  calls: [
15263
15341
  ["view", "api-endpoint"],
15264
- ["flow", "api-endpoint"]
15342
+ ["flow", "api-endpoint"],
15343
+ ["api-endpoint", "api-endpoint"]
15265
15344
  ],
15266
15345
  displays: [["view", "data-model"]],
15267
- queries: [["api-endpoint", "data-model"]]
15346
+ queries: [["api-endpoint", "data-model"]],
15347
+ covers: [
15348
+ ["acceptance", "view"],
15349
+ ["acceptance", "flow"]
15350
+ ]
15268
15351
  };
15269
15352
  function isIsoDate(value) {
15270
15353
  return typeof value === "string" && !Number.isNaN(Date.parse(value));
@@ -15425,6 +15508,38 @@ function validateBundle(input) {
15425
15508
  }
15426
15509
  }
15427
15510
  }
15511
+ const gherkin = md.gherkin;
15512
+ const values = md.values;
15513
+ if (species === "acceptance") {
15514
+ if (typeof gherkin !== "string" || !gherkin.trim()) {
15515
+ warn(
15516
+ `${base}.metadata.gherkin`,
15517
+ "acceptance-gherkin-missing",
15518
+ `Acceptance ${nodeId}: metadata.gherkin is missing or empty (one Given/When/Then scenario expected)`
15519
+ );
15520
+ }
15521
+ if (!Array.isArray(values) || values.length === 0) {
15522
+ warn(
15523
+ `${base}.metadata.values`,
15524
+ "acceptance-values-missing",
15525
+ `Acceptance ${nodeId}: metadata.values is missing or empty (assign 1-3 value elements)`
15526
+ );
15527
+ }
15528
+ } else {
15529
+ if (gherkin !== void 0) {
15530
+ warn(`${base}.metadata.gherkin`, "gherkin-species", `Node ${nodeId}: metadata.gherkin is only meaningful on acceptance nodes`);
15531
+ }
15532
+ if (values !== void 0) {
15533
+ warn(`${base}.metadata.values`, "values-species", `Node ${nodeId}: metadata.values is only meaningful on acceptance nodes`);
15534
+ }
15535
+ }
15536
+ if (Array.isArray(values)) {
15537
+ for (const v of values) {
15538
+ if (!VALUE_IDS.includes(v)) {
15539
+ error51(`${base}.metadata.values`, "valid-value", `Node ${nodeId}: invalid value element "${v}"`);
15540
+ }
15541
+ }
15542
+ }
15428
15543
  const refs = md.refs;
15429
15544
  if (Array.isArray(refs)) {
15430
15545
  const refIds = /* @__PURE__ */ new Set();
@@ -15669,6 +15784,25 @@ function validateBundle(input) {
15669
15784
  return result();
15670
15785
  }
15671
15786
 
15787
+ // ../schema/src/acceptance.ts
15788
+ var DEFAULT_DELIVERED_STATUSES = ["live"];
15789
+ function resolvePlatformStatus(node, platform) {
15790
+ if (!node.platforms.includes(platform)) return void 0;
15791
+ return node.metadata?.platformStatuses?.[platform] ?? node.status;
15792
+ }
15793
+ function hasParityGap(node, deliveredStatuses = DEFAULT_DELIVERED_STATUSES) {
15794
+ if (node.status === "archived") return false;
15795
+ const resolved = node.platforms.map((platform) => resolvePlatformStatus(node, platform)).filter((status) => status !== void 0);
15796
+ const delivered = resolved.filter((status) => deliveredStatuses.includes(status));
15797
+ return delivered.length > 0 && delivered.length < resolved.length;
15798
+ }
15799
+ function acceptancesCovering(anchorId, nodes, edges) {
15800
+ const coveringIds = new Set(
15801
+ edges.filter((edge) => edge.edge_type === "covers" && edge.target_id === anchorId).map((edge) => edge.source_id)
15802
+ );
15803
+ return nodes.filter((node) => node.species === "acceptance" && coveringIds.has(node.id));
15804
+ }
15805
+
15672
15806
  // ../schema/src/serialize.ts
15673
15807
  var BUNDLE_KEY_ORDER = ["schema_version", "project", "nodes", "edges", "journal"];
15674
15808
  var PROJECT_KEY_ORDER = [
@@ -16081,135 +16215,190 @@ function diffNodeUpdate(current, patch) {
16081
16215
  return events;
16082
16216
  }
16083
16217
 
16084
- // src/store.ts
16085
- import { writeFileSync as writeFileSync2 } from "node:fs";
16086
- import { resolve } from "node:path";
16087
-
16088
- // ../cli/src/lib/bundle-io.ts
16089
- import { existsSync, readFileSync } from "node:fs";
16090
- function readBundle(filePath) {
16091
- if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
16092
- let parsed;
16093
- try {
16094
- parsed = JSON.parse(readFileSync(filePath, "utf8"));
16095
- } catch (e) {
16096
- throw new Error(`Cannot parse JSON \u2014 ${e.message}`);
16097
- }
16098
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
16099
- throw new Error("Bundle must be a JSON object.");
16218
+ // ../schema/src/mutate.ts
16219
+ var MutationError = class extends Error {
16220
+ constructor(code, message, subjectId) {
16221
+ super(message);
16222
+ this.name = "MutationError";
16223
+ this.code = code;
16224
+ this.subjectId = subjectId;
16100
16225
  }
16101
- return parsed;
16102
- }
16103
-
16104
- // ../cli/src/lib/journal-io.ts
16105
- import { appendFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
16106
- import { dirname, join } from "node:path";
16107
- var JOURNAL_SIDECAR = "journal.jsonl";
16108
- function journalPathFor(bundlePath2) {
16109
- return join(dirname(bundlePath2), JOURNAL_SIDECAR);
16110
- }
16111
- function toLine(event) {
16112
- return JSON.stringify(event) + "\n";
16113
- }
16114
- function appendJournalEvent(journalPath, event) {
16115
- const line = toLine(event);
16116
- if (!existsSync2(journalPath)) {
16117
- mkdirSync(dirname(journalPath), { recursive: true });
16118
- writeFileSync(journalPath, line);
16119
- return;
16226
+ };
16227
+ function wouldCreateCycle(flowId, candidateId, allNodes) {
16228
+ if (candidateId === flowId) return true;
16229
+ const nodesById = new Map(allNodes.map((node) => [node.id, node]));
16230
+ const candidate = nodesById.get(candidateId);
16231
+ if (!candidate || candidate.species !== "flow") return false;
16232
+ const visited = /* @__PURE__ */ new Set();
16233
+ const stack = [candidateId];
16234
+ while (stack.length > 0) {
16235
+ const currentFlowId = stack.pop();
16236
+ if (!currentFlowId || visited.has(currentFlowId)) continue;
16237
+ visited.add(currentFlowId);
16238
+ const currentFlow = nodesById.get(currentFlowId);
16239
+ if (!currentFlow || currentFlow.species !== "flow") continue;
16240
+ const entries = currentFlow.metadata?.playlist?.entries;
16241
+ if (!Array.isArray(entries)) continue;
16242
+ const referenced = collectPlaylistNodeRefs(entries);
16243
+ if (referenced.includes(flowId)) return true;
16244
+ for (const refId of referenced) {
16245
+ if (!visited.has(refId)) stack.push(refId);
16246
+ }
16120
16247
  }
16121
- const existing = readFileSync2(journalPath, "utf8");
16122
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
16123
- appendFileSync(journalPath, prefix + line);
16248
+ return false;
16124
16249
  }
16125
-
16126
- // ../cli/src/lib/bundle-validate.ts
16127
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
16128
- import { dirname as dirname2, join as join2 } from "node:path";
16129
- var JOURNAL_SIDECAR2 = "journal.jsonl";
16130
- function validateBundleAt(filePath) {
16131
- const bundle = readBundle(filePath);
16132
- const loose = bundle;
16133
- if (!loose.project || !loose.nodes || !loose.edges) {
16134
- throw new Error("Missing top-level keys (project, nodes, edges).");
16250
+ function synthesizeComposesEdges(flow, existingEdges, projectId) {
16251
+ if (flow.species !== "flow") return [];
16252
+ const entries = flow.metadata?.playlist?.entries;
16253
+ if (!Array.isArray(entries) || entries.length === 0) return [];
16254
+ const existingIds = new Set(existingEdges.map((edge) => edge.id));
16255
+ const seen = /* @__PURE__ */ new Set();
16256
+ const synthesized = [];
16257
+ for (const refId of collectPlaylistNodeRefs(entries)) {
16258
+ const id = edgeId(flow.id, refId);
16259
+ if (existingIds.has(id) || seen.has(id)) continue;
16260
+ seen.add(id);
16261
+ synthesized.push({
16262
+ id,
16263
+ project_id: projectId,
16264
+ source_id: flow.id,
16265
+ target_id: refId,
16266
+ edge_type: "composes"
16267
+ });
16135
16268
  }
16136
- let sidecarFindings = [];
16137
- let sidecarLoaded = false;
16138
- if (loose.journal === void 0) {
16139
- const sidecarPath = join2(dirname2(filePath), JOURNAL_SIDECAR2);
16140
- if (existsSync3(sidecarPath)) {
16141
- const { events, findings } = parseJournalLines(readFileSync3(sidecarPath, "utf8"));
16142
- sidecarFindings = findings;
16143
- sidecarLoaded = true;
16144
- loose.journal = events;
16269
+ return synthesized;
16270
+ }
16271
+ function assertNoPlaylistCycle(flow, nextNodes) {
16272
+ const entries = flow.metadata?.playlist?.entries;
16273
+ if (!Array.isArray(entries)) return;
16274
+ for (const candidateId of collectPlaylistNodeRefs(entries)) {
16275
+ if (wouldCreateCycle(flow.id, candidateId, nextNodes)) {
16276
+ throw new MutationError(
16277
+ "playlist_cycle",
16278
+ `Cannot add Flow ${candidateId}: it would create a circular reference.`,
16279
+ candidateId
16280
+ );
16145
16281
  }
16146
16282
  }
16147
- const nodes = Array.isArray(loose.nodes) ? loose.nodes : [];
16148
- const edges = Array.isArray(loose.edges) ? loose.edges : [];
16149
- const journal = Array.isArray(loose.journal) ? loose.journal : [];
16150
- const result = validateBundle(bundle);
16151
- const valid = sidecarFindings.length === 0 && result.errors.length === 0;
16152
- return { bundle, nodes, edges, journal, sidecarLoaded, sidecarFindings, result, valid };
16153
16283
  }
16154
-
16155
- // src/store.ts
16156
- var MCP_ACTOR = "arkaik-mcp";
16157
- var DEFAULT_BUNDLE_PATH = "docs/arkaik/bundle.json";
16158
- function resolveBundlePath(argv2, env) {
16159
- const flagIndex = argv2.indexOf("--bundle");
16160
- const flagValue = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
16161
- if (flagValue) return resolve(flagValue);
16162
- if (env.ARKAIK_BUNDLE) return resolve(env.ARKAIK_BUNDLE);
16163
- return resolve(DEFAULT_BUNDLE_PATH);
16164
- }
16165
- function loadBundle(bundlePath2) {
16166
- return validateBundleAt(bundlePath2);
16167
- }
16168
- function persistMutation(bundlePath2, loaded, next, inputs) {
16169
- const events = toJournalEvents(inputs, MCP_ACTOR);
16170
- const nextNodes = next.nodes ?? loaded.nodes;
16171
- const nextEdges = next.edges ?? loaded.edges;
16172
- const candidate = {
16173
- ...loaded.bundle,
16174
- nodes: nextNodes,
16175
- edges: nextEdges,
16176
- journal: [...loaded.journal, ...events]
16177
- };
16178
- const result = validateBundle(candidate);
16179
- if (result.errors.length > 0) {
16180
- return { ok: false, errors: result.errors, warnings: result.warnings };
16181
- }
16182
- const embeddedJournal = !loaded.sidecarLoaded && loaded.bundle.journal !== void 0;
16183
- if (embeddedJournal) {
16184
- writeFileSync2(bundlePath2, serializeBundle(candidate));
16185
- } else {
16186
- const journalPath = journalPathFor(bundlePath2);
16187
- for (const event of events) {
16188
- appendJournalEvent(journalPath, event);
16189
- }
16190
- if (next.nodes !== void 0 || next.edges !== void 0) {
16191
- const snapshot = { ...loaded.bundle, nodes: nextNodes, edges: nextEdges };
16192
- delete snapshot.journal;
16193
- writeFileSync2(bundlePath2, serializeBundle(snapshot));
16284
+ function applyOps(input, ops) {
16285
+ let nodes = [...input.nodes];
16286
+ let edges = [...input.edges];
16287
+ const eventInputs = [];
16288
+ const synthesizedEdges = [];
16289
+ const cascadedEdgeIds = [];
16290
+ const foldSynthesized = (flow) => {
16291
+ const created = synthesizeComposesEdges(flow, edges, input.projectId);
16292
+ if (created.length === 0) return;
16293
+ edges = [...edges, ...created];
16294
+ synthesizedEdges.push(...created);
16295
+ eventInputs.push(...created.map(edgeAddedInput));
16296
+ };
16297
+ for (const op of ops) {
16298
+ switch (op.op) {
16299
+ case "create_node": {
16300
+ if (nodes.some((candidate) => candidate.id === op.node.id)) {
16301
+ throw new MutationError("duplicate_node", `Node "${op.node.id}" already exists.`, op.node.id);
16302
+ }
16303
+ nodes = [...nodes, op.node];
16304
+ assertNoPlaylistCycle(op.node, nodes);
16305
+ eventInputs.push(nodeCreatedInput(op.node));
16306
+ foldSynthesized(op.node);
16307
+ break;
16308
+ }
16309
+ case "update_node": {
16310
+ const index = nodes.findIndex((candidate) => candidate.id === op.node_id);
16311
+ if (index === -1) {
16312
+ throw new MutationError("node_not_found", `Node ${op.node_id} not found`, op.node_id);
16313
+ }
16314
+ const current = nodes[index];
16315
+ const updated = { ...current, ...op.patch };
16316
+ const nextNodes = [...nodes];
16317
+ nextNodes[index] = updated;
16318
+ if (updated.species === "flow") assertNoPlaylistCycle(updated, nextNodes);
16319
+ const inputs = diffNodeUpdate(current, op.patch);
16320
+ nodes = nextNodes;
16321
+ eventInputs.push(...inputs);
16322
+ if (inputs.length > 0) foldSynthesized(updated);
16323
+ break;
16324
+ }
16325
+ case "delete_node": {
16326
+ if (!nodes.some((candidate) => candidate.id === op.node_id)) {
16327
+ throw new MutationError("node_not_found", `Node ${op.node_id} not found`, op.node_id);
16328
+ }
16329
+ nodes = nodes.filter((candidate) => candidate.id !== op.node_id);
16330
+ for (const edge of edges) {
16331
+ if (edge.source_id === op.node_id || edge.target_id === op.node_id) {
16332
+ cascadedEdgeIds.push(edge.id);
16333
+ }
16334
+ }
16335
+ edges = edges.filter(
16336
+ (edge) => edge.source_id !== op.node_id && edge.target_id !== op.node_id
16337
+ );
16338
+ eventInputs.push(nodeDeletedInput(op.node_id));
16339
+ break;
16340
+ }
16341
+ case "delete_nodes": {
16342
+ const present = new Set(
16343
+ nodes.filter((candidate) => op.node_ids.includes(candidate.id)).map((n) => n.id)
16344
+ );
16345
+ if (present.size === 0) break;
16346
+ nodes = nodes.filter((candidate) => !present.has(candidate.id));
16347
+ for (const edge of edges) {
16348
+ if (present.has(edge.source_id) || present.has(edge.target_id)) {
16349
+ cascadedEdgeIds.push(edge.id);
16350
+ }
16351
+ }
16352
+ edges = edges.filter(
16353
+ (edge) => !present.has(edge.source_id) && !present.has(edge.target_id)
16354
+ );
16355
+ for (const id of present) eventInputs.push(nodeDeletedInput(id));
16356
+ break;
16357
+ }
16358
+ case "create_edge": {
16359
+ const edge = { ...op.edge, id: edgeId(op.edge.source_id, op.edge.target_id) };
16360
+ const existing = edges.find((candidate) => candidate.id === edge.id);
16361
+ if (existing) {
16362
+ if (existing.edge_type !== edge.edge_type) {
16363
+ throw new MutationError(
16364
+ "edge_type_conflict",
16365
+ `Edge "${edge.id}" already exists as "${existing.edge_type}", cannot re-add as "${edge.edge_type}".`,
16366
+ edge.id
16367
+ );
16368
+ }
16369
+ break;
16370
+ }
16371
+ edges = [...edges, edge];
16372
+ eventInputs.push(edgeAddedInput(edge));
16373
+ break;
16374
+ }
16375
+ case "delete_edge": {
16376
+ if (!edges.some((candidate) => candidate.id === op.edge_id)) {
16377
+ throw new MutationError("edge_not_found", `Edge ${op.edge_id} not found`, op.edge_id);
16378
+ }
16379
+ edges = edges.filter((candidate) => candidate.id !== op.edge_id);
16380
+ eventInputs.push(edgeRemovedInput(op.edge_id));
16381
+ break;
16382
+ }
16194
16383
  }
16195
16384
  }
16196
- return { ok: true, warnings: result.warnings, events };
16385
+ return { nodes, edges, eventInputs, synthesizedEdges, cascadedEdgeIds };
16197
16386
  }
16198
16387
 
16199
16388
  // src/tools.ts
16200
- function load(ctx) {
16201
- let loaded;
16389
+ async function load(ctx) {
16390
+ let graph;
16202
16391
  try {
16203
- loaded = loadBundle(ctx.bundlePath);
16392
+ graph = await ctx.store.load();
16204
16393
  } catch (error51) {
16205
- throw new ToolError(`Cannot load bundle at ${ctx.bundlePath}: ${error51.message}`);
16394
+ throw new ToolError(`Cannot load ${ctx.store.describe()}: ${error51.message}`);
16206
16395
  }
16207
16396
  return {
16208
- loaded,
16209
- nodes: loaded.nodes,
16210
- edges: loaded.edges,
16211
- project: loaded.bundle.project,
16212
- journal: loaded.journal
16397
+ loaded: graph.loaded,
16398
+ nodes: graph.nodes,
16399
+ edges: graph.edges,
16400
+ project: graph.project,
16401
+ journal: graph.journal
16213
16402
  };
16214
16403
  }
16215
16404
  function requireString(args, key) {
@@ -16225,7 +16414,12 @@ function findNode(nodes, nodeId) {
16225
16414
  return node;
16226
16415
  }
16227
16416
  function nodeSummary(node) {
16228
- return { id: node.id, title: node.title, species: node.species, status: node.status, platforms: node.platforms };
16417
+ const base = { id: node.id, title: node.title, species: node.species, status: node.status, platforms: node.platforms };
16418
+ if (node.species !== "acceptance") return base;
16419
+ const platform_statuses = Object.fromEntries(
16420
+ node.platforms.map((platform) => [platform, resolvePlatformStatus(node, platform)])
16421
+ );
16422
+ return { ...base, platform_statuses, values: node.metadata?.values ?? [] };
16229
16423
  }
16230
16424
  function unwrap(result) {
16231
16425
  if (!result.ok) {
@@ -16237,6 +16431,14 @@ function unwrap(result) {
16237
16431
  return { warnings: result.warnings, events: result.events };
16238
16432
  }
16239
16433
  var UPDATABLE_NODE_FIELDS = /* @__PURE__ */ new Set(["title", "description", "status", "platforms", "metadata"]);
16434
+ function mutate(graph, ops) {
16435
+ try {
16436
+ return applyOps({ projectId: graph.project.id, nodes: graph.nodes, edges: graph.edges }, ops);
16437
+ } catch (err) {
16438
+ if (err instanceof MutationError) throw new ToolError(err.message);
16439
+ throw err;
16440
+ }
16441
+ }
16240
16442
  function listReleases(journal, nodesById) {
16241
16443
  const latestByVersion = /* @__PURE__ */ new Map();
16242
16444
  for (const event of orderEvents(journal)) {
@@ -16262,28 +16464,45 @@ function buildCatalog(ctx) {
16262
16464
  tool(
16263
16465
  {
16264
16466
  name: "list_nodes",
16265
- description: "List nodes in the product graph, filtered by species, status, platform, and/or a case-insensitive title/description substring. Returns summaries.",
16467
+ description: "List nodes in the product graph, filtered by species, status, platform, value element, covers-anchor, parity gap, and/or a case-insensitive title/description substring. Returns summaries (acceptances include platform_statuses + values).",
16266
16468
  inputSchema: {
16267
16469
  type: "object",
16268
16470
  properties: {
16269
16471
  species: { type: "string", enum: [...SPECIES_IDS] },
16270
16472
  status: { type: "string", enum: [...STATUS_IDS] },
16271
16473
  platform: { type: "string", enum: [...PLATFORM_IDS] },
16474
+ value: {
16475
+ type: "string",
16476
+ enum: [...VALUE_IDS],
16477
+ description: "Only acceptances tagged with this value element."
16478
+ },
16479
+ anchor: {
16480
+ type: "string",
16481
+ description: "Node id \u2014 only acceptances covering it via a covers edge."
16482
+ },
16483
+ parity_gap: {
16484
+ type: "boolean",
16485
+ description: "Only acceptances delivered (live) on \u22651 applicable platform but not all."
16486
+ },
16272
16487
  query: { type: "string", description: "Case-insensitive substring over title + description." },
16273
16488
  limit: { type: "integer", minimum: 1, description: "Default 50." }
16274
16489
  },
16275
16490
  additionalProperties: false
16276
16491
  }
16277
16492
  },
16278
- (args) => {
16279
- const { nodes } = load(ctx);
16493
+ async (args) => {
16494
+ const { nodes, edges } = await load(ctx);
16280
16495
  const query = typeof args.query === "string" ? args.query.toLowerCase() : void 0;
16281
16496
  const limit = typeof args.limit === "number" && args.limit >= 1 ? Math.floor(args.limit) : 50;
16497
+ const anchorCoveringIds = typeof args.anchor === "string" ? new Set(acceptancesCovering(args.anchor, nodes, edges).map((node) => node.id)) : void 0;
16282
16498
  const matches = nodes.filter((node) => {
16283
16499
  if (typeof args.species === "string" && node.species !== args.species) return false;
16284
16500
  if (typeof args.status === "string" && node.status !== args.status) return false;
16285
16501
  if (typeof args.platform === "string" && !node.platforms.includes(args.platform))
16286
16502
  return false;
16503
+ if (typeof args.value === "string" && (node.species !== "acceptance" || !(node.metadata?.values ?? []).includes(args.value))) return false;
16504
+ if (anchorCoveringIds !== void 0 && !anchorCoveringIds.has(node.id)) return false;
16505
+ if (args.parity_gap === true && (node.species !== "acceptance" || !hasParityGap(node))) return false;
16287
16506
  if (query !== void 0) {
16288
16507
  const haystack = `${node.title}
16289
16508
  ${node.description ?? ""}`.toLowerCase();
@@ -16297,7 +16516,7 @@ ${node.description ?? ""}`.toLowerCase();
16297
16516
  tool(
16298
16517
  {
16299
16518
  name: "get_node",
16300
- description: "Fetch one node in full: fields, its edges with neighbor titles, the flows that use it, and its journal timeline.",
16519
+ description: "Fetch one node in full: fields, its edges with neighbor titles, the flows that use it, its journal timeline, and (views/flows) the acceptances covering it.",
16301
16520
  inputSchema: {
16302
16521
  type: "object",
16303
16522
  properties: { node_id: { type: "string" } },
@@ -16305,9 +16524,9 @@ ${node.description ?? ""}`.toLowerCase();
16305
16524
  additionalProperties: false
16306
16525
  }
16307
16526
  },
16308
- (args) => {
16527
+ async (args) => {
16309
16528
  const nodeId = requireString(args, "node_id");
16310
- const { nodes, edges, journal } = load(ctx);
16529
+ const { nodes, edges, journal } = await load(ctx);
16311
16530
  const node = findNode(nodes, nodeId);
16312
16531
  const nodesById = new Map(nodes.map((candidate) => [candidate.id, candidate]));
16313
16532
  const relatedEdges = edges.filter((edge) => edge.source_id === nodeId || edge.target_id === nodeId).map((edge) => {
@@ -16331,7 +16550,14 @@ ${node.description ?? ""}`.toLowerCase();
16331
16550
  }
16332
16551
  }
16333
16552
  const whereUsedFlows = [...composingFlowIds].map((flowId) => nodesById.get(flowId)).filter((flow) => flow !== void 0 && flow.species === "flow").map((flow) => ({ id: flow.id, title: flow.title }));
16334
- return { node, edges: relatedEdges, whereUsedFlows, timeline: computeNodeTimeline(journal, nodeId) };
16553
+ const covered_by = node.species === "view" || node.species === "flow" ? acceptancesCovering(nodeId, nodes, edges).map(nodeSummary) : void 0;
16554
+ return {
16555
+ node,
16556
+ edges: relatedEdges,
16557
+ whereUsedFlows,
16558
+ timeline: computeNodeTimeline(journal, nodeId),
16559
+ ...covered_by !== void 0 ? { covered_by } : {}
16560
+ };
16335
16561
  }
16336
16562
  );
16337
16563
  tool(
@@ -16344,8 +16570,8 @@ ${node.description ?? ""}`.toLowerCase();
16344
16570
  additionalProperties: false
16345
16571
  }
16346
16572
  },
16347
- (args) => {
16348
- const { nodes, journal } = load(ctx);
16573
+ async (args) => {
16574
+ const { nodes, journal } = await load(ctx);
16349
16575
  const nodesById = new Map(nodes.map((node) => [node.id, node]));
16350
16576
  if (typeof args.version === "string") {
16351
16577
  return computeChangelog(journal, args.version, { nodesById });
@@ -16359,8 +16585,8 @@ ${node.description ?? ""}`.toLowerCase();
16359
16585
  description: "Open ideas and requests \u2014 journal items not yet realized as nodes in the snapshot.",
16360
16586
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
16361
16587
  },
16362
- () => {
16363
- const { nodes, journal } = load(ctx);
16588
+ async () => {
16589
+ const { nodes, journal } = await load(ctx);
16364
16590
  return computeBacklog(journal, { existingNodeIds: new Set(nodes.map((node) => node.id)) });
16365
16591
  }
16366
16592
  );
@@ -16370,8 +16596,8 @@ ${node.description ?? ""}`.toLowerCase();
16370
16596
  description: "Every map the project offers \u2014 built-ins plus stored definitions \u2014 with live subgraph sizes.",
16371
16597
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
16372
16598
  },
16373
- () => {
16374
- const { nodes, edges, project } = load(ctx);
16599
+ async () => {
16600
+ const { nodes, edges, project } = await load(ctx);
16375
16601
  return {
16376
16602
  maps: listMaps(project).map((definition) => {
16377
16603
  const subgraph = computeMapSubgraph(definition, nodes, edges);
@@ -16391,9 +16617,9 @@ ${node.description ?? ""}`.toLowerCase();
16391
16617
  additionalProperties: false
16392
16618
  }
16393
16619
  },
16394
- (args) => {
16620
+ async (args) => {
16395
16621
  const mapId = requireString(args, "map_id");
16396
- const { nodes, edges, project } = load(ctx);
16622
+ const { nodes, edges, project } = await load(ctx);
16397
16623
  const definition = listMaps(project).find((candidate) => candidate.id === mapId);
16398
16624
  if (!definition) throw new ToolError(`No map with id "${mapId}".`);
16399
16625
  const subgraph = computeMapSubgraph(definition, nodes, edges);
@@ -16406,8 +16632,8 @@ ${node.description ?? ""}`.toLowerCase();
16406
16632
  description: "Run the full validator over the bundle (+ journal sidecar): errors, warnings, and line findings.",
16407
16633
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
16408
16634
  },
16409
- () => {
16410
- const { loaded } = load(ctx);
16635
+ async () => {
16636
+ const { loaded } = await load(ctx);
16411
16637
  return {
16412
16638
  valid: loaded.valid,
16413
16639
  errors: loaded.result.errors,
@@ -16419,7 +16645,7 @@ ${node.description ?? ""}`.toLowerCase();
16419
16645
  tool(
16420
16646
  {
16421
16647
  name: "create_node",
16422
- description: "Create a node. The id derives from species + title; the mutation is refused (nothing written) if the result fails validation.",
16648
+ description: "Create a node. The id derives from species + title; the mutation is refused (nothing written) if the result fails validation. For a flow, pass its populated metadata.playlist here \u2014 the matching composes edges to every referenced view/sub-flow are synthesized in the same mutation, so a full flow lands in one call.",
16423
16649
  inputSchema: {
16424
16650
  type: "object",
16425
16651
  properties: {
@@ -16434,8 +16660,8 @@ ${node.description ?? ""}`.toLowerCase();
16434
16660
  additionalProperties: false
16435
16661
  }
16436
16662
  },
16437
- (args) => {
16438
- const graph = load(ctx);
16663
+ async (args) => {
16664
+ const graph = await load(ctx);
16439
16665
  const species = requireString(args, "species");
16440
16666
  const title = requireString(args, "title");
16441
16667
  const platforms = Array.isArray(args.platforms) ? args.platforms : [];
@@ -16449,17 +16675,21 @@ ${node.description ?? ""}`.toLowerCase();
16449
16675
  ...typeof args.description === "string" ? { description: args.description } : {},
16450
16676
  ...typeof args.metadata === "object" && args.metadata !== null ? { metadata: args.metadata } : {}
16451
16677
  };
16452
- const result = persistMutation(ctx.bundlePath, graph.loaded, { nodes: [...graph.nodes, node] }, [
16453
- nodeCreatedInput(node)
16454
- ]);
16678
+ const ops = [{ op: "create_node", node }];
16679
+ const outcome = mutate(graph, ops);
16680
+ const result = await ctx.store.persist(
16681
+ graph,
16682
+ { nodes: outcome.nodes, edges: outcome.edges, ops },
16683
+ outcome.eventInputs
16684
+ );
16455
16685
  const { warnings, events } = unwrap(result);
16456
- return { node, events, warnings };
16686
+ return { node, edges: outcome.synthesizedEdges, events, warnings };
16457
16687
  }
16458
16688
  );
16459
16689
  tool(
16460
16690
  {
16461
16691
  name: "update_node",
16462
- description: "Patch a node's title, description, status, platforms, or metadata. Journal events derive from the diff; refused if validation fails.",
16692
+ description: "Patch a node's title, description, status, platforms, or metadata. Journal events derive from the diff; refused if validation fails. When a flow's metadata.playlist gains a view/sub-flow, the matching composes edge is synthesized in the same mutation.",
16463
16693
  inputSchema: {
16464
16694
  type: "object",
16465
16695
  properties: {
@@ -16480,7 +16710,7 @@ ${node.description ?? ""}`.toLowerCase();
16480
16710
  additionalProperties: false
16481
16711
  }
16482
16712
  },
16483
- (args) => {
16713
+ async (args) => {
16484
16714
  const nodeId = requireString(args, "node_id");
16485
16715
  if (typeof args.patch !== "object" || args.patch === null || Array.isArray(args.patch)) {
16486
16716
  throw new ToolError("`patch` is required and must be an object.");
@@ -16491,17 +16721,21 @@ ${node.description ?? ""}`.toLowerCase();
16491
16721
  throw new ToolError(`Field "${key}" cannot be patched (allowed: ${[...UPDATABLE_NODE_FIELDS].join(", ")}).`);
16492
16722
  }
16493
16723
  }
16494
- const graph = load(ctx);
16724
+ const graph = await load(ctx);
16495
16725
  const current = findNode(graph.nodes, nodeId);
16496
- const inputs = diffNodeUpdate(current, patch);
16497
- if (inputs.length === 0) {
16726
+ const ops = [{ op: "update_node", node_id: nodeId, patch }];
16727
+ const outcome = mutate(graph, ops);
16728
+ if (outcome.eventInputs.length === 0) {
16498
16729
  return { node: current, events: [], note: "No-op patch \u2014 nothing changed, nothing written." };
16499
16730
  }
16500
- const updated = { ...current, ...patch };
16501
- const nextNodes = graph.nodes.map((candidate) => candidate.id === nodeId ? updated : candidate);
16502
- const result = persistMutation(ctx.bundlePath, graph.loaded, { nodes: nextNodes }, inputs);
16731
+ const updated = outcome.nodes.find((candidate) => candidate.id === nodeId);
16732
+ const result = await ctx.store.persist(
16733
+ graph,
16734
+ { nodes: outcome.nodes, edges: outcome.edges, ops },
16735
+ outcome.eventInputs
16736
+ );
16503
16737
  const { warnings, events } = unwrap(result);
16504
- return { node: updated, events, warnings };
16738
+ return { node: updated, edges: outcome.synthesizedEdges, events, warnings };
16505
16739
  }
16506
16740
  );
16507
16741
  tool(
@@ -16515,18 +16749,19 @@ ${node.description ?? ""}`.toLowerCase();
16515
16749
  additionalProperties: false
16516
16750
  }
16517
16751
  },
16518
- (args) => {
16752
+ async (args) => {
16519
16753
  const nodeId = requireString(args, "node_id");
16520
- const graph = load(ctx);
16754
+ const graph = await load(ctx);
16521
16755
  const node = findNode(graph.nodes, nodeId);
16522
- const cascadedEdgeIds = graph.edges.filter((edge) => edge.source_id === nodeId || edge.target_id === nodeId).map((edge) => edge.id);
16523
- const nextNodes = graph.nodes.filter((candidate) => candidate.id !== nodeId);
16524
- const nextEdges = graph.edges.filter((edge) => !cascadedEdgeIds.includes(edge.id));
16525
- const result = persistMutation(ctx.bundlePath, graph.loaded, { nodes: nextNodes, edges: nextEdges }, [
16526
- nodeDeletedInput(nodeId)
16527
- ]);
16756
+ const ops = [{ op: "delete_node", node_id: nodeId }];
16757
+ const outcome = mutate(graph, ops);
16758
+ const result = await ctx.store.persist(
16759
+ graph,
16760
+ { nodes: outcome.nodes, edges: outcome.edges, ops },
16761
+ outcome.eventInputs
16762
+ );
16528
16763
  const { warnings, events } = unwrap(result);
16529
- return { removed: node, cascadedEdgeIds, events, warnings };
16764
+ return { removed: node, cascadedEdgeIds: outcome.cascadedEdgeIds, events, warnings };
16530
16765
  }
16531
16766
  );
16532
16767
  tool(
@@ -16544,11 +16779,11 @@ ${node.description ?? ""}`.toLowerCase();
16544
16779
  additionalProperties: false
16545
16780
  }
16546
16781
  },
16547
- (args) => {
16782
+ async (args) => {
16548
16783
  const sourceId = requireString(args, "source_id");
16549
16784
  const targetId = requireString(args, "target_id");
16550
16785
  const edgeType = requireString(args, "edge_type");
16551
- const graph = load(ctx);
16786
+ const graph = await load(ctx);
16552
16787
  const edge = {
16553
16788
  id: edgeId(sourceId, targetId),
16554
16789
  project_id: graph.project.id,
@@ -16559,9 +16794,13 @@ ${node.description ?? ""}`.toLowerCase();
16559
16794
  if (graph.edges.some((candidate) => candidate.id === edge.id)) {
16560
16795
  throw new ToolError(`Edge "${edge.id}" already exists.`);
16561
16796
  }
16562
- const result = persistMutation(ctx.bundlePath, graph.loaded, { edges: [...graph.edges, edge] }, [
16563
- edgeAddedInput(edge)
16564
- ]);
16797
+ const ops = [{ op: "create_edge", edge }];
16798
+ const outcome = mutate(graph, ops);
16799
+ const result = await ctx.store.persist(
16800
+ graph,
16801
+ { nodes: outcome.nodes, edges: outcome.edges, ops },
16802
+ outcome.eventInputs
16803
+ );
16565
16804
  const { warnings, events } = unwrap(result);
16566
16805
  return { edge, events, warnings };
16567
16806
  }
@@ -16577,28 +16816,31 @@ ${node.description ?? ""}`.toLowerCase();
16577
16816
  additionalProperties: false
16578
16817
  }
16579
16818
  },
16580
- (args) => {
16819
+ async (args) => {
16581
16820
  const edgeIdArg = requireString(args, "edge_id");
16582
- const graph = load(ctx);
16821
+ const graph = await load(ctx);
16583
16822
  const edge = graph.edges.find((candidate) => candidate.id === edgeIdArg);
16584
16823
  if (!edge) throw new ToolError(`No edge with id "${edgeIdArg}".`);
16585
- const nextEdges = graph.edges.filter((candidate) => candidate.id !== edgeIdArg);
16586
- const result = persistMutation(ctx.bundlePath, graph.loaded, { edges: nextEdges }, [
16587
- edgeRemovedInput(edgeIdArg)
16588
- ]);
16824
+ const ops = [{ op: "delete_edge", edge_id: edgeIdArg }];
16825
+ const outcome = mutate(graph, ops);
16826
+ const result = await ctx.store.persist(
16827
+ graph,
16828
+ { nodes: outcome.nodes, edges: outcome.edges, ops },
16829
+ outcome.eventInputs
16830
+ );
16589
16831
  const { warnings, events } = unwrap(result);
16590
16832
  return { removed: edge, events, warnings };
16591
16833
  }
16592
16834
  );
16593
- const journalOnly = (type) => (args) => {
16835
+ const journalOnly = (type) => async (args) => {
16594
16836
  const title = requireString(args, "title");
16595
- const graph = load(ctx);
16837
+ const graph = await load(ctx);
16596
16838
  const payload = { title };
16597
16839
  if (typeof args.description === "string") payload.description = args.description;
16598
16840
  if (typeof args.node_id === "string") payload.node_id = args.node_id;
16599
16841
  if (type === "request.filed" && typeof args.source === "string") payload.source = args.source;
16600
16842
  const input = { type, payload };
16601
- const result = persistMutation(ctx.bundlePath, graph.loaded, {}, [input]);
16843
+ const result = await ctx.store.persist(graph, {}, [input]);
16602
16844
  const { warnings, events } = unwrap(result);
16603
16845
  return { events, warnings };
16604
16846
  };
@@ -16640,27 +16882,341 @@ ${node.description ?? ""}`.toLowerCase();
16640
16882
  return { tools: tools2, handlers: handlers2 };
16641
16883
  }
16642
16884
 
16885
+ // src/store.ts
16886
+ import { writeFileSync as writeFileSync2 } from "node:fs";
16887
+ import { resolve } from "node:path";
16888
+
16889
+ // ../cli/src/lib/bundle-io.ts
16890
+ import { existsSync, readFileSync } from "node:fs";
16891
+ function readBundle(filePath) {
16892
+ if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
16893
+ let parsed;
16894
+ try {
16895
+ parsed = JSON.parse(readFileSync(filePath, "utf8"));
16896
+ } catch (e) {
16897
+ throw new Error(`Cannot parse JSON \u2014 ${e.message}`);
16898
+ }
16899
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
16900
+ throw new Error("Bundle must be a JSON object.");
16901
+ }
16902
+ return parsed;
16903
+ }
16904
+
16905
+ // ../cli/src/lib/journal-io.ts
16906
+ import { appendFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
16907
+ import { dirname, join } from "node:path";
16908
+ var JOURNAL_SIDECAR = "journal.jsonl";
16909
+ function journalPathFor(bundlePath) {
16910
+ return join(dirname(bundlePath), JOURNAL_SIDECAR);
16911
+ }
16912
+ function toLine(event) {
16913
+ return JSON.stringify(event) + "\n";
16914
+ }
16915
+ function appendJournalEvent(journalPath, event) {
16916
+ const line = toLine(event);
16917
+ if (!existsSync2(journalPath)) {
16918
+ mkdirSync(dirname(journalPath), { recursive: true });
16919
+ writeFileSync(journalPath, line);
16920
+ return;
16921
+ }
16922
+ const existing = readFileSync2(journalPath, "utf8");
16923
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
16924
+ appendFileSync(journalPath, prefix + line);
16925
+ }
16926
+
16927
+ // ../cli/src/lib/bundle-validate.ts
16928
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
16929
+ import { dirname as dirname2, join as join2 } from "node:path";
16930
+ var JOURNAL_SIDECAR2 = "journal.jsonl";
16931
+ function validateBundleAt(filePath) {
16932
+ const bundle = readBundle(filePath);
16933
+ const loose = bundle;
16934
+ if (!loose.project || !loose.nodes || !loose.edges) {
16935
+ throw new Error("Missing top-level keys (project, nodes, edges).");
16936
+ }
16937
+ let sidecarFindings = [];
16938
+ let sidecarLoaded = false;
16939
+ if (loose.journal === void 0) {
16940
+ const sidecarPath = join2(dirname2(filePath), JOURNAL_SIDECAR2);
16941
+ if (existsSync3(sidecarPath)) {
16942
+ const { events, findings } = parseJournalLines(readFileSync3(sidecarPath, "utf8"));
16943
+ sidecarFindings = findings;
16944
+ sidecarLoaded = true;
16945
+ loose.journal = events;
16946
+ }
16947
+ }
16948
+ const nodes = Array.isArray(loose.nodes) ? loose.nodes : [];
16949
+ const edges = Array.isArray(loose.edges) ? loose.edges : [];
16950
+ const journal = Array.isArray(loose.journal) ? loose.journal : [];
16951
+ const result = validateBundle(bundle);
16952
+ const valid = sidecarFindings.length === 0 && result.errors.length === 0;
16953
+ return { bundle, nodes, edges, journal, sidecarLoaded, sidecarFindings, result, valid };
16954
+ }
16955
+
16956
+ // src/store.ts
16957
+ var MCP_ACTOR = "arkaik-mcp";
16958
+ var DEFAULT_BUNDLE_PATH = "docs/arkaik/bundle.json";
16959
+ function resolveBundlePath(argv2, env) {
16960
+ const flagIndex = argv2.indexOf("--bundle");
16961
+ const flagValue2 = flagIndex !== -1 ? argv2[flagIndex + 1] : void 0;
16962
+ if (flagValue2) return resolve(flagValue2);
16963
+ if (env.ARKAIK_BUNDLE) return resolve(env.ARKAIK_BUNDLE);
16964
+ return resolve(DEFAULT_BUNDLE_PATH);
16965
+ }
16966
+ function loadBundle(bundlePath) {
16967
+ return validateBundleAt(bundlePath);
16968
+ }
16969
+ function persistMutation(bundlePath, loaded, next, inputs) {
16970
+ const events = toJournalEvents(inputs, MCP_ACTOR);
16971
+ const nextNodes = next.nodes ?? loaded.nodes;
16972
+ const nextEdges = next.edges ?? loaded.edges;
16973
+ const candidate = {
16974
+ ...loaded.bundle,
16975
+ nodes: nextNodes,
16976
+ edges: nextEdges,
16977
+ journal: [...loaded.journal, ...events]
16978
+ };
16979
+ const result = validateBundle(candidate);
16980
+ if (result.errors.length > 0) {
16981
+ return { ok: false, errors: result.errors, warnings: result.warnings };
16982
+ }
16983
+ const embeddedJournal = !loaded.sidecarLoaded && loaded.bundle.journal !== void 0;
16984
+ if (embeddedJournal) {
16985
+ writeFileSync2(bundlePath, serializeBundle(candidate));
16986
+ } else {
16987
+ const journalPath = journalPathFor(bundlePath);
16988
+ for (const event of events) {
16989
+ appendJournalEvent(journalPath, event);
16990
+ }
16991
+ if (next.nodes !== void 0 || next.edges !== void 0) {
16992
+ const snapshot = { ...loaded.bundle, nodes: nextNodes, edges: nextEdges };
16993
+ delete snapshot.journal;
16994
+ writeFileSync2(bundlePath, serializeBundle(snapshot));
16995
+ }
16996
+ }
16997
+ return { ok: true, warnings: result.warnings, events };
16998
+ }
16999
+ function createFileStore(bundlePath) {
17000
+ return {
17001
+ async load() {
17002
+ let loaded;
17003
+ try {
17004
+ loaded = loadBundle(bundlePath);
17005
+ } catch (error51) {
17006
+ throw new Error(`Cannot load bundle at ${bundlePath}: ${error51.message}`);
17007
+ }
17008
+ return {
17009
+ loaded,
17010
+ nodes: loaded.nodes,
17011
+ edges: loaded.edges,
17012
+ project: loaded.bundle.project,
17013
+ journal: loaded.journal
17014
+ };
17015
+ },
17016
+ async persist(graph, next, inputs) {
17017
+ return persistMutation(bundlePath, graph.loaded, next, inputs);
17018
+ },
17019
+ describe() {
17020
+ return `bundle: ${bundlePath}`;
17021
+ }
17022
+ };
17023
+ }
17024
+
17025
+ // src/remote-store.ts
17026
+ function createRemoteStore(options) {
17027
+ const doFetch = options.fetchImpl ?? ((...args) => fetch(...args));
17028
+ const base = options.baseUrl.replace(/\/+$/, "");
17029
+ const projectPath = `${base}/api/graph/projects/${encodeURIComponent(options.projectId)}`;
17030
+ async function request(path, init) {
17031
+ const res = await doFetch(`${projectPath}${path}`, {
17032
+ ...init,
17033
+ headers: {
17034
+ "content-type": "application/json",
17035
+ authorization: `Bearer ${options.token}`,
17036
+ ...init?.headers ?? {}
17037
+ }
17038
+ });
17039
+ const body = await res.json().catch(() => null);
17040
+ if (!res.ok) {
17041
+ const err = new Error(describeFailure(res.status, body));
17042
+ err.status = res.status;
17043
+ err.body = body;
17044
+ throw err;
17045
+ }
17046
+ return body;
17047
+ }
17048
+ return {
17049
+ async load() {
17050
+ const [{ bundle }, { journal }] = await Promise.all([
17051
+ request(""),
17052
+ request("/journal")
17053
+ ]);
17054
+ const nodes = bundle.nodes ?? [];
17055
+ const edges = bundle.edges ?? [];
17056
+ return {
17057
+ // `loaded` mirrors the file store's BundleValidation shape closely
17058
+ // enough for the read tools, which only ever touch bundle/nodes/edges/
17059
+ // journal. The server has already validated everything it stores, so
17060
+ // there are no findings to carry here.
17061
+ loaded: {
17062
+ bundle: { ...bundle, journal },
17063
+ nodes,
17064
+ edges,
17065
+ journal,
17066
+ sidecarLoaded: false,
17067
+ errors: [],
17068
+ warnings: []
17069
+ },
17070
+ nodes,
17071
+ edges,
17072
+ project: bundle.project,
17073
+ journal
17074
+ };
17075
+ },
17076
+ // `inputs` is deliberately not accepted: the locally-derived events are not
17077
+ // sent. The server derives its own from the ops it applies, so that the
17078
+ // events stored alongside a graph are always the ones that produced it —
17079
+ // a client cannot describe a change differently from how it was made.
17080
+ async persist(_graph, next) {
17081
+ const ops = next.ops;
17082
+ if (!ops || ops.length === 0) {
17083
+ return {
17084
+ ok: false,
17085
+ errors: [
17086
+ {
17087
+ path: "",
17088
+ rule: "remote-unsupported",
17089
+ message: "This tool writes a journal-only event, which the hosted API does not accept yet. Run against a repo bundle for now.",
17090
+ severity: "error"
17091
+ }
17092
+ ],
17093
+ warnings: []
17094
+ };
17095
+ }
17096
+ try {
17097
+ const result = await request("/mutations", { method: "POST", body: JSON.stringify({ ops }) });
17098
+ return { ok: true, warnings: result.warnings ?? [], events: result.events ?? [] };
17099
+ } catch (err) {
17100
+ const e = err;
17101
+ if (e.status === 422) {
17102
+ return {
17103
+ ok: false,
17104
+ errors: e.body?.errors ?? [
17105
+ { path: "", rule: e.body?.code ?? "mutation-refused", message: e.body?.message ?? e.message, severity: "error" }
17106
+ ],
17107
+ warnings: []
17108
+ };
17109
+ }
17110
+ throw err;
17111
+ }
17112
+ },
17113
+ describe() {
17114
+ return `hosted project: ${options.projectId} at ${base}`;
17115
+ }
17116
+ };
17117
+ }
17118
+ function describeFailure(status, body) {
17119
+ const b = body;
17120
+ if (status === 401) return "Unauthorized \u2014 check ARKAIK_TOKEN (create one at /settings/tokens).";
17121
+ if (status === 403) return `Forbidden \u2014 ${b?.message ?? b?.error ?? "the token lacks the required scope"}.`;
17122
+ if (status === 404) return "Project not found \u2014 check the project id, or that the token's account owns it.";
17123
+ return b?.message ?? b?.error ?? `Request failed (${status}).`;
17124
+ }
17125
+
17126
+ // src/config.ts
17127
+ import { readFileSync as readFileSync4 } from "node:fs";
17128
+ import { join as join3 } from "node:path";
17129
+ var LINK_FILE = "docs/arkaik/arkaik.json";
17130
+ var DEFAULT_BASE_URL = "https://arkaik.app";
17131
+ function readLinkFile(cwd) {
17132
+ try {
17133
+ const parsed = JSON.parse(readFileSync4(join3(cwd, LINK_FILE), "utf8"));
17134
+ if (typeof parsed !== "object" || parsed === null) return null;
17135
+ return parsed;
17136
+ } catch {
17137
+ return null;
17138
+ }
17139
+ }
17140
+ function flagValue(argv2, flag) {
17141
+ const index = argv2.indexOf(flag);
17142
+ return blankToUndefined(index !== -1 ? argv2[index + 1] : void 0);
17143
+ }
17144
+ function blankToUndefined(value) {
17145
+ const trimmed = value?.trim();
17146
+ return trimmed ? trimmed : void 0;
17147
+ }
17148
+ function resolveRemoteConfig(argv2, env, cwd) {
17149
+ const link = readLinkFile(cwd);
17150
+ const explicitRemote = argv2.includes("--remote");
17151
+ const projectId = flagValue(argv2, "--project") ?? blankToUndefined(env.ARKAIK_PROJECT) ?? blankToUndefined(link?.project_id);
17152
+ if (argv2.includes("--bundle") && !explicitRemote) return { mode: "file" };
17153
+ if (!explicitRemote && !projectId) return { mode: "file" };
17154
+ if (!projectId) {
17155
+ throw new Error(
17156
+ "--remote needs a project: pass --project <id>, set ARKAIK_PROJECT, or run `npx arkaik link`."
17157
+ );
17158
+ }
17159
+ const token = blankToUndefined(env.ARKAIK_TOKEN);
17160
+ if (!token) {
17161
+ throw new Error(
17162
+ `ARKAIK_TOKEN is not set. Create a token at ${link?.remote ?? DEFAULT_BASE_URL}/settings/tokens and export it.`
17163
+ );
17164
+ }
17165
+ return {
17166
+ mode: "remote",
17167
+ projectId,
17168
+ baseUrl: blankToUndefined(env.ARKAIK_URL) ?? blankToUndefined(link?.remote) ?? DEFAULT_BASE_URL,
17169
+ token
17170
+ };
17171
+ }
17172
+
16643
17173
  // src/index.ts
16644
- var VERSION = "0.1.0";
17174
+ var VERSION = "0.2.1";
16645
17175
  var argv = process.argv.slice(2);
16646
17176
  if (argv.includes("--help") || argv.includes("-h")) {
16647
17177
  process.stdout.write(
16648
17178
  [
16649
- "arkaik-mcp \u2014 MCP server over an Arkaik repo bundle (stdio transport)",
17179
+ "arkaik-mcp \u2014 MCP server over an Arkaik product graph (stdio transport)",
17180
+ "",
17181
+ "Usage: arkaik-mcp [--bundle <path>] [--remote] [--project <id>]",
17182
+ "",
17183
+ "Repo mode (default):",
17184
+ " Bundle resolution: --bundle, then $ARKAIK_BUNDLE, then docs/arkaik/bundle.json.",
17185
+ " The journal is the sibling journal.jsonl sidecar (embedded journal[] wins).",
16650
17186
  "",
16651
- "Usage: arkaik-mcp [--bundle <path>]",
17187
+ "Hosted mode (--remote, or a docs/arkaik/arkaik.json written by `arkaik link`):",
17188
+ " Project: --project, then $ARKAIK_PROJECT, then arkaik.json",
17189
+ " Token: $ARKAIK_TOKEN (create one at <origin>/settings/tokens)",
17190
+ " Origin: $ARKAIK_URL, then arkaik.json, then https://arkaik.app",
16652
17191
  "",
16653
- "Bundle resolution: --bundle, then $ARKAIK_BUNDLE, then docs/arkaik/bundle.json.",
16654
- "The journal is the sibling journal.jsonl sidecar (embedded journal[] wins).",
17192
+ "The tool catalog is identical in both modes.",
16655
17193
  "Docs: docs/spec/mcp.md",
16656
17194
  ""
16657
17195
  ].join("\n")
16658
17196
  );
16659
17197
  process.exit(0);
16660
17198
  }
16661
- var bundlePath = resolveBundlePath(argv, process.env);
16662
- var { tools, handlers } = buildCatalog({ bundlePath });
16663
- process.stderr.write(`arkaik-mcp v${VERSION} \u2014 bundle: ${bundlePath}
17199
+ function resolveStore() {
17200
+ const remote = resolveRemoteConfig(argv, process.env, process.cwd());
17201
+ if (remote.mode === "remote") {
17202
+ return createRemoteStore({
17203
+ baseUrl: remote.baseUrl,
17204
+ projectId: remote.projectId,
17205
+ token: remote.token
17206
+ });
17207
+ }
17208
+ return createFileStore(resolveBundlePath(argv, process.env));
17209
+ }
17210
+ var store;
17211
+ try {
17212
+ store = resolveStore();
17213
+ } catch (error51) {
17214
+ process.stderr.write(`arkaik-mcp: ${error51.message}
17215
+ `);
17216
+ process.exit(1);
17217
+ }
17218
+ var { tools, handlers } = buildCatalog({ store });
17219
+ process.stderr.write(`arkaik-mcp v${VERSION} \u2014 ${store.describe()}
16664
17220
  `);
16665
17221
  startServer({
16666
17222
  serverInfo: { name: "arkaik-mcp", version: VERSION },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkaik-mcp",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "Arkaik MCP server — stdio tools over an Arkaik product-graph bundle: read projections plus validator-gated dual-write mutations.",
5
5
  "license": "MIT",
6
6
  "type": "module",