-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
1243 lines (1161 loc) · 62.9 KB
/
Copy pathserver.ts
File metadata and controls
1243 lines (1161 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* AXME Code MCP Server - stdio transport.
*
* Server-side state:
* - Detects workspace/project from cwd at startup
* - Provides `instructions` to Claude Code for auto-context loading
* - Defaults project_path/workspace_path in all tools from cwd
*/
import { join } from "node:path";
import { existsSync } from "node:fs";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { getFullContextSections, getOracle, getDecisions, buildDecisionsCatalogString, buildMemoriesCatalogString } from "./tools/context.js";
import { allMemoryContext, getMemorySections } from "./storage/memory.js";
import { getOracleSections } from "./storage/oracle.js";
import { getDecisionSections } from "./storage/decisions.js";
import { paginateSections } from "./utils/pagination.js";
import { saveMemoryTool } from "./tools/memory-tools.js";
import { saveDecisionTool } from "./tools/decision-tools.js";
import { updateSafetyTool, showSafetyTool } from "./tools/safety-tools.js";
import { statusTool, worklogTool } from "./tools/status.js";
import { getMemoryTool, getDecisionTool, searchKbTool } from "./tools/kb-search.js";
import { embedKbEntry } from "./storage/embeddings.js";
import { readConfig } from "./storage/config.js";
import { detectWorkspace } from "./utils/workspace-detector.js";
import {
findOrphanSessions,
listClaudeSessionMappings,
writeClaudeSessionMapping,
clearClaudeSessionMapping,
clearLegacyActiveSession,
clearLegacyPendingAuditsDir,
readClaudeSessionMapping,
isPidAlive,
loadSession,
closeSession,
getOwnAncestorPids,
} from "./storage/sessions.js";
import { logEvent } from "./storage/worklog.js";
import { spawnDetachedAuditWorker } from "./audit-spawner.js";
import { AXME_CODE_VERSION } from "./types.js";
// --- Server state (detected at startup from --workspace flag or cwd) ---
//
// When the Cursor extension registers the MCP server it cannot control the
// cwd Cursor uses to spawn us — empirically Cursor spawns from the user's
// home directory regardless of which workspace is open. Falling back to
// cwd makes the server report a wrong `defaultProjectPath` and tools like
// axme_context (called without explicit project_path) look up
// `.axme-code/` in the wrong place. The fix is the extension passing
// `--workspace <abs>` at registration time so the server has the right
// root from the first tool call.
//
// Resolution order:
// 1. --workspace <path> CLI flag (passed by the Cursor extension)
// 2. AXME_WORKSPACE env var (escape hatch for hand-spawned servers)
// 3. process.cwd() (legacy Claude Code CLI behaviour — server spawns
// from the project root so cwd already points at the right place)
function resolveServerRoot(): string {
const argv = process.argv;
const flagIdx = argv.indexOf("--workspace");
if (flagIdx > -1 && argv[flagIdx + 1]) return argv[flagIdx + 1];
if (process.env.AXME_WORKSPACE) return process.env.AXME_WORKSPACE;
return process.cwd();
}
const serverCwd = resolveServerRoot();
const serverHasGit = existsSync(join(serverCwd, ".git"));
const serverWorkspace = detectWorkspace(serverCwd);
const isWorkspace = serverHasGit ? false : serverWorkspace.type !== "single";
const defaultProjectPath = serverCwd;
const defaultWorkspacePath = isWorkspace ? serverCwd : null;
// The MCP server does NOT create an AXME session at startup. AXME sessions
// are created lazily by hooks on the first tool call — that's when we learn
// the Claude session_id, which is the key for multi-window isolation.
//
// Instead of a single "currentSession", the server owns all AXME sessions
// created by hooks of the same IDE instance that spawned us. Hooks record
// ownerPpid via getClaudeCodePid() (their grandparent above the sh wrapper).
// Under Claude Code that equals our PARENT — claude spawns hooks and the
// MCP server alike. Cursor adds a layer: hooks hang off the cursor-server
// main process while we are a child of the extension host, so the recorded
// owner is our GRANDparent and strict ppid equality never matched — every
// Cursor extension install had session close / audit / worklog silently
// dead ("No active AXME session found", QA 2026-06-11). Match against our
// ancestor chain instead; chain[0] is process.ppid, so the Claude Code
// behavior is unchanged.
const OWN_PPID = process.ppid;
const OWN_ANCESTOR_PIDS = new Set<number>(getOwnAncestorPids(4));
function isOwnedMapping(ownerPpid: number | undefined): boolean {
return ownerPpid != null && OWN_ANCESTOR_PIDS.has(ownerPpid);
}
// Track which context paths have been delivered in this MCP session.
// Used by axme_oracle/decisions/memories to avoid duplicating workspace
// data when a repo-level call follows a workspace-level call.
// Key format: "oracle:<path>", "decisions:<path>", "memories:<path>"
const deliveredContext = new Set<string>();
// Clean up any legacy .axme-code/active-session single-file marker from
// older versions. It is stale by definition after the switch to per-Claude
// mapping files.
clearLegacyActiveSession(defaultProjectPath);
// Same for the legacy .axme-code/pending-audits/ directory: that state now
// lives on SessionMeta.auditStatus, so the directory is dead weight.
clearLegacyPendingAuditsDir(defaultProjectPath);
// Start background auto-update check (non-blocking, never crashes server)
import { backgroundAutoUpdate, getUpdateNotification } from "./auto-update.js";
backgroundAutoUpdate().catch(() => {});
// Send anonymous startup telemetry (install/startup/update) — never throws.
// We do not await here because server.ts is a top-level module side-effect;
// the event loop has plenty of time during MCP server lifetime to flush.
import { sendStartupEvents } from "./telemetry.js";
void sendStartupEvents();
/**
* Return the AXME session UUID owned by this MCP server for worklog purposes.
* If there are multiple owned sessions (shouldn't happen normally), returns
* the first one.
*
* Session recovery: if no mapping matches OWN_PPID (e.g. after VS Code reload
* where a new Claude Code process spawned this MCP server but the old mapping
* still points to the previous PID), we adopt stale mappings whose ownerPpid
* is dead. This ensures MCP tools work without requiring a hook-triggering
* built-in tool call first.
*/
function getOwnedSessionIdForLogging(): string | undefined {
const all = listClaudeSessionMappings(defaultProjectPath);
const owned = all.filter(m => isOwnedMapping(m.ownerPpid));
if (owned.length > 0) return owned[0].axmeSessionId;
// No mapping for our PID — check for stale mappings from dead Claude Code
// processes and adopt them. This handles VS Code reload where the old
// Claude Code process died but its mapping file persists.
for (const m of all) {
if (m.ownerPpid != null && !isPidAlive(m.ownerPpid)) {
writeClaudeSessionMapping(defaultProjectPath, m.claudeSessionId, m.axmeSessionId);
process.stderr.write(
`AXME: adopted stale mapping ${m.claudeSessionId.slice(0, 8)} ` +
`(old ppid=${m.ownerPpid}, new ppid=${OWN_PPID})\n`,
);
return m.axmeSessionId;
}
}
return undefined;
}
// Session cleanup is triggered by transport.onclose (see main() below) rather
// than process.on("exit") — exit handlers cannot do meaningful work.
//
// CRITICAL: cleanupAndExit DOES NOT run the audit itself. It spawns a detached
// background worker process per owned session and exits immediately. Why:
//
// VS Code may kill this MCP server process within milliseconds of closing
// the Claude Code window (especially in center-editor-tab mode where the
// tab close triggers an immediate SIGKILL, unlike the side-panel mode which
// gives us more time). Running the audit synchronously here means it dies
// mid-LLM-call and the session gets stuck at phase="started" forever.
//
// The detached worker runs in its own process group (setsid via
// `detached: true`), survives any signal to this server's process group,
// and reads fresh code from dist/cli.mjs on every spawn — so iteration on
// the auditor does not require a VS Code window reload.
//
// The worker is `axme-code audit-session --workspace X --session Y` and
// it calls the same runSessionCleanup() this file used to call directly.
// Concurrency is handled by auditStatus="pending" + stale timeout inside
// runSessionCleanup itself — two workers for the same session cannot both
// run the LLM, the second will hit "concurrent-audit" skip and exit.
let cleanupRunning = false;
async function cleanupAndExit(reason: string): Promise<void> {
if (cleanupRunning) return;
cleanupRunning = true;
// Find all mapping files owned by our Claude Code parent process, spawn a
// detached audit worker for each, clear the mapping, and exit. No awaiting.
try {
const mappings = listClaudeSessionMappings(defaultProjectPath);
const owned = mappings.filter(m => isOwnedMapping(m.ownerPpid));
// Deduplicate: group AXME sessions by Claude session ID.
// Multiple AXME sessions can share the same Claude session (race condition
// from parallel hooks). Only audit one per Claude session — the newest.
const claudeToAxme = new Map<string, { axmeId: string; createdAt: number }[]>();
for (const m of owned) {
const session = loadSession(defaultProjectPath, m.axmeSessionId);
if (!session) continue;
for (const ref of session.claudeSessions ?? []) {
const list = claudeToAxme.get(ref.id) ?? [];
list.push({ axmeId: m.axmeSessionId, createdAt: Date.parse(session.createdAt) || 0 });
claudeToAxme.set(ref.id, list);
}
}
const toAudit = new Set<string>();
const toSkip = new Set<string>();
for (const [, entries] of claudeToAxme) {
entries.sort((a, b) => b.createdAt - a.createdAt); // newest first
toAudit.add(entries[0].axmeId);
for (let i = 1; i < entries.length; i++) toSkip.add(entries[i].axmeId);
}
// Mark duplicates as done so they don't linger
for (const skipId of toSkip) {
try { closeSession(defaultProjectPath, skipId); } catch {}
}
process.stderr.write(
`AXME cleanup (${reason}): ${owned.length} owned, ${toAudit.size} to audit, ${toSkip.size} deduped\n`,
);
for (const m of owned) {
if (!toAudit.has(m.axmeSessionId)) {
try { clearClaudeSessionMapping(defaultProjectPath, m.claudeSessionId); } catch {}
continue;
}
try {
spawnDetachedAuditWorker(defaultProjectPath, m.axmeSessionId);
} catch (err) {
process.stderr.write(`AXME cleanup: failed to spawn worker for ${m.axmeSessionId}: ${err}\n`);
}
try { clearClaudeSessionMapping(defaultProjectPath, m.claudeSessionId); } catch {}
}
} catch (err) {
process.stderr.write(`AXME cleanup scan failed (${reason}): ${err}\n`);
}
process.exit(0);
}
// --- Build instructions for Claude Code ---
function buildInstructions(): string {
const parts = [
"AXME Code MCP server is active.",
`Project: ${defaultProjectPath}.`,
];
if (isWorkspace) {
parts.push(`Workspace: ${defaultWorkspacePath} (${serverWorkspace.type}, ${serverWorkspace.projects.length} projects).`);
parts.push("Call axme_context at session start to load workspace overview. It returns compact meta and instructions to call axme_oracle, axme_decisions, axme_memories in parallel.");
parts.push("Each repo has its own .axme-code/ storage initialized during setup.");
parts.push("Before working with any specific repo, call axme_context with that repo's path.");
} else {
parts.push("Call axme_context at session start. It returns compact meta and instructions to call axme_oracle, axme_decisions, axme_memories in parallel.");
}
// Per-project setup gate: AXME is configured ONCE per repo (writes
// .axme-code/ at the project root). When the agent lands in a fresh repo
// and the storage is absent, axme_context returns "project not
// initialised" — easy for the agent to ignore. Make it impossible to
// miss by stating the obligation up-front in the instructions block so
// the agent reads it BEFORE the first axme_context call.
const axmeDirExists = existsSync(join(defaultProjectPath, ".axme-code"));
if (!axmeDirExists) {
parts.push(
"PROJECT SETUP REQUIRED (HIGHEST PRIORITY): this project has no " +
".axme-code/ directory. BEFORE doing anything else, tell the user " +
"in their language: \"AXME is not set up for this project. Want " +
"me to do it now? I'll scan the repo and save architecture " +
"decisions, patterns and safety rules into .axme-code/ — runs " +
"inline on the subscription you already use for this chat, no " +
"extra API key or cost.\" If the user " +
"agrees (any affirmative in any language), EXECUTE setup. " +
"Important — setup is a sequence of MCP TOOL CALLS, not a plan " +
"to describe. Bullet-listing what you would save in prose is a " +
"FAILURE — call the tool instead. Required:\n" +
" 1. Scan: read package.json/README/main configs + key source " +
"folders to understand stack, conventions, layout.\n" +
" 2. EXECUTE at least 5 axme_save_decision calls (scope=" +
"[\"workspace\"], with concrete rationale tied to evidence).\n" +
" 3. EXECUTE at least 3 axme_save_memory calls (type=\"pattern\", " +
"scope=[\"workspace\"]) for gotchas / edge cases.\n" +
" 4. EXECUTE axme_update_safety for dangerous patterns in " +
"scripts/ or destructive commands.\n" +
" 4b. EXECUTE 4 axme_save_oracle calls — one per section (stack, " +
"structure, patterns, glossary). Stack: languages + frameworks " +
"+ build tools. Structure: top-level dirs + entry points. " +
"Patterns: observed conventions. Glossary: project-specific " +
"terms. Oracle is the high-level overview the agent reads at " +
"startup of every future session.\n" +
" 5. ONLY after all tool calls are committed, summarize:\n" +
" First line: \"Saved X decisions, Y memories, Z safety rules " +
"+ N preset rules\" where N is the count of enforcement entries " +
"(deniedPrefixes + deniedCommands + protectedBranches + " +
"deniedPaths + readOnlyPaths) ALREADY in .axme-code/safety/" +
"rules.yaml that you did NOT add this session.\n" +
" Then list those preset rules grouped by section (one " +
"per line under each header) and add: \"These presets ship " +
"with AXME Code. You can edit .axme-code/safety/rules.yaml " +
"directly to add project-specific rules or remove ones you " +
"don't need.\"\n" +
" Then list DECISIONS saved this session — one per line as " +
"\" - D-NNN: <short title>\". Header: \"Decisions saved this " +
"session (full bodies in .axme-code/decisions/):\". Keep titles " +
"short — rationale already lives in the .md files.\n" +
" Then list MEMORIES saved — one per line as \" - <slug>: " +
"<short title>\". Header: \"Memories saved this session (full " +
"bodies in .axme-code/memory/patterns/ and memory/feedback/):\".\n" +
" End with verbatim line: \"All saved artifacts are persistent " +
"across sessions. Open the folders above to read full bodies, " +
"or ask me 'show decision D-NNN' / 'show memory <slug>' to " +
"fetch any of them.\"\n" +
"If you catch yourself writing \"Save decision: X / Save memory: " +
"Y\" as text, STOP and call axme_save_decision / axme_save_memory " +
"instead. The .axme-code/ directory is auto-bootstrapped by the " +
"first save call — you do not need to create it beforehand. After " +
"setup, proceed with the user's original request.",
);
}
parts.push("TRUNCATED OUTPUT RULE: if ANY MCP tool output is truncated or saved to a file (you see 'Output too large' or 'saved to file'), you MUST use the Read tool to read the full file content into your context. Do not proceed with partial data.");
parts.push("Save memories, decisions, and safety rules immediately when discovered during work.");
parts.push("GIT COMMIT/PUSH GATE: every git commit and git push command MUST end with `#!axme pr=<NUMBER|none> repo=<OWNER/REPO>`. Example: `git commit -m \"fix bug\" #!axme pr=42 repo=AxmeAI/axme-code`. Use pr=none if no PR exists yet. Without this suffix the command will be blocked.");
parts.push("RELEASE/TAG PROHIBITION: agent must NEVER run git tag, npm publish, twine upload, dotnet nuget push, mvn deploy, gh release create, or gh workflow run deploy-prod. These are blocked by safety hooks. To release: prepare version bump + CHANGELOG + PR, then provide ready-to-run tag/publish commands to the user.");
parts.push("SESSION CLOSE: when the user asks to close/end the session (any language), call axme_begin_close to get the close checklist. Follow it: extract memories/decisions/safety (choosing correct scope for each), prepare handoff data, then call axme_finalize_close with everything. After finalize, output to the user: storage summary (what saved where), then startup_text.");
parts.push("DECISION CONFLICT RULE: if two active decisions contradict each other, treat the NEWER one (by date) as authoritative. The older one is a candidate for supersede at next audit.");
parts.push(
`STORAGE ROOT: ${join(defaultProjectPath, ".axme-code")} — for any direct inspection of .axme-code/ files via Bash (ls, cat, grep, find), use this ABSOLUTE path. Do NOT use relative paths from your cwd; in a multi-repo workspace your cwd may point to a child repo with its own separate .axme-code/ storage.`,
);
parts.push(
"IMPORTANT: if axme_context output contains a 'Pending audits' section, " +
"a previous session's audit is still running and the knowledge base is incomplete. " +
"Tell the user, offer to wait and re-run axme_context or track with a TODO.",
);
return parts.join(" ");
}
const server = new McpServer(
// Report the real release version: serverInfo previously hardcoded
// "0.1.0", which made "which version is my IDE actually running?"
// undebuggable from the client side.
{ name: "axme", version: AXME_CODE_VERSION },
{ instructions: buildInstructions() },
);
// Wrap every tool handler with a try/catch that reports caught exceptions to
// telemetry under the `mcp_tool` category. We monkey-patch server.tool() once
// here instead of touching all 19 individual tool registrations below. The
// MCP SDK still receives any thrown error and returns it to the client, so
// no behavior changes — we only add an extra observability hook.
//
// Why fatal=true: an exception that bubbles out of a tool handler means the
// tool call did not complete its intended work — the user-visible operation
// has aborted. That matches our "fatal vs degraded" definition.
const _origRegisterTool: any = server.tool.bind(server);
(server as any).tool = function (...args: any[]): any {
// Last argument is always the handler function
const handler = args[args.length - 1];
if (typeof handler === "function") {
args[args.length - 1] = async (...handlerArgs: any[]): Promise<any> => {
try {
return await handler(...handlerArgs);
} catch (err) {
try {
const { reportError, classifyError } = await import("./telemetry.js");
reportError("mcp_tool", classifyError(err), true);
} catch { /* never throw from telemetry */ }
throw err;
}
};
}
return _origRegisterTool.apply(server, args);
};
// --- Helper: resolve paths with defaults from server state ---
function pp(project_path?: string): string {
return project_path || defaultProjectPath;
}
/**
* Resolve project_path from scope when project_path is not explicitly provided.
* If scope contains a specific repo name (not "all"), resolve to workspace/repo-name.
* Falls back to pp() default behavior.
*/
function ppWithScope(project_path?: string, scope?: string[]): string {
if (project_path) return project_path;
if (isWorkspace && scope && scope.length > 0) {
const repoScope = scope.find(s => s !== "all");
if (repoScope) {
const match = serverWorkspace.projects.find(p => p.name === repoScope);
if (match) return join(defaultProjectPath, match.path);
}
// scope: ["all"] or no match -> workspace root
}
return defaultProjectPath;
}
function wp(workspace_path?: string): string | undefined {
return workspace_path || defaultWorkspacePath || undefined;
}
// axme_init removed - init only via `axme-code setup` in terminal
// axme_context will detect if project is not initialized and tell the user
// --- axme_context ---
server.tool(
"axme_context",
"Read full project context (oracle + decisions + safety + memory + test plan + active plans). Use at session start. Pass workspace_path for merged multi-repo context.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
workspace_path: z.string().optional().describe("Absolute path to workspace root (defaults to detected workspace)"),
page: z.number().optional().describe("Page number (1-based). Omit for first page. Follow pagination instructions if output is split."),
},
async ({ project_path, workspace_path, page }) => {
const sections = getFullContextSections(pp(project_path), wp(workspace_path));
// Inject auto-update notification if available (first page only)
const updateMsg = getUpdateNotification();
if (updateMsg && (!page || page === 1)) {
sections.unshift(`**Update**: ${updateMsg}`);
}
const result = paginateSections(sections, page ?? 1, "axme_context", { project_path, workspace_path });
return { content: [{ type: "text" as const, text: result.text }] };
},
);
// --- axme_oracle ---
server.tool(
"axme_oracle",
"Show project oracle data (stack, structure, patterns, glossary).",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
page: z.number().optional().describe("Page number (1-based). Omit for first page. Follow pagination instructions if output is split."),
},
async ({ project_path, page }) => {
const resolved = pp(project_path);
deliveredContext.add("oracle:" + resolved);
let sections = getOracleSections(resolved);
// If requesting repo oracle and workspace oracle was already delivered, return repo-only
if (isWorkspace && defaultWorkspacePath && resolved !== defaultWorkspacePath
&& deliveredContext.has("oracle:" + defaultWorkspacePath)) {
sections = [...sections, "*(Workspace oracle already loaded)*"];
}
const result = paginateSections(sections, page ?? 1, "axme_oracle", { project_path });
return { content: [{ type: "text" as const, text: result.text }] };
},
);
// --- axme_decisions ---
server.tool(
"axme_decisions",
"Show project decisions. Output adapts to context.mode: full → enforce levels + decision body; search → catalog (id + title + 1-line description, fetch bodies via axme_get_decision).",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
page: z.number().optional().describe("Page number (1-based). Omit for first page. Follow pagination instructions if output is split."),
},
async ({ project_path, page }) => {
const resolved = pp(project_path);
deliveredContext.add("decisions:" + resolved);
const config = readConfig(resolved);
const wsAlreadyDelivered = isWorkspace && defaultWorkspacePath && resolved !== defaultWorkspacePath
&& deliveredContext.has("decisions:" + defaultWorkspacePath);
let sections: string[];
if (config.contextMode === "search") {
const wsForMerge = isWorkspace && defaultWorkspacePath && resolved !== defaultWorkspacePath && !wsAlreadyDelivered
? defaultWorkspacePath : undefined;
sections = [buildDecisionsCatalogString(resolved, wsForMerge)];
} else {
sections = getDecisionSections(resolved);
}
if (wsAlreadyDelivered) {
sections = [...sections, "*(Workspace decisions already loaded)*"];
}
const result = paginateSections(sections, page ?? 1, "axme_decisions", { project_path });
return { content: [{ type: "text" as const, text: result.text }] };
},
);
// --- axme_memories ---
server.tool(
"axme_memories",
"Show project memories (feedback + patterns). Output adapts to context.mode: full → titles + descriptions grouped by type; search → catalog (slug + title + 1-line description, fetch bodies via axme_get_memory). Call at session start alongside axme_oracle and axme_decisions.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
page: z.number().optional().describe("Page number (1-based). Omit for first page. Follow pagination instructions if output is split."),
},
async ({ project_path, page }) => {
const resolved = pp(project_path);
deliveredContext.add("memories:" + resolved);
const config = readConfig(resolved);
const wsAlreadyDelivered = isWorkspace && defaultWorkspacePath && resolved !== defaultWorkspacePath
&& deliveredContext.has("memories:" + defaultWorkspacePath);
const isRepoCall = isWorkspace && defaultWorkspacePath && resolved !== defaultWorkspacePath;
const wsForMerge = isRepoCall && !wsAlreadyDelivered ? defaultWorkspacePath : undefined;
let sections: string[];
if (config.contextMode === "search") {
// Search mode: catalog only — bodies fetched on demand by the agent.
sections = [buildMemoriesCatalogString(resolved, wsForMerge ?? undefined)];
if (wsAlreadyDelivered) sections.push("*(Workspace memories already loaded)*");
const result = paginateSections(sections, page ?? 1, "axme_memories", { project_path });
return { content: [{ type: "text" as const, text: result.text }] };
}
// Full mode: existing behaviour (titles + descriptions grouped by type, with workspace merge).
if (wsAlreadyDelivered) {
sections = getMemorySections(resolved);
if (sections.length === 0) sections = ["No repo-specific memories."];
sections.push("*(Workspace memories already loaded)*");
} else if (wsForMerge) {
const { listMemories } = await import("./storage/memory.js");
const { mergeMemories } = await import("./storage/workspace-merge.js");
const wsMemories = listMemories(wsForMerge);
const projMemories = listMemories(resolved);
const merged = mergeMemories(wsMemories, projMemories);
if (merged.length === 0) {
return { content: [{ type: "text" as const, text: "No memories recorded." }] };
}
const feedbacks = merged.filter(m => m.type === "feedback");
const patterns = merged.filter(m => m.type === "pattern");
sections = ["## Project Memories (workspace + repo merged)"];
if (feedbacks.length > 0) {
sections.push(`### Feedback (${feedbacks.length}):\n` +
feedbacks.map(m => `- **${m.title}**: ${m.description}`).join("\n"));
}
if (patterns.length > 0) {
sections.push(`### Patterns (${patterns.length}):\n` +
patterns.map(m => `- **${m.title}**: ${m.description}`).join("\n"));
}
} else {
sections = getMemorySections(resolved);
if (sections.length === 0) {
return { content: [{ type: "text" as const, text: "No memories recorded." }] };
}
sections = ["## Project Memories", ...sections];
}
const result = paginateSections(sections, page ?? 1, "axme_memories", { project_path });
return { content: [{ type: "text" as const, text: result.text }] };
},
);
// --- axme_save_memory ---
server.tool(
"axme_save_memory",
"Save a feedback or pattern memory. Use 'feedback' for learned mistakes, 'pattern' for successful approaches.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
type: z.enum(["feedback", "pattern"]).describe("Memory type"),
title: z.string().describe("Short title"),
description: z.string().describe("1-2 sentences: what happened + specific action/command/rule. Must be self-contained without body."),
body: z.string().optional().describe("Optional archive detail. Context output uses description only, so put all essential info there."),
keywords: z.array(z.string()).optional().describe("Search keywords"),
scope: z.array(z.string()).optional().describe("Project scope (omit for current project only)"),
},
async ({ project_path, type, title, description, body, keywords, scope }) => {
const sid = getOwnedSessionIdForLogging();
const resolved = ppWithScope(project_path, scope);
const result = saveMemoryTool(resolved, { type, title, description, body, keywords, scope }, sid);
// First save lands here for cooperative-flow projects → seed the
// oracle with a deterministic stack/structure snapshot so axme_oracle
// never returns the "Oracle is empty" placeholder. No-op if oracle
// already has content.
const { ensureOracleBootstrapped } = await import("./storage/oracle.js");
ensureOracleBootstrapped(resolved);
// Update the embeddings index when search mode is on. Awaited so the
// index is consistent on return; ~50-200ms once the embedder is warm.
// Skips silently in full mode and on missing runtime.
await embedKbEntry(resolved, result.slug, "memory", title, description, readConfig(resolved).contextMode);
return { content: [{ type: "text" as const, text: `Memory saved: ${result.slug} (${type}) -> ${resolved}` }] };
},
);
// --- axme_save_decision ---
server.tool(
"axme_save_decision",
"Save a new architectural decision. Use enforce='required' for rules that must be followed, 'advisory' for recommendations.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
title: z.string().describe("Decision title"),
decision: z.string().describe("2-3 sentences: what was decided + why. Must be self-contained."),
reasoning: z.string().describe("Optional additional context. Context output uses decision field only."),
enforce: z.enum(["required", "advisory"]).optional().describe("Enforcement level"),
scope: z.array(z.string()).optional().describe("Project scope"),
},
async ({ project_path, title, decision, reasoning, enforce, scope }) => {
const resolved = ppWithScope(project_path, scope);
const result = saveDecisionTool(resolved, { title, decision, reasoning, enforce, scope });
// See axme_save_memory above — same bootstrap reasoning.
const { ensureOracleBootstrapped } = await import("./storage/oracle.js");
ensureOracleBootstrapped(resolved);
// Use decision text as description so the search index returns hits
// ranked by the actual rule, not just the title.
await embedKbEntry(resolved, result.id, "decision", title, decision, readConfig(resolved).contextMode);
return { content: [{ type: "text" as const, text: `Decision saved: ${result.id} - ${title} -> ${resolved}` }] };
},
);
// --- axme_update_safety ---
server.tool(
"axme_update_safety",
"Add or update a safety rule. Types: git_protected_branch, bash_deny, bash_allow, fs_deny, fs_readonly.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
rule_type: z.enum(["git_protected_branch", "bash_deny", "bash_allow", "fs_deny", "fs_readonly"]).describe("Type of safety rule"),
value: z.string().describe("Rule value (branch name, command prefix, or file path pattern)"),
},
async ({ project_path, rule_type, value }) => {
const sid = getOwnedSessionIdForLogging();
const result = updateSafetyTool(pp(project_path), rule_type, value, sid ?? undefined);
return { content: [{ type: "text" as const, text: `Safety rule added: ${result.ruleType} = ${result.value}` }] };
},
);
// --- axme_safety ---
server.tool(
"axme_safety",
"Show current safety rules (git, bash, filesystem restrictions).",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
},
async ({ project_path }) => {
return { content: [{ type: "text" as const, text: showSafetyTool(pp(project_path)) }] };
},
);
// --- axme_save_oracle ---
// Cooperative-flow companion to axme_oracle. Lets the agent write oracle
// sections inline during chat — the API-key path's LLM scanner is great
// for first-time setup but uses a separate billing channel; cooperative
// users do everything on their Cursor subscription, and oracle was the
// only KB area they couldn't reach. The agent fills `stack` / `structure`
// / `patterns` / `glossary` one section at a time, just like decisions
// or memories.
server.tool(
"axme_save_oracle",
"Write or append to one oracle section. Use during cooperative setup to populate stack / structure / patterns / glossary inline. Replaces by default; pass mode='append' to add to existing content.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
section: z.enum(["stack", "structure", "patterns", "glossary"]).describe("Which oracle section to write"),
content: z.string().describe("Markdown body for this section"),
mode: z.enum(["replace", "append"]).optional().describe("Default 'replace'. 'append' adds to existing content."),
},
async ({ project_path, section, content, mode }) => {
const { saveOracleSection } = await import("./storage/oracle.js");
const resolved = pp(project_path);
saveOracleSection(resolved, section, content, mode ?? "replace");
return { content: [{ type: "text" as const, text: `Oracle ${section} ${mode === "append" ? "appended" : "saved"}.` }] };
},
);
// --- axme_get_memory ---
server.tool(
"axme_get_memory",
"Fetch the full body of one memory by slug. Use after seeing the slug in axme_context (search mode catalog) or axme_search_kb results.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
slug: z.string().describe("Memory slug, e.g. 'always-call-axme-context-first'"),
},
async ({ project_path, slug }) => {
return { content: [{ type: "text" as const, text: getMemoryTool(pp(project_path), slug) }] };
},
);
// --- axme_get_decision ---
server.tool(
"axme_get_decision",
"Fetch the full body of one decision by ID (e.g. 'D-110') or slug. Use after seeing it in axme_context (search mode catalog) or axme_search_kb results.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
id_or_slug: z.string().describe("Decision ID like 'D-110' or its slug"),
},
async ({ project_path, id_or_slug }) => {
return { content: [{ type: "text" as const, text: getDecisionTool(pp(project_path), id_or_slug) }] };
},
);
// --- axme_search_kb ---
server.tool(
"axme_search_kb",
"Semantic search across memories and decisions. Useful for fuzzy lookups mid-session ('how did we handle X?'). Requires the embeddings runtime — install with `axme-code config set context.mode search`.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
query: z.string().describe("Search query in natural language"),
k: z.number().int().min(1).max(50).optional().describe("Top K results to return (default 5, max 50)"),
type: z.enum(["memory", "decision"]).optional().describe("Filter results to one type. Omit to search both."),
},
async ({ project_path, query, k, type }) => {
const text = await searchKbTool(pp(project_path), { query, k, type });
return { content: [{ type: "text" as const, text }] };
},
);
// --- axme_backlog ---
server.tool(
"axme_backlog",
"List or read backlog items. Persistent cross-session task tracking.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
status: z.enum(["open", "in-progress", "done", "blocked"]).optional().describe("Filter by status. Omit to show all."),
id: z.string().optional().describe("Get a specific item by ID (e.g. B-001) or slug."),
},
async ({ project_path, status, id }) => {
const { showBacklog, getBacklogItem } = await import("./storage/backlog.js");
const resolved = pp(project_path);
if (id) {
const item = getBacklogItem(resolved, id);
if (!item) return { content: [{ type: "text" as const, text: `Backlog item "${id}" not found.` }] };
const tags = item.tags.length > 0 ? `\nTags: ${item.tags.join(", ")}` : "";
const scope = item.scope?.length ? `\nScope: ${item.scope.join(", ")}` : "";
const notes = item.notes ? `\n\n## Notes\n${item.notes}` : "";
return { content: [{ type: "text" as const, text: `# ${item.id}: ${item.title}\n\nStatus: ${item.status} | Priority: ${item.priority} | Created: ${item.created} | Updated: ${item.updated}${tags}${scope}\n\n${item.description}${notes}` }] };
}
return { content: [{ type: "text" as const, text: showBacklog(resolved, status as any) }] };
},
);
// --- axme_backlog_add ---
server.tool(
"axme_backlog_add",
"Add a new backlog item. Use for tasks, features, bugs that should persist across sessions.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
title: z.string().describe("Short title for the backlog item"),
description: z.string().describe("Detailed description of the task/feature/bug"),
priority: z.enum(["high", "medium", "low"]).optional().describe("Priority level (default: medium)"),
tags: z.array(z.string()).optional().describe("Tags for categorization"),
scope: z.array(z.string()).optional().describe("Project scope (e.g. [\"all\"] for workspace, [\"repo-name\"] for specific repo)"),
},
async ({ project_path, title, description, priority, tags, scope }) => {
const { addBacklogItem } = await import("./storage/backlog.js");
const resolved = ppWithScope(project_path, scope);
const item = addBacklogItem(resolved, { title, description, priority: priority as any, tags, scope });
return { content: [{ type: "text" as const, text: `Backlog item created: ${item.id} - ${item.title} (${item.priority})` }] };
},
);
// --- axme_backlog_update ---
server.tool(
"axme_backlog_update",
"Update a backlog item status, priority, or add notes.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
id: z.string().describe("Item ID (e.g. B-001) or slug"),
status: z.enum(["open", "in-progress", "done", "blocked"]).optional().describe("New status"),
priority: z.enum(["high", "medium", "low"]).optional().describe("New priority"),
notes: z.string().optional().describe("Additional notes to append"),
},
async ({ project_path, id, status, priority, notes }) => {
const { updateBacklogItem } = await import("./storage/backlog.js");
const item = updateBacklogItem(pp(project_path), id, { status: status as any, priority: priority as any, notes });
if (!item) return { content: [{ type: "text" as const, text: `Backlog item "${id}" not found.` }] };
return { content: [{ type: "text" as const, text: `Updated ${item.id}: ${item.title} -> ${item.status} (${item.priority})` }] };
},
);
// --- axme_status ---
server.tool(
"axme_status",
"Show project status: oracle, decisions, memories, sessions, last activity.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
},
async ({ project_path }) => {
return { content: [{ type: "text" as const, text: statusTool(pp(project_path)) }] };
},
);
// --- axme_worklog ---
server.tool(
"axme_worklog",
"Show recent worklog events (session starts, check results, memory saves, errors).",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
limit: z.number().optional().describe("Max events to show (default: 20)"),
},
async ({ project_path, limit }) => {
return { content: [{ type: "text" as const, text: worklogTool(pp(project_path), limit) }] };
},
);
// --- axme_workspace ---
server.tool(
"axme_workspace",
"Detect workspace type and list all projects.",
{
path: z.string().optional().describe("Absolute path to check (defaults to server cwd)"),
},
async ({ path }) => {
const ws = detectWorkspace(path || serverCwd);
if (ws.type === "single") {
return { content: [{ type: "text" as const, text: `Single project (not a workspace): ${ws.root}` }] };
}
const lines = [
`Workspace: ${ws.type}`,
`Root: ${ws.root}`,
ws.manifestPath ? `Manifest: ${ws.manifestPath}` : null,
`Projects (${ws.projects.length}):`,
...ws.projects.map(p => ` - ${p.name} (${p.path})`),
].filter(Boolean);
return { content: [{ type: "text" as const, text: lines.join("\n") }] };
},
);
// --- axme_ask_question ---
server.tool(
"axme_ask_question",
"Record a question that ONLY the user can answer - architectural choices, product decisions, ambiguous requirements. NOT for bugs, TODOs, tasks, or findings - those belong in the conversation or TODO list. Example: 'Should we support backwards compatibility with v1 API?' Anti-example: 'There is a bug in extractBashWritePaths' (that is a bug, not a question for the user).",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
question: z.string().describe("The question text"),
context: z.string().optional().describe("Related decision IDs, file paths, or other context"),
},
async ({ project_path, question, context }) => {
const { askQuestion } = await import("./storage/questions.js");
const sid = getOwnedSessionIdForLogging();
const q = askQuestion(pp(project_path), {
question,
context,
source: sid ? `session-${sid.slice(0, 8)}` : "manual",
});
return { content: [{ type: "text" as const, text: `Question recorded: ${q.id} [open]` }] };
},
);
// --- axme_list_open_questions ---
server.tool(
"axme_list_open_questions",
"List open questions that need user answers. Show at session start if any exist.",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
},
async ({ project_path }) => {
const { listQuestions } = await import("./storage/questions.js");
const open = listQuestions(pp(project_path), { status: "open" });
if (open.length === 0) return { content: [{ type: "text" as const, text: "No open questions." }] };
const lines = open.map(q => `- **${q.id}**: ${q.question}${q.context ? ` (${q.context})` : ""}`);
return { content: [{ type: "text" as const, text: `Open questions (${open.length}):\n\n${lines.join("\n")}` }] };
},
);
// --- axme_answer_question ---
server.tool(
"axme_answer_question",
"Record the user's answer to an open question. Changes status from [open] to [answered].",
{
project_path: z.string().optional().describe("Absolute path to the project root (defaults to server cwd)"),
question_id: z.string().describe("Question ID (e.g. Q-001)"),
answer: z.string().describe("The user's answer"),
},
async ({ project_path, question_id, answer }) => {
const { answerQuestion } = await import("./storage/questions.js");
const q = answerQuestion(pp(project_path), question_id, answer);
if (!q) return { content: [{ type: "text" as const, text: `Question ${question_id} not found or not open.` }] };
return { content: [{ type: "text" as const, text: `Answer recorded for ${q.id}. Status: [answered]` }] };
},
);
// --- axme_begin_close ---
server.tool(
"axme_begin_close",
"Start session close process. Call when user says 'close session' / 'end session' / '\u0437\u0430\u043A\u0440\u044B\u0432\u0430\u0439 \u0441\u0435\u0441\u0441\u0438\u044E'. Returns extraction checklist. Follow it, then call axme_finalize_close with everything.",
{},
async () => {
const sid = getOwnedSessionIdForLogging();
if (!sid) {
return { content: [{ type: "text" as const, text: "No active AXME session found." }] };
}
const checklist = [
`# Session Close Checklist (session ${sid.slice(0, 8)})`,
"",
"## Step 1: Extract Knowledge",
"",
"Review your ENTIRE session for knowledge worth preserving.",
"Save items the user explicitly confirmed. For uncertain items, ask the user before saving.",
"",
"### Scope rules:",
"- Workspace-wide (git safety, deploy procedures, auth model, cross-repo conventions) -> `scope: [\"all\"]`",
"- Repo-specific (test patterns, build config, API design for one service) -> omit scope or `scope: [\"<repo-name>\"]`",
"- If you worked in multiple repos: split items by repo, each gets the scope where it applies",
"",
"### What to extract:",
"- **Memories** (feedback from user corrections, validated patterns)",
"- **Decisions** (policies user confirmed, architectural choices)",
"- **Safety rules** (user mandated bash_deny, fs_deny, git_protected_branch, etc.)",
"",
"### Dedup & conflict check (MANDATORY for each item):",
"Compare every candidate against what you already loaded via `axme_context`.",
"If writing to a repo you haven't loaded yet, call `axme_context` for it first.",
"You already have the full list of memories, decisions, and safety rules in context.",
"",
"**Exact duplicate** (same concept, different wording): skip, do NOT add.",
"**Same topic, updated info**: action `supersede` with the old slug/id.",
"**Direct contradiction**: action `supersede` on the older item (newer is authoritative).",
"**Unclear contradiction**: ask the user which to keep before adding.",
"**Outdated item found** (even unrelated to new ones): action `remove` with its slug/id.",
"",
"## Step 2: Prepare Everything for `axme_finalize_close`",
"",
"Collect ALL data into a single `axme_finalize_close` call.",
"",
"### Extractions (arrays, can be empty):",
"- `memories`: [{action, type, title, description, body, keywords, scope}]",
" - action: `add` | `remove` (slug required) | `supersede` (slug required + new data)",
"- `decisions`: [{action, title, decision, reasoning, enforce, scope}]",
" - action: `add` | `remove` (id required) | `supersede` (id required + new data)",
"- `safety_rules`: [{action, rule_type, value}]",
" - action: `add` | `remove`",
"",
"### Handoff — six REQUIRED string fields. ALL must be present and non-empty.",
"If a session legitimately has nothing to report for one of them, pass an explicit placeholder string (examples below) — do NOT omit the field. Omitting yields per-field 'Expected string, received undefined' errors from Zod.",
"",
"- **`stopped_at`** (REQUIRED, single line) — where the session stopped, e.g. `\"finalized PR #207 review\"`",
"- **`summary`** (REQUIRED) — 2-5 bullet points of accomplishments. Empty placeholder: `\"- (no items)\"`",
"- **`in_progress`** (REQUIRED) — branches, PRs, uncommitted work. Empty placeholder: `\"(nothing in progress)\"`",
"- **`next_steps`** (REQUIRED) — concrete next steps. Empty placeholder: `\"(none — work is complete)\"`",
"- **`worklog_entry`** (REQUIRED) — 5-15 line narrative markdown summary of the session",
"- **`startup_text`** (REQUIRED) — ready-to-paste startup text for the next session",
"",
"### Handoff — optional fields (omit if not applicable):",
"- `prs`: [{url, title, status}]",
"- `test_results`, `blockers`, `dirty_branches`",
"",
"## Step 3: Call `axme_finalize_close`",
"",
"Pass everything in one call. MCP writes all files atomically.",
"After it returns:",
"1. Verify handoff.md was written: `ls .axme-code/plans/handoff.md`",
"2. Output to the user: storage summary, then startup_text.",
];
return { content: [{ type: "text" as const, text: checklist.join("\n") }] };
},
);
// --- axme_finalize_close ---
server.tool(
"axme_finalize_close",
"Finalize session close: saves extractions, writes handoff + worklog, sets agentClosed flag. Call with ALL data after completing the checklist from axme_begin_close.",
{
// --- Extractions ---
memories: z.array(z.object({
action: z.enum(["add", "remove", "supersede"]),
slug: z.string().optional().describe("Required for remove/supersede: slug of existing memory"),
type: z.enum(["feedback", "pattern"]).optional().describe("Required for add/supersede"),
title: z.string().optional().describe("Required for add/supersede"),
description: z.string().optional().describe("Required for add/supersede"),
body: z.string().optional(),
keywords: z.array(z.string()).optional(),
scope: z.array(z.string()).optional(),
})).optional().describe("Memories to add/remove/supersede"),
decisions: z.array(z.object({
action: z.enum(["add", "remove", "supersede"]),
id: z.string().optional().describe("Required for remove/supersede: decision ID (e.g. D-042)"),
title: z.string().optional().describe("Required for add/supersede"),
decision: z.string().optional().describe("Required for add/supersede"),
reasoning: z.string().optional().describe("Required for add/supersede"),
enforce: z.enum(["required", "advisory"]).optional(),
scope: z.array(z.string()).optional(),
})).optional().describe("Decisions to add/remove/supersede"),
safety_rules: z.array(z.object({
action: z.enum(["add", "remove"]),
rule_type: z.enum(["git_protected_branch", "bash_deny", "bash_allow", "fs_deny", "fs_readonly"]),
value: z.string(),
})).optional().describe("Safety rules to add/remove"),
// --- Handoff ---
// All six strings below are REQUIRED. If a session legitimately has
// nothing to report for one, pass an explicit placeholder like
// "(nothing in progress)" — do NOT omit the field. Omitting yields a
// Zod "Expected string, received undefined" error per missing field,
// which has historically been mis-read by agents as a per-field server
// bug rather than a missing-argument error.
stopped_at: z.string().min(1, "stopped_at is REQUIRED — pass a single-line description of where the session stopped, e.g. 'finalized PR #207 review'.").describe("[REQUIRED] What the session stopped at (single line)"),
summary: z.string().min(1, "summary is REQUIRED — pass 2-5 bullet points of accomplishments separated by real newlines, or '- (no items)' if truly empty.").describe("[REQUIRED] 2-5 bullet points of what was accomplished. Use real newlines, NOT literal backslash-n. Each bullet on its own line starting with '- '."),
in_progress: z.string().min(1, "in_progress is REQUIRED — pass branches / PRs / uncommitted work, or '(nothing in progress)' if the working tree is clean. Do not omit the field.").describe("[REQUIRED] Current state: branches, PRs, uncommitted work. Use real newlines, NOT literal backslash-n. Pass '(nothing in progress)' if clean."),
prs: z.array(z.object({
url: z.string(),
title: z.string(),
status: z.string(),
})).optional().describe("[optional] PRs created/merged in this session"),
test_results: z.string().optional().describe("[optional] Test run summary"),
blockers: z.string().optional().describe("[optional] Blockers for next session"),
next_steps: z.string().min(1, "next_steps is REQUIRED — pass concrete next steps for the next session, or '(none — work is complete)' if there are none. Do not omit the field.").describe("[REQUIRED] Concrete next steps for next session. Use real newlines, NOT literal backslash-n. Pass '(none — work is complete)' if there are none."),
dirty_branches: z.string().optional().describe("[optional] Branch names with state"),
worklog_entry: z.string().min(1, "worklog_entry is REQUIRED — pass a 5-15 line narrative summary of the session in markdown. Do not omit the field.").describe("[REQUIRED] Narrative session summary (5-15 lines markdown). Use real newlines, NOT literal backslash-n."),
startup_text: z.string().min(1, "startup_text is REQUIRED — pass ready-to-paste text the user will hand to the next session. Do not omit the field.").describe("[REQUIRED] Ready-to-paste startup text for the next session"),
},
async (args) => {
const sid = getOwnedSessionIdForLogging();
if (!sid) {
return { content: [{ type: "text" as const, text: "No active AXME session found." }] };
}
const targetPath = defaultProjectPath;
const report: string[] = [];
// 1. Process extractions