@mcoda/codali 0.1.135-codali.41 → 0.1.135-codali.47

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 (137) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/README.md +8 -0
  3. package/config/deterministic/node-worker.mjs +15 -2
  4. package/config/skills/code-implementation/SKILL.md +1 -1
  5. package/config/skills/planning/SKILL.md +1 -1
  6. package/config/skills/testing-and-verification/SKILL.md +5 -5
  7. package/config/skills/ui-ux-design/SKILL.md +1 -1
  8. package/config/skills/webapp-testing/SKILL.md +4 -0
  9. package/config/skills/webapp-testing/journey-driver.mjs +186 -0
  10. package/dist/cli/TerminalCommand.js +2 -2
  11. package/dist/cli/tui/TerminalPresentation.js +1 -1
  12. package/dist/config/OrchestrationConfig.d.ts +1 -0
  13. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  14. package/dist/config/OrchestrationConfig.js +3 -1
  15. package/dist/docdex/DocdexClient.d.ts +11 -0
  16. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  17. package/dist/docdex/DocdexClient.js +55 -1
  18. package/dist/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  19. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  20. package/dist/eval/fixtures/ContractReviewProvider.js +63 -0
  21. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  22. package/dist/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  23. package/dist/permissions/PermissionGate.d.ts +7 -0
  24. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  25. package/dist/permissions/PermissionGate.js +27 -1
  26. package/dist/providers/ClaudeCliProvider.d.ts.map +1 -1
  27. package/dist/providers/ClaudeCliProvider.js +1 -0
  28. package/dist/providers/CodexCliProvider.d.ts.map +1 -1
  29. package/dist/providers/CodexCliProvider.js +1 -0
  30. package/dist/providers/ConfiguredProvider.d.ts +2 -0
  31. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  32. package/dist/providers/ConfiguredProvider.js +29 -0
  33. package/dist/providers/ModelServiceError.d.ts +16 -2
  34. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  35. package/dist/providers/ModelServiceError.js +18 -1
  36. package/dist/providers/OllamaRemoteProvider.d.ts.map +1 -1
  37. package/dist/providers/OllamaRemoteProvider.js +1 -0
  38. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  39. package/dist/providers/OpenAiCompatibleProvider.js +4 -0
  40. package/dist/providers/ProviderTypes.d.ts +4 -0
  41. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  42. package/dist/runtime/AnswerEdits.d.ts +39 -0
  43. package/dist/runtime/AnswerEdits.d.ts.map +1 -0
  44. package/dist/runtime/AnswerEdits.js +134 -0
  45. package/dist/runtime/AnswerVerification.d.ts.map +1 -1
  46. package/dist/runtime/AnswerVerification.js +4 -2
  47. package/dist/runtime/AuditGuards.d.ts +41 -0
  48. package/dist/runtime/AuditGuards.d.ts.map +1 -0
  49. package/dist/runtime/AuditGuards.js +81 -0
  50. package/dist/runtime/CompletionReport.d.ts +4 -2
  51. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  52. package/dist/runtime/CompletionReport.js +8 -3
  53. package/dist/runtime/ContextCompression.d.ts +5 -0
  54. package/dist/runtime/ContextCompression.d.ts.map +1 -1
  55. package/dist/runtime/ContextCompression.js +16 -4
  56. package/dist/runtime/DeliveryDocs.d.ts +21 -0
  57. package/dist/runtime/DeliveryDocs.d.ts.map +1 -0
  58. package/dist/runtime/DeliveryDocs.js +148 -0
  59. package/dist/runtime/FigureCheck.d.ts +61 -2
  60. package/dist/runtime/FigureCheck.d.ts.map +1 -1
  61. package/dist/runtime/FigureCheck.js +210 -14
  62. package/dist/runtime/GatewayRequest.d.ts +13 -0
  63. package/dist/runtime/GatewayRequest.d.ts.map +1 -1
  64. package/dist/runtime/GatewayRequest.js +54 -1
  65. package/dist/runtime/InspectionConvergence.d.ts +4 -0
  66. package/dist/runtime/InspectionConvergence.d.ts.map +1 -1
  67. package/dist/runtime/InspectionConvergence.js +24 -1
  68. package/dist/runtime/InteractionContract.d.ts +15 -0
  69. package/dist/runtime/InteractionContract.d.ts.map +1 -1
  70. package/dist/runtime/InteractionContract.js +33 -0
  71. package/dist/runtime/InteractionRouter.d.ts +3 -3
  72. package/dist/runtime/InteractionRouter.d.ts.map +1 -1
  73. package/dist/runtime/InteractionRouter.js +1 -1
  74. package/dist/runtime/NumericProvenance.d.ts +102 -0
  75. package/dist/runtime/NumericProvenance.d.ts.map +1 -0
  76. package/dist/runtime/NumericProvenance.js +411 -0
  77. package/dist/runtime/OutageWait.d.ts +46 -5
  78. package/dist/runtime/OutageWait.d.ts.map +1 -1
  79. package/dist/runtime/OutageWait.js +81 -8
  80. package/dist/runtime/ResearchEvidence.d.ts +14 -0
  81. package/dist/runtime/ResearchEvidence.d.ts.map +1 -1
  82. package/dist/runtime/ResearchEvidence.js +139 -3
  83. package/dist/runtime/ReviewCoordinator.d.ts +22 -0
  84. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  85. package/dist/runtime/ReviewCoordinator.js +203 -25
  86. package/dist/runtime/ReviewSource.d.ts +5 -0
  87. package/dist/runtime/ReviewSource.d.ts.map +1 -1
  88. package/dist/runtime/ReviewSource.js +6 -1
  89. package/dist/runtime/SessionController.d.ts +85 -10
  90. package/dist/runtime/SessionController.d.ts.map +1 -1
  91. package/dist/runtime/SessionController.js +996 -176
  92. package/dist/runtime/StructuralEvidence.d.ts +10 -0
  93. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  94. package/dist/runtime/StructuralEvidence.js +10 -0
  95. package/dist/runtime/TaskReview.d.ts +10 -0
  96. package/dist/runtime/TaskReview.d.ts.map +1 -1
  97. package/dist/runtime/TaskReview.js +31 -3
  98. package/dist/runtime/VerificationCommand.d.ts +8 -0
  99. package/dist/runtime/VerificationCommand.d.ts.map +1 -1
  100. package/dist/runtime/VerificationCommand.js +114 -0
  101. package/dist/runtime/WorkingStyle.d.ts +20 -0
  102. package/dist/runtime/WorkingStyle.d.ts.map +1 -0
  103. package/dist/runtime/WorkingStyle.js +71 -0
  104. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  105. package/dist/tools/ToolRegistry.js +30 -4
  106. package/dist/tools/ToolTypes.d.ts +3 -0
  107. package/dist/tools/ToolTypes.d.ts.map +1 -1
  108. package/dist/tools/browser/BrowserTool.d.ts +23 -1
  109. package/dist/tools/browser/BrowserTool.d.ts.map +1 -1
  110. package/dist/tools/browser/BrowserTool.js +83 -4
  111. package/dist/tools/browser/BrowserWorker.js +142 -2
  112. package/dist/tools/browser/HttpFallback.d.ts +39 -0
  113. package/dist/tools/browser/HttpFallback.d.ts.map +1 -0
  114. package/dist/tools/browser/HttpFallback.js +240 -0
  115. package/dist/tools/calculation/CalculatorTool.d.ts +16 -1
  116. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  117. package/dist/tools/calculation/CalculatorTool.js +321 -26
  118. package/dist/tools/deterministic/DeterministicTools.js +1 -1
  119. package/dist/tools/deterministic/node-worker.cjs +10 -10
  120. package/dist/tools/shell/AsyncProcess.d.ts +2 -0
  121. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  122. package/dist/tools/shell/AsyncProcess.js +38 -5
  123. package/dist/tools/shell/IsolatedExecutor.d.ts +29 -1
  124. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  125. package/dist/tools/shell/IsolatedExecutor.js +179 -9
  126. package/dist/tools/shell/ShellTool.d.ts +2 -0
  127. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  128. package/dist/tools/shell/ShellTool.js +33 -3
  129. package/dist/tools/verification/CodeRunTool.d.ts +19 -0
  130. package/dist/tools/verification/CodeRunTool.d.ts.map +1 -0
  131. package/dist/tools/verification/CodeRunTool.js +104 -0
  132. package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  133. package/dist/tools/verification/JavaScriptVerificationTool.js +21 -10
  134. package/dist/tools/verification/VitestTool.d.ts +27 -0
  135. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  136. package/dist/tools/verification/VitestTool.js +232 -18
  137. package/package.json +3 -3
@@ -25,18 +25,22 @@ export const javaScriptAnswerSource = (answer) => {
25
25
  throw new ToolExecutionError("tool_invalid_args", "Verification requires one complete JavaScript module in a code fence, or raw module text");
26
26
  return fences[0][2].trim();
27
27
  };
28
+ /** The tool's own cases may omit expected: such a case only runs and reports its
29
+ * actual value. Answer checks (final_answer checks) still need expectations. */
30
+ const toolCasesSchema = { ...javaScriptChecksSchema.properties.cases, items: { ...javaScriptChecksSchema.properties.cases.items, required: ["args"] } };
31
+ const ACTUAL_CHARS = 4000;
28
32
  export const createJavaScriptVerificationTool = () => ({
29
33
  name: "verify_javascript", capability: "verification", readOnly: true,
30
- description: "Run a self-contained synchronous JavaScript ES module against explicit JSON cases. Named export entry receives each args array. Compares actual JSON with expected; optional preserveInput checks mutation. No imports, workspace, credentials or network. Passing supplied cases is limited evidence, not proof of general correctness.",
31
- inputSchema: { type: "object", properties: { source: { type: "string", minLength: 1, maxLength: 24000 }, ...javaScriptChecksSchema.properties },
34
+ description: "Run a self-contained synchronous JavaScript ES module against JSON cases. Named export entry receives each args array. A case with expected compares the actual JSON with it; a case without expected only runs and returns its actual value (use that to compute values, never a placeholder expectation). Optional preserveInput checks mutation. No imports, workspace, credentials or network. Passing supplied cases is limited evidence, not proof of general correctness.",
35
+ inputSchema: { type: "object", properties: { source: { type: "string", minLength: 1, maxLength: 24000 }, ...javaScriptChecksSchema.properties, cases: toolCasesSchema },
32
36
  required: ["source", ...javaScriptChecksSchema.required], additionalProperties: false },
33
37
  handler: async (raw, context) => {
34
38
  context.signal?.throwIfAborted();
35
39
  const args = raw;
36
40
  if (typeof args.source !== "string" || !args.source.trim() || args.source.length > 24000 || !/^[A-Za-z_$][\w$]{0,99}$/.test(args.entry)
37
41
  || !Array.isArray(args.cases) || args.cases.length < 1 || args.cases.length > 16
38
- || args.cases.some(test => !test || !Array.isArray(test.args) || test.args.length > 16 || !Object.prototype.hasOwnProperty.call(test, "expected"))) {
39
- throw new ToolExecutionError("tool_invalid_args", "Expected bounded source, a named export, and 1-16 JSON test cases");
42
+ || args.cases.some(test => !test || !Array.isArray(test.args) || test.args.length > 16)) {
43
+ throw new ToolExecutionError("tool_invalid_args", "Expected bounded source, a named export, and 1-16 JSON cases of the form {args:[...]} or {args:[...], expected:...}");
40
44
  }
41
45
  const payload = JSON.stringify({ source: args.source, entry: args.entry, inputs: args.cases.map(test => test.args) });
42
46
  if (payload.length > 64000 || JSON.stringify(args.cases).length > 64000)
@@ -53,16 +57,23 @@ export const createJavaScriptVerificationTool = () => ({
53
57
  const observed = JSON.parse(data.stdout);
54
58
  if (!Array.isArray(observed.observations) || observed.observations.length !== args.cases.length)
55
59
  throw new ToolExecutionError("tool_execution_failed", "Incomplete verification observations");
60
+ const expects = (test) => Object.prototype.hasOwnProperty.call(test, "expected");
56
61
  const checks = args.cases.map((test, index) => {
57
62
  const observation = observed.observations[index];
58
- const passed = !observation.error && Object.prototype.hasOwnProperty.call(observation, "actual") && isDeepStrictEqual(observation.actual, test.expected)
59
- && (!args.preserveInput || observation.inputPreserved === true);
63
+ const ran = !observation.error && Object.prototype.hasOwnProperty.call(observation, "actual");
64
+ // A run-only case reports what the code returned; there is nothing to pass or fail.
65
+ if (!expects(test))
66
+ return { index, runOnly: true, ran, ...(ran ? { actual: JSON.stringify(observation.actual).slice(0, ACTUAL_CHARS) } : { reason: observation.error }) };
67
+ const passed = ran && isDeepStrictEqual(observation.actual, test.expected) && (!args.preserveInput || observation.inputPreserved === true);
60
68
  return { index, passed, ...(!passed ? { reason: observation.error ?? (args.preserveInput && !observation.inputPreserved ? "Input was mutated" : "Actual result differs"),
61
- actual: JSON.stringify(observation.actual)?.slice(0, 200), expected: JSON.stringify(test.expected).slice(0, 200) } : {}) };
69
+ actual: JSON.stringify(observation.actual)?.slice(0, ACTUAL_CHARS), expected: JSON.stringify(test.expected).slice(0, 200) } : {}) };
62
70
  });
63
- const result = { passed: checks.every(check => check.passed), checks, sourceSha256: createHash("sha256").update(args.source).digest("hex"),
64
- scope: "Only the supplied cases; synchronous JSON values, fresh module per case, no imports" };
65
- return { output: JSON.stringify(result), data: result };
71
+ const checked = checks.filter(check => !("runOnly" in check));
72
+ const result = { ...(checked.length ? { passed: checked.every(check => "passed" in check && check.passed) } : {}), ...(checked.length < checks.length ? { runOnlyCases: checks.length - checked.length } : {}), checks,
73
+ sourceSha256: createHash("sha256").update(args.source).digest("hex"),
74
+ scope: checked.length ? "Only the supplied cases; synchronous JSON values, fresh module per case, no imports" : "Run only: values the code returned for the supplied inputs; nothing was compared" };
75
+ // The full returned values stay in the receipt data (the output shows them clipped).
76
+ return { output: JSON.stringify(result), data: { ...result, actuals: observed.observations.map(observation => observation.actual) } };
66
77
  }
67
78
  finally {
68
79
  await fs.rm(root, { recursive: true, force: true });
@@ -2,5 +2,32 @@ import { type ToolDefinition } from "../ToolTypes.js";
2
2
  /** Keep the diagnostic, not hundreds of characters of runner stack frames.
3
3
  * Vitest can put timeout/caused-by messages after STACK_TRACE_ERROR frames. */
4
4
  export declare const testFailureSummary: (message: string) => string;
5
+ type TestRunner = "vitest" | "node" | "python";
6
+ interface TestFile {
7
+ path: string;
8
+ content: string;
9
+ }
10
+ /** Which supplied files are tests. Explicitly listed files are run whatever
11
+ * convention they follow: node's default names (x.test.js, x-test.js, x_test.js,
12
+ * test-x.js, test.js, test/…), test_x.js, a file importing node:test or vitest;
13
+ * Python test_x.py or x_test.py. Cycle 7 lost five runs to test_x.js. */
14
+ export declare function isTestFile(file: TestFile, runner: TestRunner): boolean;
15
+ /** Files a test imports from its own directory tree, with the paths that
16
+ * would satisfy each import. Python names cannot be told from the standard
17
+ * library, so they are reported as candidates, never as definite misses. */
18
+ export declare function localImports(files: TestFile[], runner: TestRunner): Array<{
19
+ file: string;
20
+ specifier: string;
21
+ candidates: string[];
22
+ }>;
23
+ /** The sandbox keeps nothing between calls. A test sent without the module it
24
+ * imports, when an earlier call in the same session sent that module, gets the
25
+ * session's latest version of it (cycle 7: 5 of 26 runs sent only the test).
26
+ * Only an import that names the file is filled; nothing else is inferred. */
27
+ export declare function completeTestFiles(args: unknown, earlier: ReadonlyMap<string, string>): {
28
+ args: unknown;
29
+ carried: string[];
30
+ };
5
31
  export declare const createVitestTool: () => ToolDefinition;
32
+ export {};
6
33
  //# sourceMappingURL=VitestTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAyCF,eAAO,MAAM,gBAAgB,QAAO,cAwGlC,CAAC"}
1
+ {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAOA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAiFF,KAAK,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;AAC/C,UAAU,QAAQ;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;CAAE;AAErD;;;yEAGyE;AACzE,wBAAgB,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAOtE;AAgBD;;4EAE4E;AAC5E,wBAAgB,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAyBpI;AAED;;;6EAG6E;AAC7E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAkB3H;AAmCD,eAAO,MAAM,gBAAgB,QAAO,cA2IlC,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash } from "node:crypto";
4
+ import { execFileSync } from "node:child_process";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
6
7
  import { createIsolatedExecutor } from "../shell/IsolatedExecutor.js";
@@ -60,26 +61,199 @@ async function runnerRuntime() {
60
61
  throw Error("Vitest runtime does not match the pinned version");
61
62
  return { entry, version, mounts: [...mounts] };
62
63
  }
64
+ /** Standard-library stand-in for the part of pytest that generated tests use. */
65
+ const PYTEST_STAND_IN = `import math,re
66
+ class _Raises:
67
+ def __init__(self,expected,match=None): self.expected=expected; self.match=match; self.value=None
68
+ def __enter__(self): return self
69
+ def __exit__(self,kind,value,trace):
70
+ if kind is None: raise AssertionError('DID NOT RAISE '+str(self.expected))
71
+ if not issubclass(kind,self.expected): return False
72
+ if self.match is not None and not re.search(self.match,str(value)): raise AssertionError('raised message '+repr(str(value))+' does not match '+repr(self.match))
73
+ self.value=value; return True
74
+ def raises(expected,*args,match=None,**kwargs):
75
+ if args:
76
+ with _Raises(expected,match): args[0](*args[1:],**kwargs)
77
+ return None
78
+ return _Raises(expected,match)
79
+ class approx:
80
+ def __init__(self,expected,rel=None,abs=None): self.expected=expected; self.rel=1e-6 if rel is None else rel; self.abs=1e-12 if abs is None else abs
81
+ def _one(self,actual,expected): return math.isclose(actual,expected,rel_tol=self.rel,abs_tol=self.abs)
82
+ def __eq__(self,actual):
83
+ e=self.expected
84
+ if isinstance(e,dict): return isinstance(actual,dict) and actual.keys()==e.keys() and all(self._one(actual[k],e[k]) for k in e)
85
+ if isinstance(e,(list,tuple)): return len(actual)==len(e) and all(self._one(a,b) for a,b in zip(actual,e))
86
+ return self._one(actual,e)
87
+ def __ne__(self,actual): return not self.__eq__(actual)
88
+ def __repr__(self): return 'approx('+repr(self.expected)+')'
89
+ def fail(reason=''): raise AssertionError(reason)
90
+ class _Mark:
91
+ def parametrize(self,names,values,**ignored):
92
+ keys=[n.strip() for n in names.split(',')] if isinstance(names,str) else list(names)
93
+ def wrap(fn):
94
+ rows=[tuple(v) if len(keys)>1 else (v,) for v in values]
95
+ earlier=getattr(fn,'_codali_params',[()]); earlier_names=getattr(fn,'_codali_names',())
96
+ fn._codali_params=[tuple(r)+tuple(e) for r in rows for e in earlier]; fn._codali_names=tuple(keys)+tuple(earlier_names)
97
+ return fn
98
+ return wrap
99
+ def __getattr__(self,name): raise AttributeError('pytest.mark.'+name+' is not available in this runner; only parametrize is')
100
+ mark=_Mark()
101
+ def __getattr__(name): raise AttributeError('pytest.'+name+' is not available in this runner (stand-in provides raises, approx, fail and mark.parametrize); use the standard library')
102
+ `;
103
+ /** Which supplied files are tests. Explicitly listed files are run whatever
104
+ * convention they follow: node's default names (x.test.js, x-test.js, x_test.js,
105
+ * test-x.js, test.js, test/…), test_x.js, a file importing node:test or vitest;
106
+ * Python test_x.py or x_test.py. Cycle 7 lost five runs to test_x.js. */
107
+ export function isTestFile(file, runner) {
108
+ if (runner === "python")
109
+ return /(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/.test(file.path);
110
+ const named = /(?:^|\/)(?:[^/]+[._-](?:test|spec)|test[_-][^/]+|test)\.[cm]?[jt]s$|(?:^|\/)tests?\/[^/].*\.[cm]?[jt]s$/.test(file.path);
111
+ // A name alone is not enough: test-fixtures.js or test/helpers.js with no
112
+ // test call would run as one passing file-level "test" (review of .43).
113
+ const declaresTests = /(?:^|[^\w.$])(?:test|it|describe|suite)(?:\.(?:only|skip|todo|each|concurrent|sequential))?\s*\(/m.test(file.content ?? "");
114
+ return declaresTests && (named || (runner === "node" ? /["']node:test["']/ : /["']vitest["']/).test(file.content ?? ""));
115
+ }
116
+ let stdlibModules;
117
+ /** The sandbox interpreter's standard-library module names, computed once.
118
+ * Undefined when Python is unavailable: then nothing is carried for Python. */
119
+ const pythonStdlib = () => {
120
+ if (stdlibModules === undefined) {
121
+ try {
122
+ const names = execFileSync("python3", ["-I", "-c", "import sys;print(' '.join(sorted(sys.stdlib_module_names)))"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] });
123
+ stdlibModules = new Set(names.split(/\s+/).filter(Boolean));
124
+ if (!stdlibModules.size)
125
+ stdlibModules = null;
126
+ }
127
+ catch {
128
+ stdlibModules = null;
129
+ }
130
+ }
131
+ return stdlibModules ?? undefined;
132
+ };
133
+ /** Files a test imports from its own directory tree, with the paths that
134
+ * would satisfy each import. Python names cannot be told from the standard
135
+ * library, so they are reported as candidates, never as definite misses. */
136
+ export function localImports(files, runner) {
137
+ const found = [];
138
+ for (const file of files) {
139
+ if (typeof file?.content !== "string" || typeof file.path !== "string")
140
+ continue;
141
+ if (runner === "python") {
142
+ const modules = [...file.content.matchAll(/^[ \t]*from[ \t]+([A-Za-z_][\w.]*)[ \t]+import\b/gm)].map(match => match[1])
143
+ .concat([...file.content.matchAll(/^[ \t]*import[ \t]+([A-Za-z_][\w.]*(?:[ \t]*,[ \t]*[A-Za-z_][\w.]*)*)/gm)].flatMap(match => match[1].split(",").map(item => item.trim())));
144
+ for (const module of new Set(modules)) {
145
+ const nested = module.replace(/\./g, "/"), top = module.split(".")[0];
146
+ found.push({ file: file.path, specifier: module, candidates: [...new Set([`${nested}.py`, `${nested}/__init__.py`, `${top}.py`, `${top}/__init__.py`])] });
147
+ }
148
+ continue;
149
+ }
150
+ const base = path.posix.dirname(file.path);
151
+ for (const match of file.content.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["'](\.{1,2}\/[^"'\n]+)["']/g)) {
152
+ const resolved = path.posix.normalize(path.posix.join(base, match[1]));
153
+ if (resolved.startsWith(".."))
154
+ continue;
155
+ const extension = path.posix.extname(resolved);
156
+ const candidates = [".js", ".mjs", ".cjs", ".ts"].includes(extension)
157
+ ? [resolved, ...(runner === "vitest" && extension !== ".ts" ? [resolved.slice(0, -extension.length) + ".ts"] : [])]
158
+ : extension ? [] : [".js", ".mjs", ".cjs", ...(runner === "vitest" ? [".ts"] : [])].flatMap(ext => [resolved + ext, `${resolved}/index${ext}`]);
159
+ if (candidates.length)
160
+ found.push({ file: file.path, specifier: match[1], candidates });
161
+ }
162
+ }
163
+ return found;
164
+ }
165
+ /** The sandbox keeps nothing between calls. A test sent without the module it
166
+ * imports, when an earlier call in the same session sent that module, gets the
167
+ * session's latest version of it (cycle 7: 5 of 26 runs sent only the test).
168
+ * Only an import that names the file is filled; nothing else is inferred. */
169
+ export function completeTestFiles(args, earlier) {
170
+ const value = args;
171
+ if (!value || !Array.isArray(value.files) || !earlier.size)
172
+ return { args, carried: [] };
173
+ const runner = value.runner ?? "vitest";
174
+ if (!["vitest", "node", "python"].includes(runner))
175
+ return { args, carried: [] };
176
+ const files = [...value.files], carried = [];
177
+ // A Python import of a standard-library name (json, math, ...) must not
178
+ // pull in a same-named session file that would shadow the library.
179
+ const stdlib = runner === "python" ? pythonStdlib() : undefined;
180
+ if (runner === "python" && !stdlib)
181
+ return { args, carried: [] };
182
+ for (const item of localImports(value.files, runner)) {
183
+ if (stdlib?.has(item.specifier.split(".")[0]))
184
+ continue;
185
+ if (item.candidates.some(candidate => files.some(file => file?.path === candidate)))
186
+ continue;
187
+ const reuse = item.candidates.find(candidate => earlier.has(candidate));
188
+ if (!reuse || files.length >= 12)
189
+ continue;
190
+ files.push({ path: reuse, content: earlier.get(reuse) });
191
+ carried.push(reuse);
192
+ }
193
+ return carried.length ? { args: { ...value, files }, carried } : { args, carried };
194
+ }
195
+ const invalidRequest = (args, runner, payload) => {
196
+ const problems = [];
197
+ if (!["vitest", "node", "python"].includes(runner))
198
+ problems.push(`runner must be "vitest", "node" or "python", not ${JSON.stringify(runner)}`);
199
+ if (payload.length > 96000)
200
+ problems.push(`the request is ${payload.length} characters; the limit is 96000`);
201
+ const files = args.files;
202
+ if (!Array.isArray(files) || !files.length)
203
+ problems.push("files must list the implementation and its tests (1 to 12 {path, content} objects)");
204
+ else {
205
+ if (files.length > 12)
206
+ problems.push(`${files.length} files were sent; the limit is 12`);
207
+ for (const file of files) {
208
+ const name = JSON.stringify(typeof file?.path === "string" ? file.path : file?.path ?? null);
209
+ if (typeof file?.path !== "string" || !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.(?:[cm]?js|ts|py)$/.test(file.path))
210
+ problems.push(`${name} is not a relative path ending in .js, .mjs, .cjs, .ts or .py`);
211
+ else if (runner === "python" && !file.path.endsWith(".py"))
212
+ problems.push(`${name}: runner python takes only .py files`);
213
+ else if (runner !== "python" && file.path.endsWith(".py"))
214
+ problems.push(`${name}: .py files need runner "python"`);
215
+ else if (runner === "node" && file.path.endsWith(".ts"))
216
+ problems.push(`${name}: runner node cannot load TypeScript; use runner "vitest"`);
217
+ else if (file.path.split("/").some(segment => segment === "node_modules" || segment.startsWith(".")))
218
+ problems.push(`${name}: node_modules and dot-directories are not allowed`);
219
+ else if (/(?:^|\/)(?:vite|vitest)\.config\./.test(file.path))
220
+ problems.push(`${name}: runner configs are not accepted`);
221
+ if (typeof file?.content !== "string")
222
+ problems.push(`${name} has no string content`);
223
+ else if (file.content.length > 24000)
224
+ problems.push(`${name} is ${file.content.length} characters; the limit per file is 24000`);
225
+ }
226
+ if (new Set(files.map(file => file?.path)).size !== files.length)
227
+ problems.push("two files have the same path");
228
+ if (!problems.length && ["vitest", "node", "python"].includes(runner) && !files.some(file => isTestFile(file, runner))) {
229
+ problems.push(`none of ${files.map(file => file.path).join(", ")} is recognized as a test for runner ${runner}: ${runner === "python"
230
+ ? "name the test file test_<name>.py or <name>_test.py"
231
+ : `name it <name>.test.js, test_<name>.js or test-<name>.js, or import ${runner === "node" ? "node:test" : "vitest"} in it, and declare cases with test(), it() or describe()`}`);
232
+ }
233
+ if (!problems.length && runner !== "python") {
234
+ const missing = localImports(files, runner).filter(item => !item.candidates.some(candidate => files.some(file => file.path === candidate)));
235
+ for (const item of missing.slice(0, 4))
236
+ problems.push(`${item.file} imports "${item.specifier}", which is not among the files; include ${item.candidates[0]} with the implementation`);
237
+ }
238
+ }
239
+ return problems.length ? `verify_tests did not run: ${problems.join("; ")}. Each call starts from an empty sandbox: send the implementation together with its tests.` : undefined;
240
+ };
63
241
  export const createVitestTool = () => ({
64
242
  name: "verify_tests", readOnly: true, capability: "verification",
65
- description: "Run supplied tests offline: runner vitest (default) for JS/TS, node for node:test, python for standard-library unittest (test_*.py). Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
66
- inputSchema: { type: "object", properties: { runner: { type: "string", enum: ["vitest", "node", "python"] }, files: { type: "array", minItems: 1, maxItems: 12, items: { type: "object", properties: {
243
+ description: "Run supplied tests offline: runner vitest (default) for JS/TS, node for node:test, python for unittest classes and pytest-style test_ functions or Test classes in test_*.py/*_test.py (pytest.raises/approx/parametrize only; no fixtures, async tests or plugins). JS tests: *.test.js, test_*.js, test-*.js or any file importing node:test/vitest. Send the implementation with its tests in every call. Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
244
+ inputSchema: { type: "object", properties: { runner: { type: "string", enum: ["vitest", "node", "python"] }, files: { type: "array", minItems: 1, maxItems: 12,
245
+ description: "The implementation and its tests together; nothing persists between calls. Tests: Python test_*.py or *_test.py; JS *.test.js, test_*.js, test-*.js or a file importing node:test/vitest.", items: { type: "object", properties: {
67
246
  path: { type: "string", minLength: 1, maxLength: 160 }, content: { type: "string", maxLength: 24000 },
68
247
  }, required: ["path", "content"], additionalProperties: false } } }, required: ["files"], additionalProperties: false },
69
248
  handler: async (raw, context) => {
70
249
  context.signal?.throwIfAborted();
71
250
  const args = raw;
72
251
  const runner = args.runner ?? "vitest";
73
- const testPattern = runner === "python" ? /(?:^|\/)test_[^/]+\.py$/ : /\.test\.(?:[cm]?js|ts)$/;
74
252
  const payload = JSON.stringify(args);
75
- if (!["vitest", "node", "python"].includes(runner) || payload.length > 96000 || !Array.isArray(args.files) || !args.files.length || args.files.length > 12
76
- || args.files.some(file => !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.(?:[cm]?js|ts|py)$/.test(file.path)
77
- || (runner === "python" ? !file.path.endsWith(".py") : file.path.endsWith(".py") || runner === "node" && file.path.endsWith(".ts"))
78
- || file.path.split("/").some(segment => segment === "node_modules" || segment.startsWith(".")) || /(?:^|\/)(?:vite|vitest)\.config\./.test(file.path)
79
- || typeof file.content !== "string" || file.content.length > 24000)
80
- || new Set(args.files.map(file => file.path)).size !== args.files.length || !args.files.some(file => testPattern.test(file.path))) {
81
- throw new ToolExecutionError("tool_invalid_args", "Supply up to 12 bounded relative source/test files for the chosen runner: *.test.js/ts for Vitest, *.test.js/mjs/cjs for Node, test_*.py for Python. No configs or node_modules");
82
- }
253
+ const invalid = invalidRequest(args, runner, payload);
254
+ if (invalid)
255
+ throw new ToolExecutionError("tool_invalid_args", invalid);
256
+ const testPaths = args.files.filter(file => isTestFile(file, runner)).map(file => file.path);
83
257
  const runtime = runner === "vitest" ? await runnerRuntime() : undefined;
84
258
  const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-vitest-"));
85
259
  const started = Date.now();
@@ -93,14 +267,45 @@ export const createVitestTool = () => ({
93
267
  await fs.writeFile(path.join(root, "package.json"), '{"type":"module"}');
94
268
  await fs.mkdir(path.join(root, "artifacts"));
95
269
  if (runner !== "vitest") {
96
- const tests = args.files.filter(file => testPattern.test(file.path)).map(file => path.join(root, file.path));
97
- const python = `import unittest,sys,os,json,importlib.util
270
+ const tests = testPaths.map(file => path.join(root, file));
271
+ // Models write pytest-style tests (plain test_* functions, pytest.raises,
272
+ // approx, parametrize) far more often than unittest classes; cycle 6 lost
273
+ // twelve test runs to "pytest is not installed". A small stand-in covers
274
+ // that subset on the standard library; anything else says so by name.
275
+ if (runner === "python" && !args.files.some(file => file.path === "pytest.py" || file.path.startsWith("pytest/")))
276
+ await fs.writeFile(path.join(root, "pytest.py"), PYTEST_STAND_IN);
277
+ const python = `import unittest,sys,os,json,importlib.util,inspect
98
278
  sys.path.insert(0,os.getcwd())
99
279
  suite=unittest.TestSuite()
280
+ def one(name,fn,owner=None):
281
+ sets=getattr(fn,'_codali_params',[()])
282
+ for index,values in enumerate(sets):
283
+ names=getattr(fn,'_codali_names',())
284
+ kwargs=dict(zip(names,values))
285
+ needed=[p for p in inspect.signature(fn).parameters if p not in kwargs and p!='self']
286
+ def run(fn=fn,kwargs=kwargs,needed=needed):
287
+ if inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn): raise RuntimeError('async test '+name+' is not run by this runner: make it a plain function and call asyncio.run(...) inside it')
288
+ if inspect.isgeneratorfunction(fn): raise RuntimeError('generator test '+name+' is not run by this runner: its body after the first yield would never execute')
289
+ if needed: raise RuntimeError('fixture '+needed[0]+' is not available in this runner: build the value inside the test or use unittest setUp')
290
+ if owner is None: return fn(**kwargs)
291
+ target=owner()
292
+ if hasattr(target,'setup_method'): target.setup_method(fn)
293
+ try: getattr(target,fn.__name__)(**kwargs)
294
+ finally:
295
+ if hasattr(target,'teardown_method'): target.teardown_method(fn)
296
+ yield unittest.FunctionTestCase(run,description=name+('['+str(index)+']' if len(sets)>1 else ''))
297
+ def cases(module):
298
+ for name,item in sorted(vars(module).items()):
299
+ if getattr(item,'__module__',None)!=module.__name__: continue
300
+ if name.startswith('test') and inspect.isfunction(item): yield from one(name,item)
301
+ elif name.startswith('Test') and inspect.isclass(item) and not issubclass(item,unittest.TestCase):
302
+ for method,fn in sorted(vars(item).items()):
303
+ if method.startswith('test') and inspect.isfunction(fn): yield from one(name+'.'+method,fn,item)
100
304
  for i,file in enumerate(sys.argv[1:]):
101
305
  spec=importlib.util.spec_from_file_location('codali_test_'+str(i),file)
102
- module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
306
+ module=importlib.util.module_from_spec(spec);sys.modules[spec.name]=module;spec.loader.exec_module(module)
103
307
  suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
308
+ suite.addTests(cases(module))
104
309
  result=unittest.TextTestRunner(verbosity=2).run(suite)
105
310
  data={'total':result.testsRun,'failedTests':len(result.failures)+len(result.errors)+len(result.unexpectedSuccesses),'pendingTests':len(result.skipped)+len(result.expectedFailures)}
106
311
  data['passedTests']=data['total']-data['failedTests']-data['pendingTests']
@@ -121,15 +326,24 @@ sys.exit(0 if result.wasSuccessful() and data['total']>0 and data['pendingTests'
121
326
  const reportPath = path.join(root, "artifacts", "native-report.json");
122
327
  if (runner === "python") {
123
328
  const stat = await fs.lstat(reportPath).catch(() => undefined);
329
+ // A module missing from files is usually the implementation itself:
330
+ // nothing persists between calls (cycle 7: five runs sent only tests).
331
+ const absent = /ModuleNotFoundError: No module named '([A-Za-z_][\w.]*)'/.exec(output)?.[1];
332
+ const missing = absent && !args.files.some(file => [`${absent.replace(/\./g, "/")}.py`, `${absent.split(".")[0]}.py`, `${absent.split(".")[0]}/__init__.py`].includes(file.path))
333
+ ? ` Module '${absent}' is not among the files: each call starts from an empty sandbox, so if it is the code under test, include ${absent.replace(/\./g, "/")}.py in files together with the tests.` : "";
124
334
  if (!stat)
125
- throw new ToolExecutionError("tool_execution_failed", `Python tests could not start. This runner loads standard-library unittest.TestCase tests; third-party packages such as pytest are not installed. Fix the reported import/syntax error or use unittest.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
335
+ throw new ToolExecutionError("tool_execution_failed", `Python tests could not start.${missing} This runner loads unittest.TestCase classes and plain test_* functions, with a stand-in for pytest.raises, pytest.approx and pytest.mark.parametrize; other third-party packages are not installed. Fix the reported import/syntax error.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
126
336
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16000)
127
337
  throw new Error("Invalid test report");
128
338
  }
129
- const report = runner === "node" ? { total: count("tests"), passedTests: count("pass"), failedTests: count("fail"), pendingTests: count("skipped") + count("todo") + count("cancelled") }
339
+ // node:test reports a file that declares no test as one passing test
340
+ // named after the file. That is not a test case: leave it out, so a
341
+ // helper-only run is "zero tests", never a pass.
342
+ const fileLevelPasses = runner === "node" ? [...output.matchAll(/^ok \d+ - (.+?)\s*$/gm)].filter(match => testPaths.some(file => match[1] === file || match[1] === path.join(root, file) || match[1].endsWith(`/${file}`))).length : 0;
343
+ const report = runner === "node" ? { total: count("tests") - fileLevelPasses, passedTests: count("pass") - fileLevelPasses, failedTests: count("fail"), pendingTests: count("skipped") + count("todo") + count("cancelled") }
130
344
  : JSON.parse(await fs.readFile(reportPath, "utf8"));
131
345
  if (!Object.values(report).every(value => Number.isSafeInteger(value) && Number(value) >= 0) || report.total < 1)
132
- throw new ToolExecutionError("tool_execution_failed", `No complete test results were produced. Python requires unittest.TestCase methods named test_*; Node requires node:test cases. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
346
+ throw new ToolExecutionError("tool_execution_failed", `No complete test results were produced. Python requires test_* functions or unittest.TestCase methods named test_*; Node requires node:test cases declared with test(), it() or describe(); a file without them is not a test. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
133
347
  const result = { library: runner === "node" ? "node:test" : "unittest", ...report,
134
348
  passed: exitCode === 0 && report.failedTests === 0 && report.pendingTests === 0 && report.passedTests === report.total,
135
349
  diagnostic: testFailureSummary(output).slice(0, 1800), sourceSha256: createHash("sha256").update(payload).digest("hex"), elapsedMs: Date.now() - started,
@@ -140,7 +354,7 @@ sys.exit(0 if result.wasSuccessful() and data['total']>0 and data['pendingTests'
140
354
  throw new Error("Vitest runtime unavailable");
141
355
  await fs.mkdir(path.join(root, "node_modules"));
142
356
  await fs.symlink(runtime.entry, path.join(root, "node_modules", "vitest"));
143
- const config = { cacheDir: path.join(root, "artifacts", "cache"), server: { host: "127.0.0.1", hmr: false }, test: { include: ["**/*.test.{js,ts,mjs,cjs}"], environment: "node", globals: false,
357
+ const config = { cacheDir: path.join(root, "artifacts", "cache"), server: { host: "127.0.0.1", hmr: false }, test: { include: testPaths, environment: "node", globals: false,
144
358
  // macOS denies signaling separate child processes inside this sandbox.
145
359
  // Threads retain the same OS boundary without requiring signal grants.
146
360
  pool: "threads", maxWorkers: 1, fileParallelism: false, testTimeout: 1000, hookTimeout: 1000, passWithNoTests: false, reporters: ["json"], outputFile: path.join(root, "artifacts", "report.json") } };
package/package.json CHANGED
@@ -9,8 +9,8 @@
9
9
  "url": "https://github.com/bekirdag/mcoda/issues"
10
10
  },
11
11
  "dependencies": {
12
- "@mcoda/db": "0.1.135-codali.41",
13
- "@mcoda/shared": "0.1.135-codali.41",
12
+ "@mcoda/db": "0.1.135-codali.47",
13
+ "@mcoda/shared": "0.1.135-codali.47",
14
14
  "@modelcontextprotocol/sdk": "1.30.0",
15
15
  "ajv": "8.20.0",
16
16
  "browser-use": "0.9.0",
@@ -58,5 +58,5 @@
58
58
  },
59
59
  "type": "module",
60
60
  "types": "dist/index.d.ts",
61
- "version": "0.1.135-codali.41"
61
+ "version": "0.1.135-codali.47"
62
62
  }