@mcoda/mswarm 0.1.135-codali.18 → 0.1.135-codali.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +5 -0
  2. package/dist/runtime.d.ts.map +1 -1
  3. package/dist/runtime.js +5 -2
  4. package/dist/runtime.js.map +1 -1
  5. package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
  6. package/dist/vendor/codali/cli/TerminalCommand.js +53 -20
  7. package/dist/vendor/codali/cli/TerminalInput.d.ts +6 -0
  8. package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -1
  9. package/dist/vendor/codali/cli/TerminalInput.js +3 -1
  10. package/dist/vendor/codali/cli/ToolsCommand.d.ts.map +1 -1
  11. package/dist/vendor/codali/cli/ToolsCommand.js +8 -1
  12. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts +6 -0
  13. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts.map +1 -0
  14. package/dist/vendor/codali/cli/tui/TerminalLogo.js +26 -0
  15. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts +5 -0
  16. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts.map +1 -0
  17. package/dist/vendor/codali/cli/tui/TerminalMarkdown.js +118 -0
  18. package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -1
  19. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +12 -3
  20. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts +1 -0
  21. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts.map +1 -1
  22. package/dist/vendor/codali/cli/tui/TerminalScreen.js +13 -6
  23. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts +15 -0
  24. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts.map +1 -0
  25. package/dist/vendor/codali/cli/tui/TerminalSelection.js +38 -0
  26. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts +4 -0
  27. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -1
  28. package/dist/vendor/codali/cli/tui/TerminalTui.js +96 -12
  29. package/dist/vendor/codali/cli.js +1 -1
  30. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +18 -0
  31. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  32. package/dist/vendor/codali/config/OrchestrationConfig.js +42 -2
  33. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts +12 -0
  34. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts.map +1 -0
  35. package/dist/vendor/codali/docdex/DocdexCatalog.js +30 -0
  36. package/dist/vendor/codali/docdex/DocdexClient.d.ts +8 -2
  37. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  38. package/dist/vendor/codali/docdex/DocdexClient.js +86 -11
  39. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +1 -0
  40. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
  41. package/dist/vendor/codali/docdex/ManagedDocdex.js +25 -4
  42. package/dist/vendor/codali/eval/TrustBenchmark.d.ts +94 -0
  43. package/dist/vendor/codali/eval/TrustBenchmark.d.ts.map +1 -0
  44. package/dist/vendor/codali/eval/TrustBenchmark.js +199 -0
  45. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
  46. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +10 -1
  47. package/dist/vendor/codali/permissions/PermissionGate.d.ts +1 -1
  48. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  49. package/dist/vendor/codali/permissions/PermissionGate.js +40 -2
  50. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts +11 -0
  51. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts.map +1 -0
  52. package/dist/vendor/codali/permissions/WorkspacePermissions.js +42 -0
  53. package/dist/vendor/codali/providers/ModelServiceError.js +1 -1
  54. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  55. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +3 -1
  56. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts +13 -0
  57. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts.map +1 -0
  58. package/dist/vendor/codali/runtime/ComputedAnswer.js +75 -0
  59. package/dist/vendor/codali/runtime/ContextCompression.d.ts +22 -0
  60. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -0
  61. package/dist/vendor/codali/runtime/ContextCompression.js +53 -0
  62. package/dist/vendor/codali/runtime/InspectionBudget.d.ts +8 -0
  63. package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -0
  64. package/dist/vendor/codali/runtime/InspectionBudget.js +25 -0
  65. package/dist/vendor/codali/runtime/InteractionContract.d.ts +42 -0
  66. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -0
  67. package/dist/vendor/codali/runtime/InteractionContract.js +50 -0
  68. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +46 -5
  69. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
  70. package/dist/vendor/codali/runtime/InteractionRouter.js +108 -27
  71. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts +4 -0
  72. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts.map +1 -0
  73. package/dist/vendor/codali/runtime/PreparedDocdex.js +55 -0
  74. package/dist/vendor/codali/runtime/SessionController.d.ts +22 -0
  75. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  76. package/dist/vendor/codali/runtime/SessionController.js +721 -61
  77. package/dist/vendor/codali/session/InstructionLoader.d.ts +5 -1
  78. package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -1
  79. package/dist/vendor/codali/session/InstructionLoader.js +65 -19
  80. package/dist/vendor/codali/session/SkillCatalog.d.ts +33 -0
  81. package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -0
  82. package/dist/vendor/codali/session/SkillCatalog.js +194 -0
  83. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts +19 -0
  84. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts.map +1 -0
  85. package/dist/vendor/codali/tools/SemanticToolRetrieval.js +52 -0
  86. package/dist/vendor/codali/tools/ToolRetrieval.d.ts +7 -0
  87. package/dist/vendor/codali/tools/ToolRetrieval.d.ts.map +1 -0
  88. package/dist/vendor/codali/tools/ToolRetrieval.js +25 -0
  89. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +9 -0
  90. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -0
  91. package/dist/vendor/codali/tools/browser/BrowserTool.js +152 -0
  92. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts +2 -0
  93. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts.map +1 -0
  94. package/dist/vendor/codali/tools/browser/BrowserWorker.js +51 -0
  95. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +5 -0
  96. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -0
  97. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +137 -0
  98. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts +39 -0
  99. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
  100. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.js +98 -0
  101. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts +8 -0
  102. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -0
  103. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +86 -0
  104. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +38 -0
  105. package/dist/vendor/codali/tools/deterministic/python-worker.py +222 -0
  106. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts +4 -0
  107. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
  108. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +58 -0
  109. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
  110. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
  111. package/dist/vendor/codali/tools/docdex/DocdexTools.js +72 -105
  112. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts +12 -0
  113. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts.map +1 -0
  114. package/dist/vendor/codali/tools/documents/DocumentRuntime.js +59 -0
  115. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts +19 -0
  116. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts.map +1 -0
  117. package/dist/vendor/codali/tools/documents/DocumentTools.js +150 -0
  118. package/dist/vendor/codali/tools/documents/worker.py +267 -0
  119. package/dist/vendor/codali/tools/entities/AdesTool.d.ts +7 -0
  120. package/dist/vendor/codali/tools/entities/AdesTool.d.ts.map +1 -0
  121. package/dist/vendor/codali/tools/entities/AdesTool.js +59 -0
  122. package/dist/vendor/codali/tools/research/TnlTool.d.ts +22 -0
  123. package/dist/vendor/codali/tools/research/TnlTool.d.ts.map +1 -0
  124. package/dist/vendor/codali/tools/research/TnlTool.js +246 -0
  125. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
  126. package/dist/vendor/codali/tools/shell/HostToolchain.js +14 -2
  127. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +3 -2
  128. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  129. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +34 -4
  130. package/dist/vendor/codali/tools/system/TimeTool.d.ts +4 -0
  131. package/dist/vendor/codali/tools/system/TimeTool.d.ts.map +1 -0
  132. package/dist/vendor/codali/tools/system/TimeTool.js +22 -0
  133. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
  134. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
  135. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +71 -0
  136. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
  137. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
  138. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.js +91 -0
  139. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +3 -0
  140. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -0
  141. package/dist/vendor/codali/tools/verification/VitestTool.js +128 -0
  142. package/dist/vendor/config/AGENTS.md +11 -0
  143. package/dist/vendor/config/deterministic/install-python.mjs +16 -0
  144. package/dist/vendor/config/deterministic/node-worker.mjs +77 -0
  145. package/dist/vendor/config/deterministic/python-worker.py +222 -0
  146. package/dist/vendor/config/deterministic/requirements.txt +6 -0
  147. package/dist/vendor/config/docdex-runtime.json +21 -0
  148. package/dist/vendor/config/docdex-tools-0.2.99.json +3977 -0
  149. package/dist/vendor/config/documents/install-python.mjs +16 -0
  150. package/dist/vendor/config/documents/requirements.txt +10 -0
  151. package/dist/vendor/config/documents/worker.py +267 -0
  152. package/dist/vendor/config/skills/planning/SKILL.md +13 -0
  153. package/package.json +11 -4
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { mswarmClientProductHeaders } from "@mcoda/shared";
6
+ import { docdexCatalog, docdexCatalogOperation } from "./DocdexCatalog.js";
6
7
  export class DocdexRuntimeError extends Error {
7
8
  constructor(code, message, options = {}) {
8
9
  super(message);
@@ -116,6 +117,9 @@ export const normalizeDocdexRuntimeOperation = (value) => {
116
117
  const aliased = aliases[normalized];
117
118
  if (aliased)
118
119
  return aliased;
120
+ const catalogName = normalized.replace(/^catalog:/, "").replace(/^docdex_/, "");
121
+ if (docdexCatalogOperation(`docdex_${catalogName}`) && !DOCDEX_RUNTIME_OPERATIONS.has(catalogName))
122
+ return `catalog:${catalogName}`;
119
123
  return DOCDEX_RUNTIME_OPERATIONS.has(normalized)
120
124
  ? normalized
121
125
  : undefined;
@@ -160,8 +164,8 @@ export class DocdexClient {
160
164
  this.repoId = options.repoId;
161
165
  this.dagSessionId = options.dagSessionId;
162
166
  }
163
- async fetch(input, init = {}) {
164
- const signals = [init.signal, this.options.signal?.(), AbortSignal.timeout(this.options.timeoutMs ?? 60000)].filter((signal) => !!signal);
167
+ async fetch(input, init = {}, timeoutMs = this.options.timeoutMs ?? 60000) {
168
+ const signals = [init.signal, this.options.signal?.(), AbortSignal.timeout(timeoutMs)].filter((signal) => !!signal);
165
169
  const signal = AbortSignal.any(signals);
166
170
  signal.throwIfAborted();
167
171
  await this.options.beforeRequest?.(input);
@@ -555,6 +559,23 @@ export class DocdexClient {
555
559
  await this.ensureHealth();
556
560
  await this.ensureRepoInitialized();
557
561
  const dagSessionId = options.dagSessionId ?? this.dagSessionId;
562
+ if (this.options.localSearchOnly && !this.isEncryptedSearchGateway()) {
563
+ // /search's repo_only flag does not disable its web waterfall on all
564
+ // supported daemons. The batch endpoint performs index retrieval only:
565
+ // no surprise web requests, classifier calls or embedding-memory lookups.
566
+ const response = await this.fetch(`${this.resolveBaseUrl()}/v1/search/batch`, {
567
+ method: "POST", headers: this.buildHeaders(dagSessionId),
568
+ body: JSON.stringify({ queries: [query], limit: options.limit ?? 8, include_libs: false, repo_id: this.repoId }),
569
+ });
570
+ if (!response.ok)
571
+ await this.throwResponseError(response, "local search");
572
+ const payload = await response.json();
573
+ const result = payload.results?.[0];
574
+ if (payload.results?.length !== 1 || result?.query !== query.trim() || payload.truncated || !Array.isArray(result.response?.hits)) {
575
+ throw new Error("Docdex local search returned an invalid or unavailable result; no web fallback was attempted");
576
+ }
577
+ return this.attachResponseMetadata(result.response, response, "search");
578
+ }
558
579
  const executeSearch = (searchQuery) => {
559
580
  if (this.isEncryptedSearchGateway()) {
560
581
  return this.fetch(`${this.resolveBaseUrl()}/search`, {
@@ -810,8 +831,8 @@ export class DocdexClient {
810
831
  }
811
832
  return body;
812
833
  }
813
- async ensureMcpSession() {
814
- if (!this.options.authToken || this.options.apiKey || this.mcpSessionId)
834
+ async ensureMcpSession(force = false) {
835
+ if ((!force && (!this.options.authToken || this.options.apiKey)) || this.mcpSessionId)
815
836
  return;
816
837
  if (!this.mcpInitialize) {
817
838
  this.mcpInitialize = (async () => {
@@ -841,24 +862,29 @@ export class DocdexClient {
841
862
  this.mcpInitialize = undefined;
842
863
  }
843
864
  }
844
- async callMcp(method, params) {
865
+ async callMcp(method, params, timeoutMs) {
845
866
  const operation = MCP_OPERATION_BY_METHOD[method];
846
867
  if (operation) {
847
868
  this.assertOperationAllowed(operation);
848
869
  }
870
+ else
871
+ throw this.runtimeError("docdex_operation_not_allowed", `Unknown Docdex operation: ${method}`, { retryable: false });
849
872
  await this.ensureHealth();
850
873
  await this.ensureMcpSession();
874
+ // The daemon recognizes the web-specific deadline only on standard MCP
875
+ // tools/call envelopes; a legacy direct method gets the generic 30s limit.
876
+ const standardToolCall = method === "docdex_web_research";
851
877
  const payload = {
852
878
  jsonrpc: "2.0",
853
879
  id: randomUUID(),
854
- method,
855
- params,
880
+ method: standardToolCall ? "tools/call" : method,
881
+ params: standardToolCall ? { name: method, arguments: params } : params,
856
882
  };
857
883
  const response = await this.fetch(`${this.resolveBaseUrl()}/v1/mcp`, {
858
884
  method: "POST",
859
885
  headers: { ...this.buildHeaders(), ...(this.mcpSessionId ? { "mcp-session-id": this.mcpSessionId } : {}) },
860
886
  body: JSON.stringify(payload),
861
- });
887
+ }, timeoutMs);
862
888
  if (!response.ok) {
863
889
  if (response.status === 404)
864
890
  this.mcpSessionId = undefined;
@@ -870,11 +896,53 @@ export class DocdexClient {
870
896
  const code = this.mapResponseErrorCode(500, body);
871
897
  throw this.runtimeError(code, raw.error.message ?? "Docdex MCP error", {
872
898
  retryable: code === "docdex_unavailable",
873
- details: { method },
899
+ details: { method, rpcCode: raw.error.code },
874
900
  });
875
901
  }
876
902
  return this.attachResponseMetadata(this.normalizeMcpResult(raw.result), response, operation ?? method);
877
903
  }
904
+ async listCatalog() {
905
+ this.assertOperationAllowed("capabilities");
906
+ return this.catalogRequest ?? (this.catalogRequest = this.catalogRpc("tools/list", {}).then(result => {
907
+ if (!Array.isArray(result.tools))
908
+ throw this.runtimeError("docdex_unavailable", "Invalid Docdex tool catalog");
909
+ return result.tools;
910
+ }).catch(error => { this.catalogRequest = undefined; throw error; }));
911
+ }
912
+ async callCatalog(name, arguments_) {
913
+ const operation = MCP_OPERATION_BY_METHOD[name] ?? normalizeDocdexRuntimeOperation(name);
914
+ if (!operation || !docdexCatalogOperation(name))
915
+ throw this.runtimeError("docdex_operation_not_allowed", `Unclassified Docdex catalog tool: ${name}`, { retryable: false });
916
+ this.assertOperationAllowed(operation);
917
+ // Discover only after operation authorization, never to bypass job scopes.
918
+ const catalog = await this.listCatalog();
919
+ const advertised = catalog.find(tool => tool.name === name), bundled = docdexCatalog.find(tool => tool.name === name);
920
+ if (!advertised)
921
+ throw this.runtimeError("docdex_unavailable", `This Docdex runtime does not advertise ${name}`, { retryable: false });
922
+ const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object"
923
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;
924
+ if (JSON.stringify(canonical(advertised.inputSchema)) !== JSON.stringify(canonical(bundled.inputSchema)))
925
+ throw this.runtimeError("docdex_unavailable", `Docdex schema changed for ${name}; refresh the versioned catalog before executing`, { retryable: false });
926
+ return this.catalogRpc("tools/call", { name, arguments: arguments_ });
927
+ }
928
+ async catalogRpc(method, params) {
929
+ await this.ensureHealth();
930
+ await this.ensureMcpSession(true);
931
+ const response = await this.fetch(`${this.resolveBaseUrl()}/v1/mcp`, { method: "POST",
932
+ headers: { ...this.buildHeaders(), "mcp-session-id": this.mcpSessionId },
933
+ body: JSON.stringify({ jsonrpc: "2.0", id: randomUUID(), method, params }) });
934
+ if (!response.ok) {
935
+ if (response.status === 404) {
936
+ this.mcpSessionId = undefined;
937
+ this.catalogRequest = undefined;
938
+ }
939
+ await this.throwResponseError(response, "MCP catalog");
940
+ }
941
+ const body = await response.json();
942
+ if (body.error)
943
+ throw this.runtimeError("docdex_unavailable", body.error.message ?? "Docdex catalog operation failed", { retryable: false });
944
+ return this.attachResponseMetadata(this.normalizeMcpResult(body.result), response, method);
945
+ }
878
946
  normalizeMcpResult(payload) {
879
947
  if (!payload || typeof payload !== "object")
880
948
  return payload;
@@ -1068,7 +1136,14 @@ export class DocdexClient {
1068
1136
  skip_local_search: options.skipLocalSearch,
1069
1137
  web_limit: options.webLimit,
1070
1138
  no_cache: options.noCache,
1071
- })).catch(() => this.webResearchHttp(query, options));
1139
+ }), this.options.webTimeoutMs ?? 90000).catch(error => {
1140
+ // Only a confirmed missing transport can use the compatibility endpoint.
1141
+ // A timeout may still be fetching pages or using the metered helper.
1142
+ if (error instanceof DocdexRuntimeError && ([404, 405].includes(error.status ?? 0) || error.details?.rpcCode === -32601)) {
1143
+ return this.webResearchHttp(query, options);
1144
+ }
1145
+ throw error;
1146
+ });
1072
1147
  }
1073
1148
  async webResearchHttp(query, options = {}) {
1074
1149
  this.assertOperationAllowed("web_research");
@@ -1103,7 +1178,7 @@ export class DocdexClient {
1103
1178
  this.withRepoId(params);
1104
1179
  const response = await this.fetch(`${this.resolveBaseUrl()}/search?${params.toString()}`, {
1105
1180
  headers: this.buildHeaders(this.dagSessionId),
1106
- });
1181
+ }, this.options.webTimeoutMs ?? 90000);
1107
1182
  if (!response.ok) {
1108
1183
  await this.throwResponseError(response, "web research");
1109
1184
  }
@@ -21,6 +21,7 @@ export declare class ManagedDocdex {
21
21
  signal?: AbortSignal;
22
22
  allowWeb?: boolean;
23
23
  startupTimeoutMs?: number;
24
+ webSearch?: (query: string, signal: AbortSignal) => Promise<unknown>;
24
25
  onStatus?: (status: string) => void;
25
26
  });
26
27
  start(): Promise<DocdexClient>;
@@ -1 +1 @@
1
- {"version":3,"file":"ManagedDocdex.d.ts","sourceRoot":"","sources":["../../src/docdex/ManagedDocdex.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,QAAQ,EAAmB,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAajD,wFAAwF;AACxF,qBAAa,aAAa;IAQZ,OAAO,CAAC,QAAQ,CAAC,OAAO;IAPpC,OAAO,CAAC,KAAK,CAAC,CAAe;IAC7B,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,eAAe,CAAC,CAAS;IACjC,OAAO,CAAC,KAAK,CAAC,CAAa;IAC3B,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;gBACrB,OAAO,EAAE;QACpC,aAAa,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,oBAAoB,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAC;QAC/F,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC5G,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;KACrC;IAEK,KAAK,IAAI,OAAO,CAAC,YAAY,CAAC;IAyG9B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAa7B"}
1
+ {"version":3,"file":"ManagedDocdex.d.ts","sourceRoot":"","sources":["../../src/docdex/ManagedDocdex.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,QAAQ,EAAmB,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAajD,wFAAwF;AACxF,qBAAa,aAAa;IAQZ,OAAO,CAAC,QAAQ,CAAC,OAAO;IAPpC,OAAO,CAAC,KAAK,CAAC,CAAe;IAC7B,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,eAAe,CAAC,CAAS;IACjC,OAAO,CAAC,KAAK,CAAC,CAAa;IAC3B,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;gBACrB,OAAO,EAAE;QACpC,aAAa,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,oBAAoB,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAC;QAC/F,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC5G,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;QACrE,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;KACrC;IAEK,KAAK,IAAI,OAAO,CAAC,YAAY,CAAC;IAuH9B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAa7B"}
@@ -45,7 +45,10 @@ export class ManagedDocdex {
45
45
  const prefix = `/${capability}`;
46
46
  this.bridge = createServer(async (request, response) => {
47
47
  const send = (status, body) => { response.writeHead(status, { "content-type": "application/json" }); response.end(JSON.stringify(body)); };
48
- if (request.headers.origin || !request.url?.startsWith(`${prefix}/`)) {
48
+ // Docdex resolves the web route from the origin, discarding baseUrl paths.
49
+ // Accept only this exact route with the ephemeral header capability.
50
+ const webRoute = request.url === "/v1/swarm/web/search" && request.headers["x-api-key"] === capability;
51
+ if (request.headers.origin || (!webRoute && !request.url?.startsWith(`${prefix}/`))) {
49
52
  send(403, { error: "forbidden" });
50
53
  return;
51
54
  }
@@ -59,7 +62,7 @@ export class ManagedDocdex {
59
62
  requestAbort.abort(); };
60
63
  response.once("close", onClose);
61
64
  try {
62
- const route = request.url.slice(prefix.length);
65
+ const route = webRoute ? request.url : request.url.slice(prefix.length);
63
66
  if (request.method === "GET" && route === "/api/version") {
64
67
  send(200, { version: "codali-managed-v1" });
65
68
  return;
@@ -84,6 +87,18 @@ export class ManagedDocdex {
84
87
  }
85
88
  const body = JSON.parse(Buffer.concat(chunks).toString());
86
89
  const requestSignal = AbortSignal.any([signal, requestAbort.signal]);
90
+ if (route === "/v1/swarm/web/search") {
91
+ if (!this.options.allowWeb || !this.options.webSearch || request.headers["x-api-key"] !== capability) {
92
+ send(403, { error: "web research unavailable" });
93
+ return;
94
+ }
95
+ if (typeof body.query !== "string" || !body.query.trim() || body.query.length > 4000 || body.tool_id !== "docdex") {
96
+ send(400, { error: "invalid web query" });
97
+ return;
98
+ }
99
+ send(200, await this.options.webSearch(body.query, requestSignal));
100
+ return;
101
+ }
87
102
  if (route === "/v1/embeddings") {
88
103
  if (body.model !== model || !["query", "document"].includes(String(body.input_type))) {
89
104
  send(400, { error: "managed embedding identity and input_type are required" });
@@ -116,7 +131,9 @@ export class ManagedDocdex {
116
131
  send(400, { error: "invalid inference messages" });
117
132
  return;
118
133
  }
119
- const result = await this.options.provider.generate({ messages, signal: requestSignal, stream: false, maxTokens: 2048 });
134
+ const requested = body.options && typeof body.options === "object" ? body.options.num_predict : undefined;
135
+ const maxTokens = typeof requested === "number" && Number.isSafeInteger(requested) && requested > 0 ? Math.min(2048, requested) : 2048;
136
+ const result = await this.options.provider.generate({ messages, signal: requestSignal, stream: false, maxTokens });
120
137
  send(200, { model: "configured-docdex-helper", created_at: new Date().toISOString(), done: true,
121
138
  message: { role: "assistant", content: result.message.content }, response: result.message.content,
122
139
  ...(result.usage ? { prompt_eval_count: result.usage.inputTokens, eval_count: result.usage.outputTokens } : {}) });
@@ -139,7 +156,11 @@ export class ManagedDocdex {
139
156
  const configPath = path.join(this.launchDirectory, "config.toml");
140
157
  const repositoryState = path.join(root, "repositories", createHash("sha256").update(path.resolve(this.options.workspaceRoot)).digest("hex"));
141
158
  const config = `[core]\nglobal_state_dir = ${JSON.stringify(root)}\n[server]\nhttp_bind_addr = "127.0.0.1:${port}"\n[llm]\nprovider = "ollama"\nbase_url = ${JSON.stringify(bridgeBase)}\ndefault_model = "configured-docdex-helper"\nembedding_model = ${JSON.stringify(model)}\n[llm.delegation]\nenabled = false\nauto_enable = false\n[memory]\nenabled = true\n[memory.profile]\nembedding_model = "hash-embed-v1"\nembedding_dim = 768\n[memory.conversations]\nenabled = true\nauto_capture = false\n[memory.personal_preferences]\nenabled = false\n[memory.user_memory_sync]\nenabled = false\n`;
142
- await fs.writeFile(configPath, config, { mode: 0o600, flag: "wx" });
159
+ // The private process sees only a short-lived bridge credential. The host
160
+ // retains the service credential and owns authorization/audit at tool entry.
161
+ const webConfig = this.options.allowWeb && this.options.webSearch
162
+ ? `\n[web]\ndiscovery_provider = "mswarm"\n[integrations.mswarm]\nbase_url = ${JSON.stringify(bridgeBase)}\napi_key = ${JSON.stringify(capability)}\n` : "";
163
+ await fs.writeFile(configPath, config + webConfig, { mode: 0o600, flag: "wx" });
143
164
  const env = {};
144
165
  for (const key of ["PATH", "HOME", "USER", "LOGNAME", "LANG", "TMPDIR", "SystemRoot"])
145
166
  if (process.env[key])
@@ -0,0 +1,94 @@
1
+ export interface TrustCase {
2
+ id: string;
3
+ domain: string;
4
+ family: string;
5
+ variant: number;
6
+ split: "development" | "validation" | "held_out";
7
+ prompt: string;
8
+ files: Record<string, string>;
9
+ history: Array<{
10
+ role: "user" | "assistant";
11
+ content: string;
12
+ }>;
13
+ capabilities: string[];
14
+ }
15
+ export interface TrustScoreSpec {
16
+ id: string;
17
+ kind: "json" | "code" | "rubric";
18
+ critical: boolean;
19
+ expected?: unknown;
20
+ criteria?: string[];
21
+ reference?: string;
22
+ alternatives?: unknown[];
23
+ preserveInput?: boolean;
24
+ /** The contract requires a new array rather than returning this input array. */
25
+ distinctOutputFrom?: string[];
26
+ maxWords?: number;
27
+ complexityProbe?: {
28
+ kind: "binary_search_first";
29
+ size: number;
30
+ maxIndexedReads: number;
31
+ };
32
+ tests?: Array<{
33
+ input: unknown;
34
+ expected: unknown;
35
+ }>;
36
+ }
37
+ export interface TrustGrade {
38
+ status: "passed" | "failed" | "needs_review";
39
+ passed: boolean;
40
+ semanticPassed?: boolean;
41
+ formatPassed?: boolean;
42
+ checks?: number;
43
+ failures: string[];
44
+ criteria?: string[];
45
+ outputSha256: string;
46
+ toolEvidence?: {
47
+ required: boolean;
48
+ passed: boolean;
49
+ successfulTools: string[];
50
+ expectedTools: string[];
51
+ };
52
+ }
53
+ /** A correct-looking guess does not satisfy an explicit request to inspect with Docdex.
54
+ * raw_direct receives the entire fixture in its prompt and explicitly has no tools.
55
+ */
56
+ export declare function applyTrustToolEvidence(task: TrustCase, arm: string, grade: TrustGrade, events: Array<{
57
+ type: string;
58
+ data: Record<string, unknown>;
59
+ }>): TrustGrade;
60
+ export declare const trustHash: (text: string | Buffer) => string;
61
+ export declare function equalTrustValue(actual: unknown, expected: unknown): boolean;
62
+ /** No answer keys, grading code or host credentials are mounted in the submission sandbox.
63
+ * The sandbox returns observations. Expected values are compared here, in the host.
64
+ */
65
+ export declare function gradeTrustAnswer(spec: TrustScoreSpec, content: string, options?: {
66
+ error?: string;
67
+ workspacePreserved?: boolean;
68
+ }): Promise<TrustGrade>;
69
+ export interface TrustCorpusContract {
70
+ count: number;
71
+ families: number;
72
+ splits: {
73
+ development: number;
74
+ validation: number;
75
+ held_out: number;
76
+ };
77
+ }
78
+ export declare function validateTrustCorpus(cases: TrustCase[], specs: TrustScoreSpec[], contract?: TrustCorpusContract): void;
79
+ export interface RubricReview {
80
+ caseId: string;
81
+ attemptId: string;
82
+ outputSha256: string;
83
+ reviewer: string;
84
+ dimensions: Array<{
85
+ criterion: number;
86
+ passed: boolean;
87
+ evidence: string;
88
+ }>;
89
+ criticalFailure: boolean;
90
+ rationale: string;
91
+ }
92
+ /** Review is explicit and bound to the original output; model self-grading is not a pass. */
93
+ export declare function applyTrustReview(spec: TrustScoreSpec, grade: TrustGrade, review: RubricReview): TrustGrade;
94
+ //# sourceMappingURL=TrustBenchmark.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TrustBenchmark.d.ts","sourceRoot":"","sources":["../../src/eval/TrustBenchmark.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAC5D,KAAK,EAAE,aAAa,GAAG,YAAY,GAAG,UAAU,CAAC;IACjD,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9C,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB;AACD,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAC;IAChE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5D,YAAY,CAAC,EAAE,OAAO,EAAE,CAAC;IACz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AAe,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAS3E;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,OAAO,CAAC,UAAU,CAAC,CA0EjK;AAED,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAChC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CACvE;AACD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,QAAQ,GAAE,mBAAkH,GAAG,IAAI,CAyBnN;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAC1E,UAAU,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5E,eAAe,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;CAC7C;AACD,6FAA6F;AAC7F,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,GAAG,UAAU,CAM1G"}
@@ -0,0 +1,199 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { createIsolatedExecutor } from "../tools/shell/IsolatedExecutor.js";
6
+ /** A correct-looking guess does not satisfy an explicit request to inspect with Docdex.
7
+ * raw_direct receives the entire fixture in its prompt and explicitly has no tools.
8
+ */
9
+ export function applyTrustToolEvidence(task, arm, grade, events) {
10
+ if (task.domain !== "repository_and_docdex" || arm === "raw_direct")
11
+ return grade;
12
+ const names = new Set();
13
+ for (const event of events) {
14
+ if (event.type !== "tool_receipt")
15
+ continue;
16
+ const receipt = event.data.receipt;
17
+ const call = event.data.call;
18
+ if (receipt?.status === "success" && receipt.tool)
19
+ names.add(receipt.tool);
20
+ if (receipt?.ok === true && call?.name)
21
+ names.add(call.name);
22
+ }
23
+ const passed = [...names].some(name => /^docdex_(search|open|symbols|ast|impact_graph|tree|stats|files)$/.test(name));
24
+ return { ...grade, toolEvidence: { required: true, passed, successfulTools: [...names].sort(), expectedTools: task.capabilities },
25
+ ...(!passed ? { passed: false, status: "failed", failures: [...grade.failures, "No successful Docdex evidence call for the explicitly requested investigation"] } : {}) };
26
+ }
27
+ export const trustHash = (text) => createHash("sha256").update(text).digest("hex");
28
+ export function equalTrustValue(actual, expected) {
29
+ if (typeof actual === "number" && typeof expected === "number")
30
+ return Number.isFinite(actual) && Math.abs(actual - expected) <= 1e-9 * Math.max(1, Math.abs(expected));
31
+ if (actual === expected)
32
+ return true;
33
+ if (Array.isArray(actual) && Array.isArray(expected))
34
+ return actual.length === expected.length && actual.every((x, i) => equalTrustValue(x, expected[i]));
35
+ if (actual && expected && typeof actual === "object" && typeof expected === "object" && !Array.isArray(actual) && !Array.isArray(expected)) {
36
+ const a = actual, b = expected;
37
+ return Object.keys(a).length === Object.keys(b).length && Object.keys(b).every(k => Object.prototype.hasOwnProperty.call(a, k) && equalTrustValue(a[k], b[k]));
38
+ }
39
+ return false;
40
+ }
41
+ /** No answer keys, grading code or host credentials are mounted in the submission sandbox.
42
+ * The sandbox returns observations. Expected values are compared here, in the host.
43
+ */
44
+ export async function gradeTrustAnswer(spec, content, options = {}) {
45
+ const grade = { status: "failed", passed: false, failures: [], outputSha256: trustHash(content) };
46
+ if (options.error)
47
+ grade.failures.push(`attempt_error: ${options.error.slice(0, 1000)}`);
48
+ if (options.workspacePreserved === false)
49
+ grade.failures.push("Read-only fixture changed");
50
+ if (grade.failures.length)
51
+ return grade;
52
+ if (!content.trim()) {
53
+ grade.failures.push("Empty answer");
54
+ return grade;
55
+ }
56
+ if (spec.maxWords !== undefined) {
57
+ const words = content.trim().split(/\s+/u).filter(token => /[\p{L}\p{N}]/u.test(token)).length;
58
+ if (words > spec.maxWords) {
59
+ grade.failures.push(`Requested word limit exceeded: ${words} > ${spec.maxWords}`);
60
+ return grade;
61
+ }
62
+ }
63
+ if (spec.kind === "rubric") {
64
+ grade.status = "needs_review";
65
+ grade.criteria = spec.criteria;
66
+ return grade;
67
+ }
68
+ if (spec.kind === "json") {
69
+ let actual;
70
+ try {
71
+ actual = JSON.parse(content.trim());
72
+ grade.formatPassed = true;
73
+ }
74
+ catch {
75
+ grade.formatPassed = false;
76
+ const match = content.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n```$/);
77
+ try {
78
+ actual = match ? JSON.parse(match[1]) : undefined;
79
+ }
80
+ catch { /* malformed remains failed */ }
81
+ }
82
+ grade.semanticPassed = equalTrustValue(actual, spec.expected) || (spec.alternatives ?? []).some(value => equalTrustValue(actual, value));
83
+ if (!grade.semanticPassed)
84
+ grade.failures.push("Answer differs from the independently specified value");
85
+ if (!grade.formatPassed)
86
+ grade.failures.push("Requested JSON-only format not followed");
87
+ }
88
+ else {
89
+ const blocks = [...content.matchAll(/```(?:javascript|js|mjs)?\s*\n([\s\S]*?)\n```/g)];
90
+ const source = blocks.length === 1 ? blocks[0][1] : blocks.length ? "" : content;
91
+ if (!source || Buffer.byteLength(source) > 65536) {
92
+ grade.failures.push("Missing, ambiguous or oversized code");
93
+ return grade;
94
+ }
95
+ if (!spec.tests?.length)
96
+ throw new Error("Code score specification has no independent inputs");
97
+ const tests = [...spec.tests];
98
+ if (spec.complexityProbe) {
99
+ const { size, maxIndexedReads } = spec.complexityProbe;
100
+ if (spec.complexityProbe.kind !== "binary_search_first" || !Number.isSafeInteger(size) || size < 1000 || size > 100000 || !Number.isSafeInteger(maxIndexedReads) || maxIndexedReads < 1)
101
+ throw new Error("Invalid complexity probe");
102
+ const target = Math.floor((size - 3) / 3);
103
+ tests.push({ input: { values: Array.from({ length: size }, (_, i) => Math.floor(i / 3)), target }, expected: target * 3 });
104
+ }
105
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-trust-grade-"));
106
+ try {
107
+ await fs.chmod(root, 0o700);
108
+ await fs.writeFile(path.join(root, "submission.mjs"), source, { flag: "wx", mode: 0o600 });
109
+ // Inputs only. A deliberately wrong submission cannot read expected answers.
110
+ await fs.writeFile(path.join(root, "inputs.json"), JSON.stringify({ inputs: tests.map(t => t.input), instrumentIndex: spec.complexityProbe ? tests.length - 1 : -1, distinctOutputPath: spec.distinctOutputFrom ?? null }), { flag: "wx", mode: 0o600 });
111
+ await fs.writeFile(path.join(root, "observe.mjs"), `import { readFileSync } from 'node:fs';
112
+ const stringify=JSON.stringify.bind(JSON); const parse=JSON.parse.bind(JSON); const output=process.stdout.write.bind(process.stdout);
113
+ const {inputs,instrumentIndex,distinctOutputPath}=parse(readFileSync(new URL('./inputs.json',import.meta.url),'utf8'));const get=Reflect.get.bind(Reflect);
114
+ const {solve}=await import('./submission.mjs');
115
+ if(typeof solve!=='function')throw Error('Export solve(input)');
116
+ const results=[];for(let index=0;index<inputs.length;index++){const input=inputs[index];let reads=0;
117
+ if(index===instrumentIndex)input.values=new Proxy(input.values,{get(t,p,r){if(typeof p==='string'&&/^[0-9]+$/.test(p))reads++;return get(t,p,r);}});
118
+ const originalArray=distinctOutputPath===null?undefined:distinctOutputPath.reduce((v,k)=>v[k],input);
119
+ const before=stringify(input);reads=0;const value=await solve(input);const indexedReads=reads;results.push({value,indexedReads,distinctOutput:distinctOutputPath===null||value!==originalArray,unchanged:before===stringify(input)});}
120
+ output(stringify(results));`, { flag: "wx", mode: 0o600 });
121
+ const execute = createIsolatedExecutor({ network: false });
122
+ const observed = await execute(process.execPath, ["--max-old-space-size=96", "observe.mjs"], {
123
+ workspaceRoot: root, allowedWritePaths: [], shellTimeoutMs: 5000, shellMaxOutputBytes: 131072,
124
+ });
125
+ const actual = JSON.parse(observed.output);
126
+ if (!Array.isArray(actual) || actual.length !== tests.length)
127
+ throw new Error("Incomplete observations");
128
+ grade.checks = actual.length;
129
+ for (let i = 0; i < actual.length; i++) {
130
+ if (!equalTrustValue(actual[i]?.value, tests[i].expected))
131
+ grade.failures.push(`Independent input ${i + 1}: wrong value`);
132
+ if (spec.preserveInput && actual[i]?.unchanged !== true)
133
+ grade.failures.push(`Independent input ${i + 1}: input mutated`);
134
+ if (spec.distinctOutputFrom !== undefined && actual[i]?.distinctOutput !== true)
135
+ grade.failures.push(`Independent input ${i + 1}: returned the original array instead of a new one`);
136
+ }
137
+ if (spec.complexityProbe && (!Number.isSafeInteger(actual[actual.length - 1].indexedReads) || actual[actual.length - 1].indexedReads > spec.complexityProbe.maxIndexedReads))
138
+ grade.failures.push("Binary search exceeded its bounded indexed-read probe");
139
+ grade.semanticPassed = !grade.failures.length;
140
+ grade.formatPassed = blocks.length === 1 && content.trim() === blocks[0][0];
141
+ // Code fencing is presentational; runnable correct code is accepted without a fence.
142
+ }
143
+ catch (error) {
144
+ grade.failures.push(`Sandbox/check failure: ${String(error).slice(0, 1200)}`);
145
+ }
146
+ finally {
147
+ await fs.rm(root, { recursive: true, force: true });
148
+ }
149
+ }
150
+ grade.passed = !grade.failures.length;
151
+ grade.status = grade.passed ? "passed" : "failed";
152
+ return grade;
153
+ }
154
+ export function validateTrustCorpus(cases, specs, contract = { count: 1000, families: 100, splits: { development: 600, validation: 200, held_out: 200 } }) {
155
+ if (!contract || typeof contract !== "object" || Array.isArray(contract) || Object.keys(contract).sort().join() !== "count,families,splits" ||
156
+ !Number.isSafeInteger(contract.count) || contract.count < 1 || contract.count > 10000 ||
157
+ !Number.isSafeInteger(contract.families) || contract.families < 1 || contract.families > contract.count ||
158
+ !contract.splits || typeof contract.splits !== "object" || Array.isArray(contract.splits) || Object.keys(contract.splits).sort().join() !== "development,held_out,validation" ||
159
+ Object.values(contract.splits).some(n => !Number.isSafeInteger(n) || n < 0) || Object.values(contract.splits).reduce((a, b) => a + b, 0) !== contract.count)
160
+ throw new Error("Invalid explicit corpus contract");
161
+ if (cases.length !== contract.count || specs.length !== contract.count)
162
+ throw new Error(`The frozen corpus must contain exactly ${contract.count} questions and grading specifications`);
163
+ const ids = new Set(), questions = new Set(), families = new Map();
164
+ const specIds = new Set(specs.map(x => x.id));
165
+ if (specIds.size !== contract.count)
166
+ throw new Error("Duplicate scoring ID");
167
+ const splits = {};
168
+ for (const c of cases) {
169
+ if (!/^[a-z0-9_.-]+$/.test(c.id) || ids.has(c.id) || !specIds.has(c.id))
170
+ throw new Error("Invalid/duplicate/missing case ID");
171
+ ids.add(c.id);
172
+ const signature = JSON.stringify([c.prompt, c.files, c.history]);
173
+ if (questions.has(signature))
174
+ throw new Error(`Duplicate question: ${c.id}`);
175
+ questions.add(signature);
176
+ if (families.has(c.family) && families.get(c.family) !== c.split)
177
+ throw new Error("Family leaked across splits");
178
+ families.set(c.family, c.split);
179
+ splits[c.split] = (splits[c.split] ?? 0) + 1;
180
+ for (const [file, contents] of Object.entries(c.files)) {
181
+ if (!file || path.isAbsolute(file) || file.split(/[\\/]/).some(part => !part || part === ".." || part === "." || part === ".git" || part === ".mcoda") || Buffer.byteLength(contents) > 65536)
182
+ throw new Error("Unsafe fixture path/size");
183
+ }
184
+ if (c.history.some(m => !["user", "assistant"].includes(m.role) || typeof m.content !== "string"))
185
+ throw new Error("Unsafe fixture history");
186
+ }
187
+ if (families.size !== contract.families || Object.entries(contract.splits).some(([name, count]) => (splits[name] ?? 0) !== count))
188
+ throw new Error("Corpus partition contract failed");
189
+ }
190
+ /** Review is explicit and bound to the original output; model self-grading is not a pass. */
191
+ export function applyTrustReview(spec, grade, review) {
192
+ if (spec.kind !== "rubric" || grade.status !== "needs_review" || review.caseId !== spec.id || review.outputSha256 !== grade.outputSha256 || !review.reviewer.trim() || !review.rationale.trim())
193
+ throw new Error("Invalid review identity or output binding");
194
+ const count = spec.criteria?.length ?? 0;
195
+ if (review.dimensions.length !== count || new Set(review.dimensions.map(x => x.criterion)).size !== count || review.dimensions.some(x => !Number.isInteger(x.criterion) || x.criterion < 0 || x.criterion >= count || !x.evidence.trim() || typeof x.passed !== "boolean"))
196
+ throw new Error("Incomplete rubric review");
197
+ const passed = !review.criticalFailure && review.dimensions.every(x => x.passed);
198
+ return { ...grade, passed, semanticPassed: passed, status: passed ? "passed" : "failed", failures: passed ? [] : [review.rationale] };
199
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"TerminalRecoveryJourney.d.ts","sourceRoot":"","sources":["../../../src/eval/fixtures/TerminalRecoveryJourney.ts"],"names":[],"mappings":"AAuBA;sEACsE;AACtE,wBAAsB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA2EvH"}
1
+ {"version":3,"file":"TerminalRecoveryJourney.d.ts","sourceRoot":"","sources":["../../../src/eval/fixtures/TerminalRecoveryJourney.ts"],"names":[],"mappings":"AAuBA;sEACsE;AACtE,wBAAsB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAiFvH"}
@@ -21,6 +21,9 @@ const call = (name, args) => ({ ...reply(""), toolCalls: [{ id: `${name}-${Math.
21
21
  /** A scripted fault fixture, deliberately separate from live-model evaluation.
22
22
  * Each stage is launched in a fresh OS process by the parent test. */
23
23
  export async function runTerminalRecoveryStage(workspaceRoot, storageRoot, stage) {
24
+ const started = performance.now();
25
+ const progress = (operation) => process.stderr.write(`[recovery stage=${stage} elapsedMs=${Math.round(performance.now() - started)}] ${operation}\n`);
26
+ progress("initializing controller");
24
27
  const events = [];
25
28
  let step = 0;
26
29
  let lastRead;
@@ -80,6 +83,7 @@ export async function runTerminalRecoveryStage(workspaceRoot, storageRoot, stage
80
83
  controller = new SessionController({ workspaceRoot, storageRoot, resolved: { config, hash: orchestrationHash(config), source: "deterministic-fixture" }, provider, docdex: false, permissions: "workspace", effort: "high",
81
84
  onEvent: event => { events.push(event); if (event.type === "tool_receipt") {
82
85
  const receipt = event.data.receipt;
86
+ progress(`${receipt.tool}: ${receipt.status}`);
83
87
  if (receipt.tool === "read_file" && receipt.status === "success")
84
88
  lastRead = receipt.id;
85
89
  } },
@@ -100,9 +104,13 @@ export async function runTerminalRecoveryStage(workspaceRoot, storageRoot, stage
100
104
  await controller.steer("Use stable ordering while retaining every prior criterion and the user's notes.");
101
105
  assert.throws(() => assertWorkAttempt(controller.state, "T1", priorAttempt), /Stale/);
102
106
  }
107
+ progress("running canonical work");
103
108
  const result = await controller.run();
104
- for (let i = 0; i < (stage === 3 ? 1 : 2); i++)
109
+ for (let i = 0; i < (stage === 3 ? 1 : 2); i++) {
110
+ progress(`compacting context ${i + 1}`);
105
111
  await controller.compact();
112
+ }
113
+ progress("checking preserved state");
106
114
  const state = controller.state;
107
115
  assert.equal(state.originalObjective, objective);
108
116
  assert.equal(state.requirements.length, stage === 1 ? 12 : 13);
@@ -130,6 +138,7 @@ export async function runTerminalRecoveryStage(workspaceRoot, storageRoot, stage
130
138
  assert.equal(JSON.parse(activeWorkContext(state, 16000)).originalObjective, objective);
131
139
  }
132
140
  await atomicWriteJson(handoffPath, { schemaVersion: 1, sessionId: controller.sessionId, stage, completed: result.completed, goalRevision: state.goalRevision, requirements: state.requirements.length, compactions: state.checkpoints.filter(checkpoint => checkpoint.note.startsWith("Context compacted")).length, usage: controller.usageSnapshot() });
141
+ progress("handoff persisted");
133
142
  }
134
143
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
135
144
  runTerminalRecoveryStage(process.argv[2], process.argv[3], Number(process.argv[4])).catch(error => { process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`); process.exitCode = 1; });
@@ -1,5 +1,5 @@
1
1
  import { type ToolDescriptor } from "../tools/ToolTypes.js";
2
- export type PermissionProfile = "plan" | "ask" | "workspace";
2
+ export type PermissionProfile = "plan" | "ask" | "workspace" | "full";
3
3
  export type PermissionKind = "read" | "write" | "shell" | "web" | "memory" | "media" | "external";
4
4
  export interface PermissionRequest {
5
5
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"PermissionGate.d.ts","sourceRoot":"","sources":["../../src/permissions/PermissionGate.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEhF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,KAAK,GAAG,WAAW,CAAC;AAC7D,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;AAClG,MAAM,WAAW,iBAAiB;IAAG,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;CAAE;AACrH,MAAM,WAAW,gBAAgB;IAAG,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAAE;AACjF,MAAM,WAAW,gBAAgB;IAAG,aAAa,EAAE,CAAC,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAC;CAAE;AAC5F,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,iBAAiB,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CA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