-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.ts
More file actions
4260 lines (4061 loc) · 219 KB
/
Copy pathserver.ts
File metadata and controls
4260 lines (4061 loc) · 219 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
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
type Tool,
} from "@modelcontextprotocol/sdk/types.js";
import { cwd } from "node:process";
import { DatabaseSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { Config } from "./config.js";
import { runInSandbox, runFileInSandbox } from "./sandbox.js";
import { indexContent, searchKnowledge, searchAllProjects, getKbStats, explainRetrieval } from "./knowledge.js";
import { fetchAndConvert } from "./fetcher.js";
import { getRecentEvents } from "./session.js";
import {
rememberFact,
forgetFact,
recallWorkingMemory,
archiveSessionSummary,
formatWorkingMemoryForContext,
getMemoryStats,
broadcastFact,
recallSharedChannel,
replayBroadcasts,
ackBroadcast,
getBroadcastChainStatus,
setChannelKey,
isChannelKeyConfigured,
formatSharedChannelForContext,
computeProjectComplexity,
type BroadcastType,
type ComplexityProfile,
} from "./memory.js";
import {
issueToken,
revokeAllAgentTokens,
countActiveSessions,
type AgentRole,
} from "./access-control.js";
import { checkIntegrity, type IntegrityResult } from "./integrity.js";
import { getCurrentSchemaVersion } from "./migrations.js";
// Sprint 1 Phase B: telemetry interception
import { recordToolCall, newCallId, formatCostHeader } from "./telemetry.js";
import { computeCost } from "./pricing.js";
import { logger, newTraceId } from "./logger.js";
import { randomUUID } from "node:crypto";
import {
indexProject,
getFileSummary,
getProjectCard,
setProjectCard,
captureToolOutput,
checkAnswer,
getSystemHealth,
formatHealthBanner,
type ProjectCard,
} from "./harness.js";
import { ACTIVE_MODEL, checkOllamaAvailable } from "./embedder.js";
const PROJECT_PATH = process.env["ZC_PROJECT_PATH"] || cwd();
// ─── HTTP client mode ─────────────────────────────────────────────────────────
// When ZC_API_URL is set, all tool calls are proxied to the SecureContext API
// server instead of accessing SQLite directly. The tool schemas are identical —
// agents never know whether they are talking to a local DB or a remote server.
//
// Usage:
// ZC_API_URL=http://sc-api:3099 ZC_API_KEY=<key> node dist/server.js
//
// Authentication: every HTTP request carries "Authorization: Bearer <ZC_API_KEY>"
// ─────────────────────────────────────────────────────────────────────────────
const ZC_API_URL = process.env["ZC_API_URL"]?.replace(/\/$/, ""); // strip trailing slash
const ZC_API_KEY = process.env["ZC_API_KEY"];
/**
* Proxy a tool call to the remote API server.
* Returns the parsed JSON response body.
* Throws on HTTP error or network failure.
*/
async function apiCall(
method: "GET" | "POST" | "DELETE",
path: string,
body?: Record<string, unknown>
): Promise<Record<string, unknown>> {
const url = `${ZC_API_URL}${path}`;
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (ZC_API_KEY) headers["Authorization"] = `Bearer ${ZC_API_KEY}`;
const res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const json = await res.json() as Record<string, unknown>;
if (!res.ok) {
throw new Error(String(json["error"] ?? `API error ${res.status}`));
}
return json;
}
// ─── Startup integrity check ─────────────────────────────────────────────────
const integrity: IntegrityResult = checkIntegrity(Config.VERSION);
if (integrity.firstRun) {
process.stderr.write(`[zc-ctx] Integrity baseline established for v${Config.VERSION}\n`);
} else if (!integrity.ok) {
for (const w of integrity.warnings) {
process.stderr.write(`[zc-ctx] ⚠️ INTEGRITY WARNING: ${w}\n`);
}
// STRICT MODE: refuse to start if tampered (ZC_STRICT_INTEGRITY=1)
if (integrity.strictMode) {
process.stderr.write(
`[zc-ctx] STRICT MODE: integrity failure is fatal. ` +
`Run: rm ~/.claude/zc-ctx/integrity.json to re-baseline after a legitimate update.\n`
);
process.exit(1);
}
}
// ─── Persistent fetch rate limiting ──────────────────────────────────────────
// Per-project, per-day counter stored in SQLite global.db.
// Resets at UTC midnight each day. More meaningful than per-session limits.
function openGlobalDb(): DatabaseSync {
mkdirSync(Config.GLOBAL_DIR, { recursive: true });
const db = new DatabaseSync(join(Config.GLOBAL_DIR, "global.db"));
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA busy_timeout = 5000");
db.exec(`
CREATE TABLE IF NOT EXISTS rate_limits (
project_hash TEXT NOT NULL,
date TEXT NOT NULL,
fetch_count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (project_hash, date)
);
`);
return db;
}
function checkAndIncrementFetchLimit(projectPath: string): { remaining: number } {
const db = openGlobalDb();
const projectHash = createHash("sha256").update(projectPath).digest("hex").slice(0, 16);
const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
type Row = { fetch_count: number };
const row = db.prepare(
"SELECT fetch_count FROM rate_limits WHERE project_hash = ? AND date = ?"
).get(projectHash, today) as Row | undefined;
const currentCount = row?.fetch_count ?? 0;
if (currentCount >= Config.FETCH_LIMIT) {
db.close();
throw new Error(
`Daily fetch limit reached: ${Config.FETCH_LIMIT} fetches/day per project. ` +
`Resets at UTC midnight. Use zc_index to manually add content instead.`
);
}
db.prepare(`
INSERT INTO rate_limits(project_hash, date, fetch_count) VALUES (?, ?, 1)
ON CONFLICT(project_hash, date) DO UPDATE SET fetch_count = fetch_count + 1
`).run(projectHash, today);
db.close();
return { remaining: Config.FETCH_LIMIT - currentCount - 1 };
}
// ─── Tool definitions ─────────────────────────────────────────────────────────
const TOOLS: Tool[] = [
{
name: "zc_execute",
description:
"Run code in a secure isolated sandbox. Code is delivered via stdin (not visible in process list). " +
"No credentials in the sandbox environment — only PATH. " +
"Hard limits: 30s timeout, 512KB stdout cap, 64KB stderr cap. " +
"Supported languages: python, javascript, bash.",
inputSchema: {
type: "object",
properties: {
language: { type: "string", enum: ["python", "python3", "javascript", "js", "bash", "sh"] },
code: { type: "string", description: "Code to execute" },
},
required: ["language", "code"],
},
},
{
name: "zc_execute_file",
description:
"Run analysis code against a specific file in the sandbox. " +
"TARGET_FILE variable is injected via stdin (not visible in process list — Gap 8 fix).",
inputSchema: {
type: "object",
properties: {
path: { type: "string" },
language: { type: "string", enum: ["python", "python3"] },
code: { type: "string", description: "Analysis code using TARGET_FILE variable" },
},
required: ["path", "language", "code"],
},
},
{
name: "zc_fetch",
description:
"Fetch a public URL, convert to markdown, and index into the knowledge base. " +
"Private IPs, localhost, and cloud metadata endpoints are blocked. " +
"DNS resolution checked to prevent rebinding attacks. " +
"Rate limited to 50 fetches/day per project (persistent, resets at UTC midnight).",
inputSchema: {
type: "object",
properties: {
url: { type: "string", description: "Public URL to fetch (http/https only)" },
source: { type: "string", description: "Optional label for this KB entry" },
},
required: ["url"],
},
},
{
name: "zc_index",
description: "Manually index text into the session knowledge base for later hybrid search.",
inputSchema: {
type: "object",
properties: {
content: { type: "string" },
source: { type: "string", description: "Label for this content entry" },
},
required: ["content", "source"],
},
},
{
name: "zc_search",
description:
"Hybrid BM25 + semantic vector search across the knowledge base. " +
"If Ollama (nomic-embed-text) is running locally, cosine similarity reranking is applied. " +
"Falls back to pure BM25 if Ollama is unavailable. " +
"Pass multiple queries to search several topics at once. " +
"v0.20.0 — optional advanced modes: " +
"{ rerank: true } adds cross-encoder reranking for precision, " +
"{ mode: 'hyde' } generates a hypothetical answer first then searches by it (10-25% precision lift on long-tail queries), " +
"{ mode: 'multihop', hopDepth: 2 } follows file/URL references in initial results.",
inputSchema: {
type: "object",
properties: {
queries: { type: "array", items: { type: "string" }, minItems: 1 },
rerank: { type: "boolean", description: "v0.20.0 — apply reranker for precision (slower)" },
mode: { type: "string", enum: ["default", "hyde", "multihop", "global"], description: "v0.20.0 — retrieval strategy. v0.37.0: 'global' answers CORPUS-LEVEL questions ('what are the main themes / what does this project know about X overall?') by map-reducing over pre-computed knowledge-cluster summaries, and returns drill-down follow-up queries." },
hopDepth: { type: "integer", minimum: 1, maximum: 3, description: "v0.20.0 — for mode=multihop, how many reference hops to follow (default 2)" },
},
required: ["queries"],
},
},
{
name: "zc_search_global",
description:
"Search across ALL projects in your SecureContext knowledge base (cross-project federated search). " +
"Use when looking for patterns, decisions, or notes you remember from a different project. " +
"Searches the N most recently active projects. External content trust warnings still apply.",
inputSchema: {
type: "object",
properties: {
queries: { type: "array", items: { type: "string" }, minItems: 1, description: "Search terms (up to 5)" },
max_projects: { type: "integer", minimum: 1, maximum: 10, default: 5, description: "Max projects to search (most recently active first)" },
},
required: ["queries"],
},
},
{
name: "zc_batch",
description:
"Execute shell commands in sandbox AND search the knowledge base in one parallel call. " +
"Ideal for research: run commands while retrieving existing knowledge simultaneously.",
inputSchema: {
type: "object",
properties: {
commands: {
type: "array",
items: {
type: "object",
properties: {
label: { type: "string" },
command: { type: "string" },
},
required: ["label", "command"],
},
},
queries: { type: "array", items: { type: "string" } },
},
required: ["commands", "queries"],
},
},
{
name: "zc_remember",
description:
"Store a key-value fact in working memory (MemGPT-style). " +
"Working memory is bounded (100 facts base, scales up to 250 by project complexity) — lowest-importance facts auto-evict to archival KB. " +
"IMPORTANCE DISCIPLINE (v0.43.0): ★5 is ONLY for facts whose loss breaks future sessions (service names, " +
"irreversible decisions, credentials-locations, breaking gotchas) — a soft quota warns past " +
"25 ★5 facts per namespace. Work-log entries and findings are ★3-4; per-task notes " +
"(ownership markers, task state) should ALSO set ttl_days so they expire when the task is long done. " +
"Use agent_id to namespace facts for parallel agent use. " +
"EPISTEMOLOGY (v0.31.0) — TYPE YOUR CLAIMS: recording a falsifiable claim about the FUTURE? set kind='prediction' + confidence (0–1) + resolution='open', then later re-remember the SAME key with resolution='resolved_correct'/'resolved_incorrect' to close it. Recording a CHOSEN approach? set kind='decision'. A tentative/unverified claim? kind='hypothesis'. Plain observed facts need nothing (kind defaults to 'fact'; the system also auto-classifies from the text). Typed claims power contradiction detection + self-calibration.",
inputSchema: {
type: "object",
properties: {
key: { type: "string", description: "Short identifier (max 100 chars)" },
value: { type: "string", description: "The fact to remember (max 500 chars)" },
importance: { type: "integer", minimum: 1, maximum: 5, description: "1=ephemeral, 3=normal, 5=critical" },
agent_id: { type: "string", description: "Agent namespace for parallel use (default: 'default')" },
kind: { type: "string", enum: ["fact", "decision", "hypothesis", "prediction"], description: "Epistemic kind. fact=observed; decision=chosen approach; hypothesis=tentative; prediction=falsifiable future claim. Default 'fact' (auto-classified from text if omitted)." },
confidence: { type: "number", minimum: 0, maximum: 1, description: "0.0–1.0 subjective probability for predictions/hypotheses. Omit for plain facts." },
resolution: { type: "string", enum: ["open", "resolved_correct", "resolved_incorrect", "resolved_partial"], description: "Set 'open' when recording a prediction; later re-remember the same key with a resolved_* value to close it." },
ttl_days: { type: "number", minimum: 0.01, description: "R1 (v0.42.0) — auto-expire this fact after N days (e.g. 7 for a sprint-scoped note, 0.5 for a same-day reminder). Expired facts leave recall and are retired (revivable for 30 days). Omit for permanent facts." },
},
required: ["key", "value"],
},
},
{
name: "zc_index_file",
description:
"R5 (v0.42.0) — Index a MULTIMODAL file into the knowledge base: PDF (text extracted), " +
"DOCX (text extracted), or image (described by a local Ollama vision model when one is " +
"installed — llava/qwen-vl/minicpm-v/moondream). The extracted text flows through the " +
"normal indexing pipeline: searchable via zc_search, summarized, embedded, graph-linked. " +
"For plain text/code files use zc_index_project or zc_index instead.",
inputSchema: {
type: "object",
properties: {
path: { type: "string", description: "File path (absolute, or relative to the project root). Supported: .pdf, .docx, .png, .jpg, .jpeg, .gif, .webp, .bmp" },
},
required: ["path"],
},
},
{
name: "zc_memory_contradictions",
description:
"List suspected contradictions in working memory — pairs of facts that look like they conflict " +
"(a falsified claim still asserted as live, two disagreeing decisions, or opposite-polarity claims). " +
"Surfaced for review; NEVER auto-applied. Pass run:true to run a fresh scan first (embeds facts; needs Ollama). " +
"Manage a pair with action ('dismiss'|'acknowledge'|'resolve') + key_a + key_b.",
inputSchema: {
type: "object",
properties: {
run: { type: "boolean", description: "Run a fresh scan before listing (default: just list existing)" },
action: { type: "string", enum: ["dismiss", "acknowledge", "resolve"], description: "Mark a specific pair reviewed" },
key_a: { type: "string", description: "First key of the pair (use with action)" },
key_b: { type: "string", description: "Second key of the pair (use with action)" },
agent_id: { type: "string", description: "Agent namespace (default: this agent)" },
},
required: [],
},
},
{
name: "zc_forget",
description:
"Delete a specific key from working memory. " +
"Use to remove stale, incorrect, or sensitive facts. Safe to call even if key doesn't exist.",
inputSchema: {
type: "object",
properties: {
key: { type: "string", description: "Working memory key to delete (max 100 chars)" },
agent_id: { type: "string", description: "Agent namespace (default: 'default')" },
},
required: ["key"],
},
},
{
name: "zc_recall_context",
description:
"Recall working memory and recent session events. " +
"Call this at the start of every session to restore project context. " +
"Returns structured sections: Working Memory · Session Events · System Status. " +
"ALWAYS pass focus:'<one line describing your current task>' when you have one — facts are then " +
"ranked by relevance to YOUR task instead of raw importance (v0.41.0), and time expressions in the " +
"focus ('last week', 'since March') select facts from that window with priority. " +
"v0.43.0: output is BUDGETED — the top-ranked facts render in full and the tail collapses into a " +
"grouped index (nothing is deleted; pull collapsed facts with a narrower focus or zc_search). " +
"The recall output IS already the digest: NEVER spawn a subagent to summarize it — that is slower, " +
"loses exact keys/hashes/numbers, and costs more than reading it directly. If it feels too broad, " +
"re-call with a tighter focus instead. " +
"v0.17.1: repeat calls within 60s by the same agent/project return a cached response " +
"(unchanged if no new memory / broadcasts / events have landed), saving ~$0.06 per cached call. " +
"Pass force:true to bypass the cache.",
inputSchema: {
type: "object",
properties: {
agent_id: { type: "string", description: "Agent namespace (default: 'default')" },
force: { type: "boolean", description: "Skip the recall cache and force a fresh pull (default: false)" },
cite: { type: "boolean", description: "v0.38.0 — append a provenance citation to every fact: 〔agent · date · origin〕 (origin = what created it: zc_remember, compact:<session>, broadcast:REJECT:<task>). Default false (keeps recall lean)." },
focus: { type: "string", description: "v0.41.0 — one line describing your CURRENT task. Re-ranks facts by blended relevance (cosine to focus × importance × salience) so task-relevant facts surface first. Omit for the classic importance ordering." },
},
required: [],
},
},
{
name: "zc_summarize_session",
description:
"Archive a session summary to long-term memory (MemGPT session eviction). " +
"Call when a significant task is complete. Summary is searchable via zc_search. " +
"Kept for 365 days (vs 30 days for regular KB content).",
inputSchema: {
type: "object",
properties: {
summary: {
type: "string",
description: "2–5 sentence summary of what was accomplished, key decisions made, and current state",
},
},
required: ["summary"],
},
},
{
name: "zc_status",
description:
"Show SecureContext health: DB size, KB entry counts, working memory fill, " +
"schema version, embedding model, today's fetch budget, and integrity status. " +
"Call this to diagnose issues or verify the plugin is working correctly.",
inputSchema: {
type: "object",
properties: {
agent_id: { type: "string", description: "Agent namespace for memory stats (default: 'default')" },
},
required: [],
},
},
{
name: "zc_compact_window",
description:
"v0.20.0 — Rolling conversation compaction (Tier A item #4). Pulls the last N broadcasts + " +
"tool_calls in this session, generates a structured summary via local Ollama, stores it as " +
"an importance=4 working memory fact. Call when zc_context_status reports tier=alert (≥85%). " +
"Returns the summary text inline so you can include it in your next reasoning step.",
inputSchema: {
type: "object",
properties: {
turns: { type: "integer", minimum: 5, maximum: 100, description: "How many recent turns to compact (default 30)" },
},
required: [],
},
},
{
name: "zc_context_status",
description:
"v0.20.0 — Return current context-budget state for this MCP session. " +
"Reports: total tokens used, fraction of 200K budget consumed, tier (ok/warn/alert/emergency), " +
"recommended action. Use when you suspect you're approaching context exhaustion. " +
"Every other tool already shows a [ctx: X% / 200K] suffix in its cost header — call this " +
"for the explicit recommendation when you cross a threshold.",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "zc_broadcast",
description:
"Broadcast a coordination message to the shared A2A channel (Agent-to-Agent). " +
"Use for multi-agent orchestration: assign tasks, report status, propose changes, " +
"declare file dependencies, approve/reject/revise proposals. " +
"Shared channel is readable by all agents via zc_recall_context(). " +
"If a channel key is configured (via set_key action), all WRITE operations require it. " +
"READ and STATUS actions never require a key. " +
"Actions: ASSIGN · STATUS · PROPOSED · DEPENDENCY · MERGE · REJECT · REVISE · LAUNCH_ROLE · RETIRE_ROLE · set_key",
inputSchema: {
type: "object",
properties: {
type: {
type: "string",
enum: ["ASSIGN", "STATUS", "PROPOSED", "DEPENDENCY", "MERGE", "REJECT", "REVISE", "LAUNCH_ROLE", "RETIRE_ROLE", "set_key"],
description:
"ASSIGN=orchestrator assigns task | STATUS=report progress | " +
"PROPOSED=propose file changes | DEPENDENCY=declare file deps | " +
"MERGE=approve changes | REJECT=reject changes | REVISE=request revision | " +
"LAUNCH_ROLE=spawn new agent role (orchestrator, via dispatcher) | " +
"RETIRE_ROLE=retire agent role (orchestrator, via dispatcher) | " +
"set_key=configure channel key (orchestrator only)",
},
agent_id: {
type: "string",
description: "Sending agent identifier (e.g. 'orchestrator', 'agent-auth', 'agent-db')",
},
task: {
type: "string",
description: "Task name or description (max 500 chars)",
},
files: {
type: "array",
items: { type: "string" },
description: "File paths affected by this broadcast (max 50 entries)",
},
state: {
type: "string",
description: "Current state: e.g. 'in-progress', 'blocked', 'done'",
},
summary: {
type: "string",
description: "Human-readable summary of work done or decision made (max 1000 chars)",
},
depends_on: {
type: "array",
items: { type: "string" },
description: "agent_ids whose outputs this broadcast depends on",
},
reason: {
type: "string",
description: "Reason for a REJECT or REVISE decision (max 500 chars)",
},
importance: {
type: "integer",
minimum: 1,
maximum: 5,
description: "Priority: 1=low, 3=normal, 5=critical",
},
channel_key: {
type: "string",
description: "Channel capability key — required if key is configured. For set_key action, this IS the new key to set.",
},
session_token: {
type: "string",
description: "Session token from zc_issue_token — required when RBAC sessions are active.",
},
},
required: ["type", "agent_id"],
},
},
{
name: "zc_issue_token",
description:
"Issue a signed RBAC session token for an agent (orchestrator use). " +
"Token grants role-specific broadcast permissions. Valid 24 hours. " +
"Chapter 6 session tokens + Chapter 14 RBAC. Requires channel_key if configured.",
inputSchema: {
type: "object",
properties: {
agent_id: { type: "string", description: "Agent identifier to issue token for" },
role: {
type: "string",
enum: ["orchestrator", "developer", "marketer", "researcher", "worker"],
description: "RBAC role — determines allowed broadcast types",
},
channel_key: { type: "string", description: "Channel key (required if configured)" },
},
required: ["agent_id", "role"],
},
},
{
name: "zc_revoke_token",
description:
"Revoke all session tokens for an agent. Requires channel_key if configured. " +
"Agent will need a new token from zc_issue_token before it can broadcast again.",
inputSchema: {
type: "object",
properties: {
agent_id: { type: "string", description: "Agent whose tokens should be revoked" },
channel_key: { type: "string", description: "Channel key (required if configured)" },
},
required: ["agent_id"],
},
},
{
name: "zc_explain",
description:
"Show retrieval transparency for a search query — BM25 scores, vector scores, merged rank, " +
"and tier loaded for each result. Use to debug why certain content was or wasn't returned.",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query to explain" },
depth: {
type: "string",
enum: ["L0", "L1", "L2"],
description: "Content depth: L0=one-sentence, L1=planning detail, L2=full (default)",
},
},
required: ["query"],
},
},
{
name: "zc_replay",
description:
"Replay broadcast history from a given time. Returns all broadcasts from that point, oldest first. " +
"Use for session post-mortems and context reconstruction.",
inputSchema: {
type: "object",
properties: {
from: { type: "string", description: "ISO timestamp to replay from (optional — all if omitted)" },
limit: { type: "integer", minimum: 1, maximum: 500, description: "Max broadcasts to return (default: 100)" },
},
required: [],
},
},
{
name: "zc_ack",
description:
"Acknowledge receipt of a broadcast. Marks the broadcast as delivered in the audit log. " +
"Call after you have read and acted on an ASSIGN broadcast.",
inputSchema: {
type: "object",
properties: {
broadcast_id: { type: "integer", description: "Broadcast ID to acknowledge" },
agent_id: { type: "string", description: "Acknowledging agent ID" },
session_token: { type: "string", description: "Session token (optional)" },
},
required: ["broadcast_id", "agent_id"],
},
},
// ── v0.10.0 Harness Engineering ─────────────────────────────────────────────
{
name: "zc_index_project",
description:
"Walk the current project and index every source file into the KB with an L0 (first 100-char purpose) + L1 (first 1500-char detail) summary. " +
"Run once per project after initial clone — afterward, agents call zc_file_summary(path) for 'check/review' questions instead of Read. " +
"Idempotent: re-running refreshes summaries for changed files. " +
"Excludes node_modules, dist, build, .git, coverage, .worktrees by default. " +
"This is the foundation of the v0.10.0 harness — Tier 1 (KB) becomes the default, Tier 2 (Read) the exception.",
inputSchema: {
type: "object",
properties: {
excludes: { type: "array", items: { type: "string" }, description: "Path prefixes to skip (overrides default)" },
extensions: { type: "array", items: { type: "string" }, description: "File extensions to index (e.g. '.ts', '.py')" },
max_bytes: { type: "integer", minimum: 1024, description: "Max file size to read in bytes (default 262144)" },
},
required: [],
},
},
{
name: "zc_file_summary",
description:
"Return the L0 (one-line purpose) + L1 (1500-char detail) summary for a single file — no Read required. " +
"The primary Tier-1 verb for check/review questions. ~400 tokens vs ~4000 for a full Read. " +
"Returns stale=true if the file on disk is newer than the indexed version (run zc_index_project to refresh, or the PostEdit hook will do it automatically). " +
"v0.39.0 — pass symbol:'<functionOrClassName>' for L2 PROGRESSIVE DISCLOSURE: returns ONLY that symbol's code slice (the middle rung between the L1 summary and force_full_read — never pay for the whole file when you need one function).",
inputSchema: {
type: "object",
properties: {
path: { type: "string", description: "Path relative to project root (or absolute)" },
symbol: { type: "string", description: "v0.39.0 — L2: return only this function/class/method's code slice instead of the summary" },
},
required: ["path"],
},
},
{
name: "zc_project_card",
description:
"Return (or update) the per-project orientation card: stack + layout + state + gotchas + hot_files. " +
"Call once per session after zc_recall_context to replace the Read-CLAUDE.md / ls / Glob ritual. ~500 tokens vs ~8k. " +
"Pass any of stack/layout/state/gotchas/hot_files to UPDATE the card; omit them to READ it.",
inputSchema: {
type: "object",
properties: {
stack: { type: "string", description: "e.g. 'Node 22 + TypeScript + SQLite + MCP'" },
layout: { type: "string", description: "Top-level dirs with one-line purpose each" },
state: { type: "string", description: "Current work state / sprint / pending" },
gotchas: { type: "string", description: "Known pitfalls and constraints" },
hot_files: { type: "array", items: { type: "string" }, description: "Top-N frequently-edited paths" },
},
required: [],
},
},
{
name: "zc_check",
description:
"Memory-first answer wrapper: searches the KB for the question and returns top hits with a confidence score. " +
"Use this BEFORE reaching for Read/Grep — if the KB answer is high-confidence, skip the file read entirely. " +
"Confidence levels: high (use this), medium (corroborate), low (might miss details), none (Read required).",
inputSchema: {
type: "object",
properties: {
question: { type: "string", description: "Natural-language question" },
path: { type: "string", description: "Optional: scope search to one source file" },
},
required: ["question"],
},
},
{
name: "zc_capture_output",
description:
"Store a long bash/tool output in the KB and return a compact summary (head + tail + omission marker). " +
"Called by the PostToolUse bash hook automatically; callable directly when an agent knows it ran a noisy command. " +
"Full output becomes FTS-searchable via source='tool_output/<hash>'. Dedup by sha256(cmd+stdout).",
inputSchema: {
type: "object",
properties: {
command: { type: "string", description: "The command that was run" },
stdout: { type: "string", description: "Full output" },
exit_code: { type: "integer", description: "Process exit code" },
},
required: ["command", "stdout", "exit_code"],
},
},
{
name: "zc_logs",
description:
"Query structured telemetry logs from the harness (Sprint 1 v0.11.0). " +
"Components: telemetry, outcomes, learnings-mirror, skills, mutations, budget, compaction, " +
"tasks, ownership, routing, retrieval. Returns newest-first. When ZC_AGENT_ID env is set, " +
"results are agent-scoped (only entries matching this agent_id or system entries). " +
"Use this to diagnose cost spikes, trace outcome resolution, or correlate events across " +
"components via trace_id. Logs are ON THE LOCAL DISK — this tool is local-only.",
inputSchema: {
type: "object",
properties: {
component: { type: "string", description: "One of: telemetry, outcomes, learnings-mirror, skills, mutations, budget, compaction, tasks, ownership, routing, retrieval" },
since_date: { type: "string", description: "Inclusive ISO date YYYY-MM-DD (default: today)" },
until_date: { type: "string", description: "Inclusive ISO date YYYY-MM-DD (default: today)" },
min_level: { type: "string", enum: ["DEBUG", "INFO", "WARN", "ERROR"], description: "Minimum severity (default: INFO)" },
event_contains: { type: "string", description: "Substring to match (case-insensitive) against event name" },
trace_id: { type: "string", description: "Exact trace_id match (for cross-log correlation)" },
agent_id: { type: "string", description: "Filter by agent_id (falls back to ZC_AGENT_ID env)" },
limit: { type: "integer", minimum: 1, maximum: 5000, description: "Max rows (default: 200)" },
},
required: ["component"],
},
},
// ── v0.13.0 graphify integration ──────────────────────────────────────
{
name: "zc_graph_query",
description:
"Query the project's structural knowledge graph (built by graphify). " +
"Use for ARCHITECTURAL questions like 'how does auth work' or 'what depends on the user model'. " +
"Returns graph nodes + relationships + confidence tags. " +
"Requires `graphify-out/graph.json` in the project (run `/graphify .` first to build it). " +
"Pairs with zc_search for precise content retrieval — graph orient first, then targeted reads.",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Natural-language graph query (e.g. 'how does auth flow connect to the database')" },
},
required: ["query"],
},
},
{
name: "zc_graph_path",
description:
"Find the shortest path between two named nodes in the structural graph. " +
"Use for 'how does X connect to Y' questions. Returns the chain of nodes + edges. " +
"Requires graphify-out/graph.json (see zc_graph_query for setup).",
inputSchema: {
type: "object",
properties: {
from: { type: "string", description: "Source node name" },
to: { type: "string", description: "Target node name" },
},
required: ["from", "to"],
},
},
{
name: "zc_graph_neighbors",
description:
"Get the immediate neighbors of a named node in the structural graph. " +
"Use for 'what's related to X' questions. Returns directly-connected nodes + their edge types. " +
"Requires graphify-out/graph.json.",
inputSchema: {
type: "object",
properties: {
node: { type: "string", description: "Node name to inspect" },
},
required: ["node"],
},
},
// ── v0.14.0 community detection (Louvain over SC's KB) ────────────────
{
name: "zc_kb_cluster",
description:
"Run Louvain community detection over the project's knowledge base. " +
"Identifies clusters of related sources by graph topology (no embeddings). " +
"For 'what's the architecture of this project' questions, this surfaces higher-order " +
"structure (e.g. 'auth cluster', 'data layer cluster') that pure top-k similarity misses. " +
"Persists results to kb_communities table for fast subsequent lookups via zc_kb_community_for.",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "zc_kb_community_for",
description:
"Look up the community of a single KB source plus its community-mates. " +
"Use for 'what's related to X' questions where X is a known KB source path. " +
"Run zc_kb_cluster first to populate community assignments.",
inputSchema: {
type: "object",
properties: {
source: { type: "string", description: "KB source identifier (e.g. 'file:src/auth.ts')" },
},
required: ["source"],
},
},
// ── v0.31.0 backlink graph (Tier-1 A) ────────────────────────────────
{
name: "zc_graph_backlinks",
description:
"Show the backlink in-degree of a KB source: how many other sources reference it (weighted), " +
"plus the inbound sources + relation types. Highly-referenced 'hub' sources rank higher in " +
"zc_search (backlink boost). Run zc_graph_rebuild or zc_kb_cluster first to populate the graph.",
inputSchema: {
type: "object",
properties: {
source: { type: "string", description: "KB source identifier (e.g. 'file:src/config.ts')" },
limit: { type: "integer", minimum: 1, maximum: 100, description: "Max inbound sources to list (default 20)" },
},
required: ["source"],
},
},
{
name: "zc_graph_rebuild",
description:
"Force a rebuild of the persistent knowledge graph (kb_edges) + backlink in-degree (kb_backlinks) " +
"for this project, mirrored to Postgres. Normally rebuilt automatically (debounced) after indexing; " +
"use this to force it — e.g. before an A/B of backlink ranking, or after a bulk import.",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "zc_choose_model",
description:
"v0.17.0 §8.5 — Recommend a Claude model tier for a task given its complexity_estimate (1-5). " +
"Maps 1-2→Haiku (cheap/trivial), 3-4→Sonnet (standard), 5→Opus (hard reasoning). " +
"Returns model id, tier, rationale, per-Mtok input cost, and whether the input was clamped. " +
"Use before dispatching a task to a worker pool to route by cost-efficiency. " +
"Operators can override via ZC_MODEL_TIER_{HAIKU,SONNET,OPUS} env vars.",
inputSchema: {
type: "object",
properties: {
complexity: {
type: "number",
description: "Task complexity 1-5 (from v0.15.0 §8.1 structured ASSIGN). " +
"Values outside 1-5, NaN, or missing → defaults to Sonnet with inputClamped=true.",
},
},
required: [],
},
},
{
name: "zc_skill_list",
description:
"v0.18.0 Sprint 2 — List all active skills in this project (per-project + global). " +
"Each entry shows name, version, scope, description, and recent run-aggregate score. " +
"Use this as the entry point before zc_skill_show / zc_skill_propose_mutation.",
inputSchema: { type: "object", properties: {}, required: [] },
},
{
name: "zc_skill_show",
description:
"v0.18.0 — Show full skill: frontmatter (acceptance_criteria, fixtures) + body markdown. " +
"Resolves per-project version first, falls back to global. Verifies HMAC at load — " +
"skills with mismatched body_hmac return an error rather than the body.",
inputSchema: {
type: "object",
properties: {
name: { type: "string", description: "Skill name (e.g. 'audit_file')" },
},
required: ["name"],
},
},
{
name: "zc_skill_score",
description:
"v0.18.0 — Compute aggregate score for a skill from its recent skill_runs " +
"(default last 20). Returns avg_score, pass_rate, avg_cost_usd, avg_duration_ms, " +
"and whether the skill currently meets its acceptance_criteria.",
inputSchema: {
type: "object",
properties: {
name: { type: "string", description: "Skill name" },
window: { type: "number", description: "How many recent runs to aggregate (default 20)" },
},
required: ["name"],
},
},
{
name: "zc_skill_run_replay",
description:
"v0.18.0 — Replay a skill against its synthetic fixtures and return per-fixture results " +
"+ aggregate. Useful for inspecting why a candidate would or wouldn't be promoted. " +
"Uses the LocalDeterministicExecutor (no LLM cost) for v0.18.0.",
inputSchema: {
type: "object",
properties: { name: { type: "string", description: "Skill name" } },
required: ["name"],
},
},
{
name: "zc_skill_propose_mutation",
description:
"v0.18.0 — Run ONE on-demand mutation cycle on a skill: invoke the configured mutator " +
"(via ZC_MUTATOR_MODEL — defaults to local-mock), generate 5 candidates, replay each " +
"against fixtures, decide promotion. Records EVERY candidate in skill_mutations regardless " +
"of outcome. Returns the cycle result (baseline, best candidate score, promoted, reason).",
inputSchema: {
type: "object",
properties: { name: { type: "string", description: "Skill name to mutate" } },
required: ["name"],
},
},
{
name: "zc_skill_export",
description:
"v0.18.0 — Export a skill as agentskills.io-format markdown for sharing with the " +
"broader ecosystem. SC-specific metadata (acceptance_criteria, fixtures, scope) is " +
"preserved in the metadata block so a round-trip back through zc_skill_import is lossless.",
inputSchema: {
type: "object",
properties: { name: { type: "string", description: "Skill name to export" } },
required: ["name"],
},
},
{
name: "zc_skill_import",
description:
"v0.18.0 — Import agentskills.io markdown as a new skill. Reconstructs the Skill, " +
"computes a fresh body_hmac (against this machine's secret), and inserts into the " +
"skills table. SC-specific metadata in the source's metadata block is honored.",
inputSchema: {
type: "object",
properties: {
markdown: { type: "string", description: "agentskills.io-format markdown text" },
scope: { type: "string", description: "Default scope when source has none. 'global' or 'project:<hash>'." },
},
required: ["markdown"],
},
},
{
name: "zc_skill_pending_promotions",
description:
"v0.18.1 — List skill promotion candidates awaiting operator review. Each row has " +
"candidate_skill_id (per-project version that beat global by ≥10% in ≥2 projects), " +
"best_avg / global_avg, project_count, surfaced_at/by. Use zc_skill_approve_promotion " +
"or zc_skill_reject_promotion to act on each.",
inputSchema: { type: "object", properties: {}, required: [] },
},
{
name: "zc_skill_approve_promotion",
description:
"v0.18.1 — Approve a pending global-promotion candidate. Atomic: marks the row " +
"approved + exports the candidate's body + imports as global scope. The new global " +
"version supersedes the prior global on next zc_skill_show. Operator-gated; rationale required.",
inputSchema: {
type: "object",
properties: {
candidate_skill_id: { type: "string", description: "The candidate's full skill_id (name@version@scope)" },
rationale: { type: "string", description: "Why this is being approved (audit trail)" },
proposed_target: { type: "string", description: "Target scope. Default 'global'." },
},
required: ["candidate_skill_id", "rationale"],
},
},
{
name: "zc_skill_reject_promotion",
description:
"v0.18.1 — Reject a pending global-promotion candidate. Marks the row rejected with " +
"rationale; row stays in the queue for audit but won't surface in zc_skill_pending_promotions.",
inputSchema: {
type: "object",
properties: {
candidate_skill_id: { type: "string", description: "The candidate's full skill_id" },
rationale: { type: "string", description: "Why this is being rejected" },
proposed_target: { type: "string", description: "Target scope. Default 'global'." },
},
required: ["candidate_skill_id", "rationale"],
},
},
{
name: "zc_record_skill_outcome",
description:
"v0.18.1 — Worker-agent (developer/researcher/etc.) tool: report the outcome of running a skill " +
"against a fixture or task input. Atomically writes a row to skill_runs (telemetry) AND, when " +
"the run failed or scored below threshold, an outcome row with refType='skill_run' (which " +
"triggers the L1 mutation hook if ZC_L1_MUTATION_ENABLED=1). This is the canonical way for " +
"agents to close the feedback loop on a skill — failed runs become learning signal that the " +
"mutator agent can act on autonomously.",
inputSchema: {
type: "object",
properties: {
skill_id: { type: "string", description: "Full skill_id (name@version@scope) of the skill that was run." },
fixture_id: { type: "string", description: "Optional: fixture identifier for traceability (e.g. 'happy', 'edge-case-null')." },
inputs: { type: "object", description: "The actual inputs the skill was run with (becomes the inputs JSON of the skill_run row)." },
status: { type: "string", enum: ["succeeded", "failed", "timeout"], description: "Run status. 'failed' or 'timeout' will trigger the L1 mutation hook." },
outcome_score: { type: "number", description: "Optional 0..1 score. Below 0.5 also triggers the L1 mutation hook even if status='succeeded'." },
failure_trace: { type: "string", description: "Required when status='failed' — short description of what went wrong." },
what_worked: { type: "string", description: "v0.30.8 evidence — 1-2 sentences: which parts of the skill's guidance actually helped on this task. Recommended on every run." },
what_didnt: { type: "string", description: "v0.30.8 evidence — 1-2 sentences: which guidance was wrong, missing, or misleading for this task. REQUIRED when status is failed/timeout or outcome_score < 0.6 — this is the signal the mutator uses to fix the skill." },
recommendation_for_skill: { type: "string", description: "v0.30.8 evidence — one concrete, actionable change to the skill body (e.g. 'add a Windows path example to step 3'). REQUIRED when status is failed/timeout or outcome_score < 0.6." },
duration_ms: { type: "number", description: "Wall-clock duration of the run in ms." },
total_cost: { type: "number", description: "USD cost of the run (default 0)." },
total_tokens: { type: "number", description: "Total tokens consumed in the run (default 0)." },
task_id: { type: "string", description: "Optional: ID of the parent task the skill was running for (links skill_run → task_queue_pg)." },
session_id: { type: "string", description: "Optional: session id (default 'agent-session')." },