@flyingrobots/graft 0.4.0 → 0.5.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.
Files changed (111) hide show
  1. package/ARCHITECTURE.md +386 -0
  2. package/CHANGELOG.md +47 -0
  3. package/CODE_OF_CONDUCT.md +65 -0
  4. package/README.md +153 -17
  5. package/bin/graft.js +4 -14
  6. package/docs/ADVANCED_GUIDE.md +49 -0
  7. package/docs/CLI.md +43 -0
  8. package/docs/GUIDE.md +321 -32
  9. package/docs/MCP.md +44 -0
  10. package/package.json +15 -4
  11. package/src/adapters/node-fs.ts +4 -0
  12. package/src/adapters/node-git.ts +47 -0
  13. package/src/adapters/node-process-runner.ts +27 -0
  14. package/src/cli/index-cmd.ts +75 -11
  15. package/src/cli/init.ts +808 -57
  16. package/src/cli/main.ts +437 -0
  17. package/src/contracts/capabilities.ts +341 -0
  18. package/src/contracts/causal-ontology.ts +622 -0
  19. package/src/contracts/causal-surface-next-action.ts +18 -0
  20. package/src/contracts/output-schemas.ts +1169 -0
  21. package/src/git/diff.ts +25 -21
  22. package/src/git/target-git-hook-bootstrap.ts +56 -0
  23. package/src/hooks/posttooluse-read.ts +21 -74
  24. package/src/hooks/pretooluse-read.ts +20 -56
  25. package/src/hooks/read-governor.ts +95 -0
  26. package/src/hooks/read-messages.ts +53 -0
  27. package/src/mcp/burden.ts +123 -0
  28. package/src/mcp/cache.ts +51 -0
  29. package/src/mcp/cached-file.ts +10 -8
  30. package/src/mcp/context.ts +65 -2
  31. package/src/mcp/daemon-control-plane.ts +554 -0
  32. package/src/mcp/daemon-job-scheduler.ts +279 -0
  33. package/src/mcp/daemon-repos.ts +216 -0
  34. package/src/mcp/daemon-server.ts +396 -0
  35. package/src/mcp/daemon-worker-pool.ts +310 -0
  36. package/src/mcp/daemon-worker-process.ts +52 -0
  37. package/src/mcp/metrics.ts +108 -1
  38. package/src/mcp/monitor-tick-job.ts +99 -0
  39. package/src/mcp/persisted-local-history.ts +1246 -0
  40. package/src/mcp/persistent-monitor-runtime.ts +549 -0
  41. package/src/mcp/policy.ts +84 -0
  42. package/src/mcp/receipt.ts +82 -12
  43. package/src/mcp/repo-concurrency.ts +318 -0
  44. package/src/mcp/repo-state.ts +777 -0
  45. package/src/mcp/repo-tool-job.ts +302 -0
  46. package/src/mcp/run-capture-config.ts +33 -0
  47. package/src/mcp/runtime-causal-context.ts +72 -0
  48. package/src/mcp/runtime-observability.ts +219 -0
  49. package/src/mcp/runtime-staged-target.ts +161 -0
  50. package/src/mcp/runtime-workspace-overlay.ts +255 -0
  51. package/src/mcp/semantic-transition-guidance.ts +60 -0
  52. package/src/mcp/semantic-transition-summary.ts +130 -0
  53. package/src/mcp/server.ts +696 -55
  54. package/src/mcp/stdio-server.ts +12 -0
  55. package/src/mcp/stdio.ts +2 -5
  56. package/src/mcp/tools/activity-view.ts +325 -0
  57. package/src/mcp/tools/causal-attach.ts +67 -0
  58. package/src/mcp/tools/causal-status.ts +58 -0
  59. package/src/mcp/tools/changed-since.ts +13 -11
  60. package/src/mcp/tools/code-find.ts +164 -0
  61. package/src/mcp/tools/code-refs.ts +466 -0
  62. package/src/mcp/tools/code-show.ts +252 -0
  63. package/src/mcp/tools/daemon-monitors.ts +14 -0
  64. package/src/mcp/tools/daemon-repos.ts +22 -0
  65. package/src/mcp/tools/daemon-sessions.ts +14 -0
  66. package/src/mcp/tools/daemon-status.ts +12 -0
  67. package/src/mcp/tools/doctor.ts +45 -2
  68. package/src/mcp/tools/explain.ts +4 -0
  69. package/src/mcp/tools/file-outline.ts +7 -3
  70. package/src/mcp/tools/git-files.ts +73 -0
  71. package/src/mcp/tools/graft-diff.ts +12 -4
  72. package/src/mcp/tools/map.ts +92 -38
  73. package/src/mcp/tools/monitor-pause.ts +18 -0
  74. package/src/mcp/tools/monitor-resume.ts +18 -0
  75. package/src/mcp/tools/monitor-start.ts +20 -0
  76. package/src/mcp/tools/monitor-stop.ts +18 -0
  77. package/src/mcp/tools/precision-match.ts +51 -0
  78. package/src/mcp/tools/precision-query.ts +127 -0
  79. package/src/mcp/tools/precision.ts +312 -0
  80. package/src/mcp/tools/run-capture.ts +126 -44
  81. package/src/mcp/tools/safe-read.ts +14 -12
  82. package/src/mcp/tools/since.ts +7 -2
  83. package/src/mcp/tools/state.ts +11 -3
  84. package/src/mcp/tools/stats.ts +5 -1
  85. package/src/mcp/tools/workspace-authorizations.ts +14 -0
  86. package/src/mcp/tools/workspace-authorize.ts +20 -0
  87. package/src/mcp/tools/workspace-bind.ts +25 -0
  88. package/src/mcp/tools/workspace-rebind.ts +25 -0
  89. package/src/mcp/tools/workspace-revoke.ts +18 -0
  90. package/src/mcp/tools/workspace-status.ts +12 -0
  91. package/src/mcp/warp-pool.ts +36 -0
  92. package/src/mcp/workspace-router.ts +984 -0
  93. package/src/operations/file-outline.ts +12 -2
  94. package/src/operations/graft-diff.ts +56 -10
  95. package/src/operations/safe-read.ts +27 -4
  96. package/src/operations/state.ts +6 -9
  97. package/src/parser/lang.ts +19 -3
  98. package/src/parser/outline.ts +191 -2
  99. package/src/parser/types.ts +9 -1
  100. package/src/policy/types.ts +4 -3
  101. package/src/ports/filesystem.ts +1 -0
  102. package/src/ports/git.ts +16 -0
  103. package/src/ports/process-runner.ts +22 -0
  104. package/src/release/security-gate.ts +102 -0
  105. package/src/session/tracker.ts +31 -0
  106. package/src/version.ts +3 -0
  107. package/src/warp/indexer.ts +171 -56
  108. package/src/warp/observers.ts +1 -1
  109. package/src/warp/open.ts +4 -3
  110. package/src/warp/plumbing.d.ts +5 -1
  111. package/src/warp/writer-id.ts +30 -0
@@ -0,0 +1,12 @@
1
+ import * as path from "node:path";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { createGraftServer } from "./server.js";
4
+
5
+ export async function startStdioServer(cwd = process.cwd()): Promise<void> {
6
+ const graft = createGraftServer({
7
+ projectRoot: cwd,
8
+ graftDir: path.join(cwd, ".graft"),
9
+ });
10
+ const transport = new StdioServerTransport();
11
+ await graft.getMcpServer().connect(transport);
12
+ }
package/src/mcp/stdio.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { createGraftServer } from "./server.js";
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1
+ import { startStdioServer } from "./stdio-server.js";
3
2
 
4
- const graft = createGraftServer();
5
- const transport = new StdioServerTransport();
6
- await graft.getMcpServer().connect(transport);
3
+ await startStdioServer();
@@ -0,0 +1,325 @@
1
+ import { z } from "zod";
2
+ import { buildRuntimeStagedTarget } from "../runtime-staged-target.js";
3
+ import { deriveCausalSurfaceNextAction } from "../semantic-transition-guidance.js";
4
+ import type { PersistedLocalActivityItem } from "../persisted-local-history.js";
5
+ import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
6
+
7
+ const limitSchema = z.number().int().positive().max(50).optional();
8
+
9
+ type ActivityGroupKind = "transition" | "stage" | "continuity" | "read";
10
+
11
+ const GROUP_ORDER: readonly ActivityGroupKind[] = [
12
+ "transition",
13
+ "stage",
14
+ "continuity",
15
+ "read",
16
+ ];
17
+
18
+ function classifyActivityItem(item: PersistedLocalActivityItem): ActivityGroupKind {
19
+ if ("itemKind" in item) {
20
+ return "continuity";
21
+ }
22
+ if (item.eventKind === "transition") {
23
+ return "transition";
24
+ }
25
+ if (item.eventKind === "stage") {
26
+ return "stage";
27
+ }
28
+ return "read";
29
+ }
30
+
31
+ function groupLabel(kind: ActivityGroupKind): string {
32
+ switch (kind) {
33
+ case "transition":
34
+ return "semantic transitions";
35
+ case "stage":
36
+ return "staged activity";
37
+ case "continuity":
38
+ return "workspace continuity";
39
+ case "read":
40
+ return "read activity";
41
+ }
42
+ }
43
+
44
+ function buildAnchor(workspaceBound: boolean, headRef: string | null, headSha: string | null) {
45
+ if (!workspaceBound) {
46
+ return {
47
+ posture: "unknown" as const,
48
+ headRef: null,
49
+ headSha: null,
50
+ reason: "workspace_unbound" as const,
51
+ };
52
+ }
53
+ if (headSha === null) {
54
+ return {
55
+ posture: "unknown" as const,
56
+ headRef,
57
+ headSha: null,
58
+ reason: "missing_head_commit" as const,
59
+ };
60
+ }
61
+ return {
62
+ posture: "head_commit" as const,
63
+ headRef,
64
+ headSha,
65
+ };
66
+ }
67
+
68
+ function unique(values: readonly string[]): string[] {
69
+ return [...new Set(values)];
70
+ }
71
+
72
+ function pluralize(count: number, singular: string, plural = `${singular}s`): string {
73
+ return count === 1 ? singular : plural;
74
+ }
75
+
76
+ function countText(count: number): string {
77
+ return String(count);
78
+ }
79
+
80
+ function shortSha(sha: string | null): string {
81
+ return sha === null ? "unknown" : sha.slice(0, 7);
82
+ }
83
+
84
+ function describeAnchor(anchor: ReturnType<typeof buildAnchor>): string {
85
+ if (anchor.posture === "unknown") {
86
+ return anchor.reason === "workspace_unbound"
87
+ ? "Anchor to the current Git commit is unavailable because no workspace is bound."
88
+ : "Anchor to the current Git commit is unavailable because HEAD could not be resolved.";
89
+ }
90
+
91
+ const refLabel = anchor.headRef ?? "HEAD";
92
+ return `Current commit anchor is ${refLabel} @ ${shortSha(anchor.headSha)}. This view summarizes recent bounded local artifact history for the active checkout epoch, not a complete since-commit ledger.`;
93
+ }
94
+
95
+ function describeStagedTarget(
96
+ stagedTarget: ReturnType<typeof buildRuntimeStagedTarget>,
97
+ ): string {
98
+ switch (stagedTarget.availability) {
99
+ case "none":
100
+ return "No staged target is active.";
101
+ case "full_file":
102
+ return `Staged target is a full-file selection across ${countText(stagedTarget.target.selectionEntries.length)} ${pluralize(
103
+ stagedTarget.target.selectionEntries.length,
104
+ "path",
105
+ )}.`;
106
+ case "ambiguous":
107
+ return `Staged target is ambiguous across ${countText(stagedTarget.observedStagedPaths)} staged ${pluralize(
108
+ stagedTarget.observedStagedPaths,
109
+ "path",
110
+ )}.`;
111
+ }
112
+ }
113
+
114
+ function describeWorkspace(
115
+ repoConcurrency: { posture: string; summary: string } | null,
116
+ semanticTransitionSummary: string | null,
117
+ stagedTarget: ReturnType<typeof buildRuntimeStagedTarget>,
118
+ ): string {
119
+ return [
120
+ repoConcurrency === null
121
+ ? "Repo concurrency posture is unknown."
122
+ : `Repo concurrency posture is ${repoConcurrency.posture}. ${repoConcurrency.summary}`,
123
+ semanticTransitionSummary ?? "No active semantic transition is recorded.",
124
+ describeStagedTarget(stagedTarget),
125
+ ].join(" ");
126
+ }
127
+
128
+ function summarizeTransitionGroup(items: PersistedLocalActivityItem[]): string {
129
+ const transitionItems = items.filter((item) => "eventKind" in item && item.eventKind === "transition");
130
+ const latest = transitionItems[0];
131
+ if (latest === undefined) {
132
+ return "No semantic transitions are recorded.";
133
+ }
134
+ if (transitionItems.length === 1) {
135
+ return `1 semantic transition recorded: ${latest.payload.summary}.`;
136
+ }
137
+ return `${countText(transitionItems.length)} semantic transitions recorded, latest: ${latest.payload.summary}.`;
138
+ }
139
+
140
+ function summarizeStageGroup(items: PersistedLocalActivityItem[]): string {
141
+ const stageItems = items.filter((item) => "eventKind" in item && item.eventKind === "stage");
142
+ const uniquePaths = new Set<string>();
143
+ for (const item of stageItems) {
144
+ for (const path of item.footprint.paths) {
145
+ uniquePaths.add(path);
146
+ }
147
+ }
148
+ return `${countText(stageItems.length)} staging ${pluralize(stageItems.length, "event")} across ${countText(uniquePaths.size)} ${pluralize(
149
+ uniquePaths.size,
150
+ "path",
151
+ )}.`;
152
+ }
153
+
154
+ function summarizeContinuityGroup(items: PersistedLocalActivityItem[]): string {
155
+ const continuityItems = items.filter((item) => "itemKind" in item);
156
+ const operations = unique(continuityItems.map((item) => item.operation));
157
+ return `${countText(continuityItems.length)} continuity ${pluralize(continuityItems.length, "change")} (${operations.join(", ")}).`;
158
+ }
159
+
160
+ function summarizeReadGroup(items: PersistedLocalActivityItem[]): string {
161
+ const readItems = items.filter((item) => "eventKind" in item && item.eventKind === "read");
162
+ const uniquePaths = new Set<string>();
163
+ for (const item of readItems) {
164
+ for (const path of item.footprint.paths) {
165
+ uniquePaths.add(path);
166
+ }
167
+ }
168
+ const latest = readItems[0];
169
+ if (latest === undefined) {
170
+ return "No read activity is recorded.";
171
+ }
172
+ return `${countText(readItems.length)} reads across ${countText(uniquePaths.size)} ${pluralize(
173
+ uniquePaths.size,
174
+ "path",
175
+ )}, latest via ${latest.payload.surface}.`;
176
+ }
177
+
178
+ function summarizeGroup(
179
+ kind: ActivityGroupKind,
180
+ items: PersistedLocalActivityItem[],
181
+ ): string {
182
+ switch (kind) {
183
+ case "transition":
184
+ return summarizeTransitionGroup(items);
185
+ case "stage":
186
+ return summarizeStageGroup(items);
187
+ case "continuity":
188
+ return summarizeContinuityGroup(items);
189
+ case "read":
190
+ return summarizeReadGroup(items);
191
+ }
192
+ }
193
+
194
+ function buildHeadline(
195
+ returned: number,
196
+ truncated: boolean,
197
+ ): string {
198
+ const headline = `Showing ${countText(returned)} recent ${pluralize(returned, "activity item")} from bounded local artifact history for the active line of work.`;
199
+ return truncated ? `${headline} Results are truncated to the requested window.` : headline;
200
+ }
201
+
202
+ export const activityViewTool: ToolDefinition = {
203
+ name: "activity_view",
204
+ description:
205
+ "Inspect recent bounded local artifact history for the active workspace, anchored to the current commit when possible.",
206
+ schema: {
207
+ limit: limitSchema,
208
+ },
209
+ createHandler(ctx: ToolContext): ToolHandler {
210
+ return async (args) => {
211
+ const limit = limitSchema.parse(args["limit"]) ?? 20;
212
+ const workspaceStatus = ctx.getWorkspaceStatus();
213
+
214
+ if (workspaceStatus.bindState === "unbound") {
215
+ return ctx.respond("activity_view", {
216
+ ...workspaceStatus,
217
+ truthClass: "artifact_history",
218
+ anchor: buildAnchor(false, null, null),
219
+ summary: {
220
+ headline: buildHeadline(0, false),
221
+ anchor: "Anchor to the current Git commit is unavailable because no workspace is bound.",
222
+ workspace: "No active causal workspace is available until a workspace is bound.",
223
+ groups: [],
224
+ },
225
+ activeCausalWorkspace: null,
226
+ activityWindow: {
227
+ historyPath: null,
228
+ limit,
229
+ returned: 0,
230
+ totalMatchingItems: 0,
231
+ truncated: false,
232
+ missingSignalKinds: ["write_events_not_captured"],
233
+ groups: [],
234
+ },
235
+ degradedReasons: ["workspace_unbound", "anchor_unknown"],
236
+ nextAction: "bind_workspace_to_begin_local_history",
237
+ });
238
+ }
239
+
240
+ const repoState = ctx.getRepoState();
241
+ const causalContext = ctx.getCausalContext();
242
+ const persistedLocalHistory = await ctx.getPersistedLocalHistorySummary();
243
+ const activityWindow = await ctx.getPersistedLocalActivityWindow(limit);
244
+ const workspaceOverlayFooting = await ctx.getWorkspaceOverlayFooting();
245
+ const repoConcurrency = await ctx.getRepoConcurrencySummary();
246
+ const nextAction = deriveCausalSurfaceNextAction(
247
+ persistedLocalHistory.nextAction,
248
+ repoState.semanticTransition,
249
+ repoConcurrency,
250
+ );
251
+ const stagedTarget = buildRuntimeStagedTarget(
252
+ workspaceStatus,
253
+ causalContext,
254
+ repoState,
255
+ persistedLocalHistory.attribution,
256
+ );
257
+ const anchor = buildAnchor(true, repoState.headRef, repoState.headSha);
258
+ const workspaceOverlayDegradedReason = workspaceOverlayFooting?.degradedReason ?? null;
259
+
260
+ const groups = GROUP_ORDER.map((groupKind) => {
261
+ const items = activityWindow.items.filter((item) => classifyActivityItem(item) === groupKind);
262
+ if (items.length === 0) {
263
+ return null;
264
+ }
265
+ return {
266
+ groupKind,
267
+ label: groupLabel(groupKind),
268
+ summary: summarizeGroup(groupKind, items),
269
+ count: items.length,
270
+ items,
271
+ };
272
+ }).filter((group) => group !== null);
273
+
274
+ const degradedReasons = unique([
275
+ ...(anchor.posture === "unknown" ? ["anchor_unknown"] : []),
276
+ ...(workspaceOverlayDegradedReason === null ? [] : [workspaceOverlayDegradedReason]),
277
+ ...(stagedTarget.availability === "ambiguous" ? ["staged_target_ambiguous"] : []),
278
+ ...(repoConcurrency !== null && repoConcurrency.posture !== "exclusive"
279
+ ? [repoConcurrency.posture]
280
+ : []),
281
+ ]);
282
+
283
+ return ctx.respond("activity_view", {
284
+ ...workspaceStatus,
285
+ truthClass: "artifact_history",
286
+ anchor,
287
+ summary: {
288
+ headline: buildHeadline(activityWindow.items.length, activityWindow.truncated),
289
+ anchor: describeAnchor(anchor),
290
+ workspace: describeWorkspace(
291
+ repoConcurrency === null
292
+ ? null
293
+ : { posture: repoConcurrency.posture, summary: repoConcurrency.summary },
294
+ repoState.semanticTransition?.summary ?? null,
295
+ stagedTarget,
296
+ ),
297
+ groups: groups.map((group) => group.summary),
298
+ },
299
+ activeCausalWorkspace: {
300
+ causalContext,
301
+ attribution: persistedLocalHistory.attribution,
302
+ repoConcurrency,
303
+ checkoutEpoch: repoState.checkoutEpoch,
304
+ lastTransition: repoState.lastTransition,
305
+ semanticTransition: repoState.semanticTransition,
306
+ workspaceOverlayId: repoState.workspaceOverlayId,
307
+ workspaceOverlay: repoState.workspaceOverlay,
308
+ workspaceOverlayFooting,
309
+ stagedTarget,
310
+ },
311
+ activityWindow: {
312
+ historyPath: activityWindow.historyPath,
313
+ limit: activityWindow.limit,
314
+ returned: activityWindow.items.length,
315
+ totalMatchingItems: activityWindow.totalMatchingItems,
316
+ truncated: activityWindow.truncated,
317
+ missingSignalKinds: ["write_events_not_captured"],
318
+ groups,
319
+ },
320
+ degradedReasons,
321
+ nextAction,
322
+ });
323
+ };
324
+ },
325
+ };
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ import { buildRuntimeStagedTarget } from "../runtime-staged-target.js";
3
+ import { deriveCausalSurfaceNextAction } from "../semantic-transition-guidance.js";
4
+ import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
5
+
6
+ const actorKindSchema = z.enum(["human", "agent"]);
7
+
8
+ export const causalAttachTool: ToolDefinition = {
9
+ name: "causal_attach",
10
+ description:
11
+ "Explicitly declare lawful continuation or handoff for the current causal workspace.",
12
+ schema: {
13
+ actor_kind: actorKindSchema,
14
+ actor_id: z.string().min(1).optional(),
15
+ from_actor_id: z.string().min(1).optional(),
16
+ note: z.string().min(1).optional(),
17
+ },
18
+ createHandler(ctx: ToolContext): ToolHandler {
19
+ return async (args) => {
20
+ const result = await ctx.declareCausalAttach({
21
+ actorKind: actorKindSchema.parse(args["actor_kind"]),
22
+ actorId: typeof args["actor_id"] === "string" ? args["actor_id"] : undefined,
23
+ fromActorId: typeof args["from_actor_id"] === "string" ? args["from_actor_id"] : undefined,
24
+ note: typeof args["note"] === "string" ? args["note"] : undefined,
25
+ });
26
+
27
+ const workspaceStatus = ctx.getWorkspaceStatus();
28
+ const repoState = ctx.getRepoState();
29
+ const causalContext = ctx.getCausalContext();
30
+ const workspaceOverlayFooting = await ctx.getWorkspaceOverlayFooting();
31
+ const repoConcurrency = await ctx.getRepoConcurrencySummary();
32
+ const nextAction = deriveCausalSurfaceNextAction(
33
+ result.persistedLocalHistory.nextAction,
34
+ repoState.semanticTransition,
35
+ repoConcurrency,
36
+ );
37
+ const activeCausalWorkspace = workspaceStatus.bindState === "bound"
38
+ ? {
39
+ causalContext,
40
+ attribution: result.persistedLocalHistory.attribution,
41
+ latestReadEvent: result.persistedLocalHistory.latestReadEvent,
42
+ latestStageEvent: result.persistedLocalHistory.latestStageEvent,
43
+ latestTransitionEvent: result.persistedLocalHistory.latestTransitionEvent,
44
+ repoConcurrency,
45
+ checkoutEpoch: repoState.checkoutEpoch,
46
+ lastTransition: repoState.lastTransition,
47
+ semanticTransition: repoState.semanticTransition,
48
+ workspaceOverlayId: repoState.workspaceOverlayId,
49
+ workspaceOverlay: repoState.workspaceOverlay,
50
+ workspaceOverlayFooting,
51
+ stagedTarget: buildRuntimeStagedTarget(
52
+ workspaceStatus,
53
+ causalContext,
54
+ repoState,
55
+ result.persistedLocalHistory.attribution,
56
+ ),
57
+ }
58
+ : null;
59
+
60
+ return ctx.respond("causal_attach", {
61
+ ...result,
62
+ activeCausalWorkspace,
63
+ nextAction,
64
+ });
65
+ };
66
+ },
67
+ };
@@ -0,0 +1,58 @@
1
+ import { buildRuntimeStagedTarget } from "../runtime-staged-target.js";
2
+ import { deriveCausalSurfaceNextAction } from "../semantic-transition-guidance.js";
3
+ import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
4
+
5
+ export const causalStatusTool: ToolDefinition = {
6
+ name: "causal_status",
7
+ description:
8
+ "Inspect the active causal workspace and persisted local-history posture.",
9
+ createHandler(ctx: ToolContext): ToolHandler {
10
+ return async () => {
11
+ const workspaceStatus = ctx.getWorkspaceStatus();
12
+ const persistedLocalHistory = await ctx.getPersistedLocalHistorySummary();
13
+ if (workspaceStatus.bindState === "unbound") {
14
+ return ctx.respond("causal_status", {
15
+ ...workspaceStatus,
16
+ activeCausalWorkspace: null,
17
+ persistedLocalHistory,
18
+ nextAction: persistedLocalHistory.nextAction,
19
+ });
20
+ }
21
+
22
+ const repoState = ctx.getRepoState();
23
+ const causalContext = ctx.getCausalContext();
24
+ const workspaceOverlayFooting = await ctx.getWorkspaceOverlayFooting();
25
+ const repoConcurrency = await ctx.getRepoConcurrencySummary();
26
+ const nextAction = deriveCausalSurfaceNextAction(
27
+ persistedLocalHistory.nextAction,
28
+ repoState.semanticTransition,
29
+ repoConcurrency,
30
+ );
31
+ return ctx.respond("causal_status", {
32
+ ...workspaceStatus,
33
+ activeCausalWorkspace: {
34
+ causalContext,
35
+ attribution: persistedLocalHistory.attribution,
36
+ latestReadEvent: persistedLocalHistory.latestReadEvent,
37
+ latestStageEvent: persistedLocalHistory.latestStageEvent,
38
+ latestTransitionEvent: persistedLocalHistory.latestTransitionEvent,
39
+ repoConcurrency,
40
+ checkoutEpoch: repoState.checkoutEpoch,
41
+ lastTransition: repoState.lastTransition,
42
+ semanticTransition: repoState.semanticTransition,
43
+ workspaceOverlayId: repoState.workspaceOverlayId,
44
+ workspaceOverlay: repoState.workspaceOverlay,
45
+ workspaceOverlayFooting,
46
+ stagedTarget: buildRuntimeStagedTarget(
47
+ workspaceStatus,
48
+ causalContext,
49
+ repoState,
50
+ persistedLocalHistory.attribution,
51
+ ),
52
+ },
53
+ persistedLocalHistory,
54
+ nextAction,
55
+ });
56
+ };
57
+ },
58
+ };
@@ -1,11 +1,10 @@
1
1
  import { z } from "zod";
2
- import { evaluatePolicy } from "../../policy/evaluate.js";
3
2
  import { RefusedResult } from "../../policy/types.js";
4
- import { extractOutline } from "../../parser/outline.js";
3
+ import { extractOutlineForFile } from "../../parser/outline.js";
5
4
  import { diffOutlines } from "../../parser/diff.js";
6
- import { detectLang } from "../../parser/lang.js";
7
5
  import { hashContent } from "../cache.js";
8
6
  import type { ToolDefinition, ToolContext, ToolHandler } from "../context.js";
7
+ import { evaluateMcpPolicy } from "../policy.js";
9
8
 
10
9
  export const changedSinceTool: ToolDefinition = {
11
10
  name: "changed_since",
@@ -15,7 +14,7 @@ export const changedSinceTool: ToolDefinition = {
15
14
  "default; pass consume: true to update the observation cache.",
16
15
  schema: { path: z.string(), consume: z.boolean().optional() },
17
16
  createHandler(ctx: ToolContext): ToolHandler {
18
- return (args) => {
17
+ return async (args) => {
19
18
  const filePath = ctx.resolvePath(args["path"] as string);
20
19
  const consume = (args["consume"] as boolean | undefined) === true;
21
20
 
@@ -23,7 +22,7 @@ export const changedSinceTool: ToolDefinition = {
23
22
  // Read the file first to get dimensions for policy evaluation.
24
23
  let rawContent: string;
25
24
  try {
26
- rawContent = ctx.fs.readFileSync(filePath, "utf-8");
25
+ rawContent = await ctx.fs.readFile(filePath, "utf-8");
27
26
  } catch {
28
27
  return ctx.respond("changed_since", { status: "file_not_found" });
29
28
  }
@@ -32,14 +31,19 @@ export const changedSinceTool: ToolDefinition = {
32
31
  lines: rawContent.split("\n").length,
33
32
  bytes: Buffer.byteLength(rawContent),
34
33
  };
35
- const policy = evaluatePolicy(
36
- { path: filePath, lines: actual.lines, bytes: actual.bytes },
37
- { sessionDepth: ctx.session.getSessionDepth() },
38
- );
34
+ const policy = evaluateMcpPolicy(ctx, filePath, actual);
39
35
  if (policy instanceof RefusedResult) {
40
36
  return ctx.respond("changed_since", { status: "refused", reason: policy.reason });
41
37
  }
42
38
 
39
+ const newOutlineResult = extractOutlineForFile(filePath, rawContent);
40
+ if (newOutlineResult === null) {
41
+ return ctx.respond("changed_since", {
42
+ status: "unsupported",
43
+ reason: "UNSUPPORTED_LANGUAGE",
44
+ });
45
+ }
46
+
43
47
  const cacheResult = ctx.cache.check(filePath, rawContent);
44
48
  if (cacheResult.hit) {
45
49
  return ctx.respond("changed_since", { status: "unchanged" });
@@ -48,8 +52,6 @@ export const changedSinceTool: ToolDefinition = {
48
52
  return ctx.respond("changed_since", { status: "no_previous_observation" });
49
53
  }
50
54
 
51
- // Use extractOutline with rawContent directly to avoid snapshot race.
52
- const newOutlineResult = extractOutline(rawContent, detectLang(filePath) ?? "ts");
53
55
  const diff = diffOutlines(cacheResult.stale.outline, newOutlineResult.entries);
54
56
 
55
57
  if (consume) {