@mcoda/mswarm 0.1.135-codali.40 → 0.1.135-codali.42

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 (80) hide show
  1. package/dist/vendor/codali/cli/TerminalCommand.js +2 -2
  2. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +1 -1
  3. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +1 -0
  4. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  5. package/dist/vendor/codali/config/OrchestrationConfig.js +8 -3
  6. package/dist/vendor/codali/docdex/DocdexClient.d.ts +11 -0
  7. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  8. package/dist/vendor/codali/docdex/DocdexClient.js +55 -1
  9. package/dist/vendor/codali/permissions/PermissionGate.d.ts +7 -0
  10. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  11. package/dist/vendor/codali/permissions/PermissionGate.js +26 -0
  12. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +2 -0
  13. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
  14. package/dist/vendor/codali/providers/ConfiguredProvider.js +29 -0
  15. package/dist/vendor/codali/providers/ModelServiceError.d.ts +2 -2
  16. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  17. package/dist/vendor/codali/providers/ModelServiceError.js +4 -0
  18. package/dist/vendor/codali/runtime/AnswerVerification.d.ts +14 -0
  19. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
  20. package/dist/vendor/codali/runtime/AnswerVerification.js +26 -0
  21. package/dist/vendor/codali/runtime/ContextCompression.d.ts +5 -0
  22. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -1
  23. package/dist/vendor/codali/runtime/ContextCompression.js +16 -4
  24. package/dist/vendor/codali/runtime/FigureCheck.d.ts +20 -0
  25. package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -0
  26. package/dist/vendor/codali/runtime/FigureCheck.js +44 -0
  27. package/dist/vendor/codali/runtime/InteractionContract.d.ts +22 -0
  28. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -1
  29. package/dist/vendor/codali/runtime/InteractionContract.js +41 -0
  30. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +3 -3
  31. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
  32. package/dist/vendor/codali/runtime/InteractionRouter.js +1 -1
  33. package/dist/vendor/codali/runtime/OutageWait.d.ts +33 -5
  34. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
  35. package/dist/vendor/codali/runtime/OutageWait.js +68 -8
  36. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +21 -1
  37. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
  38. package/dist/vendor/codali/runtime/ResearchEvidence.js +109 -3
  39. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
  40. package/dist/vendor/codali/runtime/ReviewCoordinator.js +2 -1
  41. package/dist/vendor/codali/runtime/ReviewSource.d.ts +5 -0
  42. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
  43. package/dist/vendor/codali/runtime/ReviewSource.js +6 -1
  44. package/dist/vendor/codali/runtime/SessionController.d.ts +71 -1
  45. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  46. package/dist/vendor/codali/runtime/SessionController.js +553 -39
  47. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
  48. package/dist/vendor/codali/runtime/TaskReview.js +17 -2
  49. package/dist/vendor/codali/runtime/VerificationCommand.d.ts +8 -0
  50. package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -1
  51. package/dist/vendor/codali/runtime/VerificationCommand.js +114 -0
  52. package/dist/vendor/codali/runtime/WorkingStyle.d.ts +20 -0
  53. package/dist/vendor/codali/runtime/WorkingStyle.d.ts.map +1 -0
  54. package/dist/vendor/codali/runtime/WorkingStyle.js +71 -0
  55. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  56. package/dist/vendor/codali/tools/ToolRegistry.js +19 -2
  57. package/dist/vendor/codali/tools/ToolTypes.d.ts +3 -0
  58. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
  59. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +23 -1
  60. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -1
  61. package/dist/vendor/codali/tools/browser/BrowserTool.js +83 -4
  62. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts +39 -0
  63. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts.map +1 -0
  64. package/dist/vendor/codali/tools/browser/HttpFallback.js +240 -0
  65. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +16 -1
  66. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
  67. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +147 -20
  68. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  69. package/dist/vendor/codali/tools/shell/AsyncProcess.js +6 -0
  70. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  71. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +10 -2
  72. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
  73. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
  74. package/dist/vendor/codali/tools/shell/ShellTool.js +32 -2
  75. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
  76. package/dist/vendor/codali/tools/verification/VitestTool.js +75 -5
  77. package/dist/vendor/config/skills/testing-and-verification/SKILL.md +5 -5
  78. package/dist/vendor/config/skills/webapp-testing/SKILL.md +13 -0
  79. package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +85 -0
  80. package/package.json +3 -3
@@ -4,6 +4,12 @@ import { runProcess } from "./AsyncProcess.js";
4
4
  import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
5
5
  /** Shared by terminal execution and tool-enabled benchmark baselines. */
6
6
  export const DEVELOPMENT_COMMANDS = ["git", "rg", "grep", "node", "npm", "pnpm", "npx", "python3", "pytest", "cargo", "rustc", "go", "make", "cmake", "tsc", "sh", "bash", "ls", "cat", "pwd", "expr", "printf", "head", "tail", "sed", "awk", "uname", "which", "env", "find", "wc", "sort", "uniq", "cut", "diff", "file", "stat", "du", "df", "mkdir", "touch", "cp", "mv", "rm", "curl", "wget", "tar", "unzip", "zip", "cc", "gcc", "g++", "clang", "clang++", "ar", "swift", "swiftc", "java", "javac", "xcrun", "xcodebuild", "google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
7
+ /** A fixed two minutes ended test suites and browser journeys fifteen times in
8
+ * one 12-hour build; the caller can now ask for the time a command needs. */
9
+ /** What to use when a listed command is missing on the host. */
10
+ const MISSING_ALTERNATIVES = { rg: "grep -rn (add -E for extended patterns)", fd: "find", python3: "node", pytest: "python3 -m unittest", pnpm: "npm", tsc: "npx tsc" };
11
+ export const DEFAULT_SHELL_TIMEOUT_SECONDS = 120;
12
+ export const MAX_SHELL_TIMEOUT_SECONDS = 900;
7
13
  const resolveAllowlist = (context) => {
8
14
  return context.shellAllowlist ?? [];
9
15
  };
@@ -56,6 +62,7 @@ export const createShellTool = () => ({
56
62
  args: { type: "array", items: { type: "string" } },
57
63
  cwd: { type: "string", description: "Existing working directory inside the workspace, relative to its root. Default: workspace root. Does not change the base of writePaths." },
58
64
  writePaths: { type: "array", items: { type: "string" }, description: "Terminal mode: root-relative existing files/directories to make writable, regardless of cwd. Default: no workspace writes. Must fit the claimed task scope." },
65
+ timeoutSeconds: { type: "integer", minimum: 1, maximum: MAX_SHELL_TIMEOUT_SECONDS, description: `Time allowed for this command. Default ${DEFAULT_SHELL_TIMEOUT_SECONDS}; raise it (up to ${MAX_SHELL_TIMEOUT_SECONDS}) for a full test suite, a build or a browser journey that needs longer.` },
59
66
  },
60
67
  },
61
68
  handler: async (args, context) => {
@@ -64,7 +71,10 @@ export const createShellTool = () => ({
64
71
  retryable: false,
65
72
  });
66
73
  }
67
- const { command, args: commandArgs = [], cwd } = args;
74
+ const { command, args: commandArgs = [], cwd, timeoutSeconds } = args;
75
+ if (timeoutSeconds !== undefined && (!Number.isSafeInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > MAX_SHELL_TIMEOUT_SECONDS)) {
76
+ throw new ToolExecutionError("tool_invalid_args", `timeoutSeconds must be a whole number from 1 to ${MAX_SHELL_TIMEOUT_SECONDS}`, { retryable: false });
77
+ }
68
78
  if (!context.allowDestructiveOperations
69
79
  && !context.shellIsolated
70
80
  && isDestructiveShellAction(command, commandArgs)) {
@@ -96,6 +106,26 @@ export const createShellTool = () => ({
96
106
  }
97
107
  effectiveArgs.splice(at, 0, "-o", "pipefail");
98
108
  }
99
- return (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory });
109
+ // A host may set the default (shellTimeoutMs) and the most a command may ask
110
+ // for (shellMaxTimeoutMs). A host that sets only a default keeps it as the cap.
111
+ const defaultMs = context.shellTimeoutMs ?? DEFAULT_SHELL_TIMEOUT_SECONDS * 1000;
112
+ const maxMs = context.shellMaxTimeoutMs ?? (context.shellTimeoutMs !== undefined ? context.shellTimeoutMs : MAX_SHELL_TIMEOUT_SECONDS * 1000);
113
+ const shellTimeoutMs = timeoutSeconds === undefined ? defaultMs : Math.min(timeoutSeconds * 1000, maxMs);
114
+ try {
115
+ return await (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory, shellTimeoutMs });
116
+ }
117
+ catch (error) {
118
+ // An allowed command that is not installed on this machine (rg on a host
119
+ // without ripgrep) is named as such, with what to use instead.
120
+ const missing = error instanceof ToolExecutionError ? /execvp ([\w.+-]+): No such file or directory|spawn ([\w.+-]+) ENOENT/.exec(`${error.message} ${String(error.details?.stderr ?? "")}`) : null;
121
+ if (missing) {
122
+ const name = missing[1] ?? missing[2];
123
+ throw new ToolExecutionError("tool_execution_failed", `${name} is not installed on this machine.${MISSING_ALTERNATIVES[name] ? ` Use ${MISSING_ALTERNATIVES[name]} instead.` : " Use another available command."}`, { retryable: false, details: error.details });
124
+ }
125
+ if (error instanceof ToolExecutionError && error.code === "tool_timeout" && shellTimeoutMs < maxMs) {
126
+ error.message += `\nThe command was stopped after ${Math.round(shellTimeoutMs / 1000)} s. If it needs longer, pass timeoutSeconds (up to ${Math.floor(maxMs / 1000)}); start servers in the background so the call can return.`;
127
+ }
128
+ throw error;
129
+ }
100
130
  },
101
131
  });
@@ -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":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAiFF,eAAO,MAAM,gBAAgB,QAAO,cAsIlC,CAAC"}
@@ -60,9 +60,48 @@ async function runnerRuntime() {
60
60
  throw Error("Vitest runtime does not match the pinned version");
61
61
  return { entry, version, mounts: [...mounts] };
62
62
  }
63
+ /** Standard-library stand-in for the part of pytest that generated tests use. */
64
+ const PYTEST_STAND_IN = `import math,re
65
+ class _Raises:
66
+ def __init__(self,expected,match=None): self.expected=expected; self.match=match; self.value=None
67
+ def __enter__(self): return self
68
+ def __exit__(self,kind,value,trace):
69
+ if kind is None: raise AssertionError('DID NOT RAISE '+str(self.expected))
70
+ if not issubclass(kind,self.expected): return False
71
+ 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))
72
+ self.value=value; return True
73
+ def raises(expected,*args,match=None,**kwargs):
74
+ if args:
75
+ with _Raises(expected,match): args[0](*args[1:],**kwargs)
76
+ return None
77
+ return _Raises(expected,match)
78
+ class approx:
79
+ 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
80
+ def _one(self,actual,expected): return math.isclose(actual,expected,rel_tol=self.rel,abs_tol=self.abs)
81
+ def __eq__(self,actual):
82
+ e=self.expected
83
+ 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)
84
+ if isinstance(e,(list,tuple)): return len(actual)==len(e) and all(self._one(a,b) for a,b in zip(actual,e))
85
+ return self._one(actual,e)
86
+ def __ne__(self,actual): return not self.__eq__(actual)
87
+ def __repr__(self): return 'approx('+repr(self.expected)+')'
88
+ def fail(reason=''): raise AssertionError(reason)
89
+ class _Mark:
90
+ def parametrize(self,names,values,**ignored):
91
+ keys=[n.strip() for n in names.split(',')] if isinstance(names,str) else list(names)
92
+ def wrap(fn):
93
+ rows=[tuple(v) if len(keys)>1 else (v,) for v in values]
94
+ earlier=getattr(fn,'_codali_params',[()]); earlier_names=getattr(fn,'_codali_names',())
95
+ fn._codali_params=[tuple(r)+tuple(e) for r in rows for e in earlier]; fn._codali_names=tuple(keys)+tuple(earlier_names)
96
+ return fn
97
+ return wrap
98
+ def __getattr__(self,name): raise AttributeError('pytest.mark.'+name+' is not available in this runner; only parametrize is')
99
+ mark=_Mark()
100
+ 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')
101
+ `;
63
102
  export const createVitestTool = () => ({
64
103
  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.",
104
+ 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 (pytest.raises/approx/parametrize only; no fixtures, async tests or plugins). Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
66
105
  inputSchema: { type: "object", properties: { runner: { type: "string", enum: ["vitest", "node", "python"] }, files: { type: "array", minItems: 1, maxItems: 12, items: { type: "object", properties: {
67
106
  path: { type: "string", minLength: 1, maxLength: 160 }, content: { type: "string", maxLength: 24000 },
68
107
  }, required: ["path", "content"], additionalProperties: false } } }, required: ["files"], additionalProperties: false },
@@ -94,13 +133,44 @@ export const createVitestTool = () => ({
94
133
  await fs.mkdir(path.join(root, "artifacts"));
95
134
  if (runner !== "vitest") {
96
135
  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
136
+ // Models write pytest-style tests (plain test_* functions, pytest.raises,
137
+ // approx, parametrize) far more often than unittest classes; cycle 6 lost
138
+ // twelve test runs to "pytest is not installed". A small stand-in covers
139
+ // that subset on the standard library; anything else says so by name.
140
+ if (runner === "python" && !args.files.some(file => file.path === "pytest.py" || file.path.startsWith("pytest/")))
141
+ await fs.writeFile(path.join(root, "pytest.py"), PYTEST_STAND_IN);
142
+ const python = `import unittest,sys,os,json,importlib.util,inspect
98
143
  sys.path.insert(0,os.getcwd())
99
144
  suite=unittest.TestSuite()
145
+ def one(name,fn,owner=None):
146
+ sets=getattr(fn,'_codali_params',[()])
147
+ for index,values in enumerate(sets):
148
+ names=getattr(fn,'_codali_names',())
149
+ kwargs=dict(zip(names,values))
150
+ needed=[p for p in inspect.signature(fn).parameters if p not in kwargs and p!='self']
151
+ def run(fn=fn,kwargs=kwargs,needed=needed):
152
+ 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')
153
+ if inspect.isgeneratorfunction(fn): raise RuntimeError('generator test '+name+' is not run by this runner: its body after the first yield would never execute')
154
+ if needed: raise RuntimeError('fixture '+needed[0]+' is not available in this runner: build the value inside the test or use unittest setUp')
155
+ if owner is None: return fn(**kwargs)
156
+ target=owner()
157
+ if hasattr(target,'setup_method'): target.setup_method(fn)
158
+ try: getattr(target,fn.__name__)(**kwargs)
159
+ finally:
160
+ if hasattr(target,'teardown_method'): target.teardown_method(fn)
161
+ yield unittest.FunctionTestCase(run,description=name+('['+str(index)+']' if len(sets)>1 else ''))
162
+ def cases(module):
163
+ for name,item in sorted(vars(module).items()):
164
+ if getattr(item,'__module__',None)!=module.__name__: continue
165
+ if name.startswith('test') and inspect.isfunction(item): yield from one(name,item)
166
+ elif name.startswith('Test') and inspect.isclass(item) and not issubclass(item,unittest.TestCase):
167
+ for method,fn in sorted(vars(item).items()):
168
+ if method.startswith('test') and inspect.isfunction(fn): yield from one(name+'.'+method,fn,item)
100
169
  for i,file in enumerate(sys.argv[1:]):
101
170
  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)
171
+ module=importlib.util.module_from_spec(spec);sys.modules[spec.name]=module;spec.loader.exec_module(module)
103
172
  suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
173
+ suite.addTests(cases(module))
104
174
  result=unittest.TextTestRunner(verbosity=2).run(suite)
105
175
  data={'total':result.testsRun,'failedTests':len(result.failures)+len(result.errors)+len(result.unexpectedSuccesses),'pendingTests':len(result.skipped)+len(result.expectedFailures)}
106
176
  data['passedTests']=data['total']-data['failedTests']-data['pendingTests']
@@ -122,14 +192,14 @@ sys.exit(0 if result.wasSuccessful() and data['total']>0 and data['pendingTests'
122
192
  if (runner === "python") {
123
193
  const stat = await fs.lstat(reportPath).catch(() => undefined);
124
194
  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 } });
195
+ throw new ToolExecutionError("tool_execution_failed", `Python tests could not start. 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
196
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16000)
127
197
  throw new Error("Invalid test report");
128
198
  }
129
199
  const report = runner === "node" ? { total: count("tests"), passedTests: count("pass"), failedTests: count("fail"), pendingTests: count("skipped") + count("todo") + count("cancelled") }
130
200
  : JSON.parse(await fs.readFile(reportPath, "utf8"));
131
201
  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 } });
202
+ 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. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
133
203
  const result = { library: runner === "node" ? "node:test" : "unittest", ...report,
134
204
  passed: exitCode === 0 && report.failedTests === 0 && report.pendingTests === 0 && report.passedTests === report.total,
135
205
  diagnostic: testFailureSummary(output).slice(0, 1800), sourceSha256: createHash("sha256").update(payload).digest("hex"), elapsedMs: Date.now() - started,
@@ -3,14 +3,14 @@ name: testing-and-verification
3
3
  description: "Verify software with real unit, integration, contract and UI checks."
4
4
  ---
5
5
 
6
- Inspect requirements, exports, tests, scripts and runtime before writing tests; never invent API names. Derive expected results independently from requirements, not from implementation. Cover boundaries, empties, ties/order, duplicates, cancellation/rejections, units and rounding. For stateful rules, test invalid-to-valid sequences; a rejected step must not corrupt later valid behavior unless specified. Resolve contradictory model-written expectations from the original requirement.
6
+ Inspect requirements, exports, tests, scripts and runtime before writing tests; never invent API names. Derive expected results independently from requirements, not from implementation. Cover boundaries, empties, ties/order, duplicates, cancellation, units and rounding. For stateful rules, test invalid-to-valid sequences; a rejected step must not corrupt later valid behavior unless specified. Resolve contradictory model-written expectations from the original requirement.
7
7
 
8
- Reproduce bugs with isolated fixtures and the repository runner. Missing dependencies are not reproductions. Discover tool schemas. Node --test uses default discovery or explicit test files; a directory argument is not portable test discovery. For supplied Python answers, verify_tests runner python supports standard-library unittest.TestCase, not pytest.
8
+ Reproduce bugs with isolated fixtures and the repository runner. Missing dependencies are not reproductions. Node --test uses default discovery or explicit test files; a directory argument is not portable test discovery. verify_tests python runs unittest and plain test_* functions with pytest.raises/approx/parametrize, no fixtures.
9
9
 
10
- For apps, exercise the actual setup, build, entrypoint and a real user journey, not just helper tests. Verify persisted seed state, restart persistence, authorization, invalid input, duplicate requests, rollback and concurrency. Before a negative authorization test, prove authentication, fixture existence and a permitted operation succeed. A missing route returning 404 proves nothing about tenant isolation. Zero tests, syntax-only checks, no-op scripts and placeholder UI do not prove domain functionality.
10
+ For apps, exercise the actual setup, build, entrypoint and a real user journey, not just helper tests. Verify persisted seed state, restart persistence, authorization, invalid input, duplicate requests, rollback and concurrency. Before a negative authorization test, prove authentication, fixture existence and a permitted operation succeed. A missing route returning 404 proves nothing about tenant isolation. Zero tests, syntax-only checks, no-op scripts and placeholder UI prove nothing.
11
11
 
12
- Use webapp-testing for rendered interaction: loading/error/empty states, keyboard operation and responsive layout. Temporary servers and checks can share one shell call; persistent previews need managed services. Sandbox writes must fit claimed paths.
12
+ Use webapp-testing for rendered interaction: loading/error/empty states, keyboard operation, layout. For a browser journey load webapp-testing first: it ships a tested Chrome driver; write only the steps. Temporary servers and checks share one shell call (set timeoutSeconds); previews need managed services. Sandbox writes must fit claimed paths.
13
13
 
14
- Record commands, environment, exit status and output. Distinguish passed, failed, skipped and untested. Diagnose before rerunning; never loop unchanged checks or weaken requirements. Expand checks only for unresolved impact/risk. Attach actual receipts to work_verify. Provide reproducible start/test instructions and disclose infrastructure or platform blockers. Model-authored passing tests are limited evidence, not independent proof of completion.
14
+ Record commands, exit status and output. Separate passed, failed, skipped, untested. Diagnose before rerunning; never loop unchanged checks or weaken requirements. Expand checks only for unresolved impact/risk. Attach actual receipts to work_verify. Give reproducible start/test instructions; disclose platform blockers. Model-authored passing tests are limited evidence, not independent proof of completion.
15
15
 
16
16
  Source: https://raw.githubusercontent.com/obra/superpowers/main/skills/test-driven-development/SKILL.md. Adaptation without blanket approval or test-first mandates.
@@ -7,6 +7,19 @@ Read the application entry point and package scripts before choosing a launch me
7
7
 
8
8
  For a backend, use its existing managed service or an authorized host service workflow. A temporary run_shell server can support checks within that single call, but cannot provide a persistent demo URL.
9
9
 
10
+ Browser journey of an app with a backend: do not write a browser driver. Read this skill's journey-driver.mjs with skill_read (path journey-driver.mjs, follow nextOffset to the end) and save it unchanged in the project's test folder. It needs Node 22 and an installed Chrome or Chromium, and no packages. Then write one short script that does everything in a single run_shell call, because processes do not survive the call:
11
+
12
+ import { launch, startServer } from './journey-driver.mjs';
13
+ const server = await startServer('node', ['server/index.js'], { url: 'http://127.0.0.1:3000/health', env: { PORT: '3000' } });
14
+ const page = await launch();
15
+ try {
16
+ await page.goto('http://127.0.0.1:3000/');
17
+ await page.type('#email', 'admin@example.test'); await page.type('#password', 'correct horse');
18
+ await page.click('button[type=submit]'); await page.waitForText('Dashboard');
19
+ } finally { await page.close(); server.kill(); }
20
+
21
+ The page object has goto, click, type, text, waitForSelector, waitForText, waitFor (any expression), evaluate and screenshot. A wait that fails reports what the page shows instead. Print PASS or FAIL per scenario and exit non-zero on a failure. Run it with run_shell and timeoutSeconds sized to the journey (for example 300). Use data-testid or id selectors you put in the markup yourself.
22
+
10
23
  Inspect rendered page state before selecting controls. Exercise the requested user journey, verify visible outcomes, and run the project's real tests separately. A successful HTTP fetch does not prove interactivity. Record the tested URL and observed results; identify untested behavior.
11
24
 
12
25
  Source: https://github.com/anthropics/skills/blob/main/skills/webapp-testing/SKILL.md. Original Codali adaptation of its inspect-before-action workflow; no upstream scripts bundled.
@@ -0,0 +1,85 @@
1
+ // journey-driver.mjs: drive headless Chrome over its debugging protocol.
2
+ // No dependencies; Node 22 or newer. Copy it into the project's test folder.
3
+ import { spawn } from 'node:child_process';
4
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+
8
+ export const sleep = ms => new Promise(r => setTimeout(r, ms));
9
+
10
+ /** Start the app and wait until `url` answers. Kill the returned process when done. */
11
+ export async function startServer(command, args, { url, env = {}, ms = 20000 } = {}) {
12
+ const proc = spawn(command, args, { stdio: 'inherit', env: { ...process.env, ...env } });
13
+ for (const end = Date.now() + ms; ;) {
14
+ try { await fetch(url); return proc; } catch {}
15
+ if (proc.exitCode !== null) throw new Error('Server exited before it answered');
16
+ if (Date.now() > end) { proc.kill(); throw new Error(`Server not reachable at ${url}`); }
17
+ await sleep(100);
18
+ }
19
+ }
20
+
21
+ /** Launch Chrome and return page controls. Every wait fails with a clear message. */
22
+ export async function launch({ chrome = process.env.CHROME_BIN } = {}) {
23
+ const dir = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'journey-'));
24
+ // Port 0: Chrome picks a free port and writes it to DevToolsActivePort, so
25
+ // two journeys on one machine never attach to each other's browser.
26
+ const flags = ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run',
27
+ '--remote-debugging-port=0', `--user-data-dir=${dir}`, 'about:blank'];
28
+ let proc;
29
+ for (const bin of [chrome, 'google-chrome', 'chromium', 'chromium-browser'].filter(Boolean)) {
30
+ const candidate = spawn(bin, flags, { stdio: 'ignore' });
31
+ if (await new Promise(r => { candidate.once('error', () => r(false)); setTimeout(() => r(true), 300); })) { proc = candidate; break; }
32
+ }
33
+ if (!proc) throw new Error('No Chrome or Chromium executable found');
34
+ let target;
35
+ for (let i = 0; i < 150 && !target; i++) {
36
+ try {
37
+ const port = Number(readFileSync(join(dir, 'DevToolsActivePort'), 'utf8').split('\n')[0]);
38
+ target = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).find(t => t.type === 'page');
39
+ } catch {}
40
+ if (!target) await sleep(100);
41
+ }
42
+ if (!target) { proc.kill(); throw new Error('Chrome did not open its debugging port'); }
43
+ const ws = new WebSocket(target.webSocketDebuggerUrl);
44
+ await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('Debugging socket failed')); });
45
+ let id = 0;
46
+ const pending = new Map();
47
+ ws.onmessage = e => {
48
+ const m = JSON.parse(e.data), p = pending.get(m.id);
49
+ if (p) { pending.delete(m.id); m.error ? p.rej(new Error(m.error.message)) : p.res(m.result); }
50
+ };
51
+ const cdp = (method, params = {}) => new Promise((res, rej) => { pending.set(++id, { res, rej }); ws.send(JSON.stringify({ id, method, params })); });
52
+ await cdp('Page.enable'); await cdp('Runtime.enable');
53
+ const evaluate = async expression => {
54
+ const r = await cdp('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
55
+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text);
56
+ return r.result.value;
57
+ };
58
+ const waitFor = async (expression, what = expression, ms = 5000) => {
59
+ for (const end = Date.now() + ms; ;) {
60
+ const value = await evaluate(expression).catch(() => undefined);
61
+ if (value) return value;
62
+ if (Date.now() > end) throw new Error(`Timed out waiting for ${what}; page shows: ${String(await evaluate('document.body?.innerText ?? ""').catch(() => '')).slice(0, 300)}`);
63
+ await sleep(50);
64
+ }
65
+ };
66
+ const q = s => `document.querySelector(${JSON.stringify(s)})`;
67
+ return {
68
+ cdp, evaluate, waitFor,
69
+ goto: async url => { await cdp('Page.navigate', { url }); await waitFor('document.readyState === "complete"', `load of ${url}`, 10000); },
70
+ waitForSelector: (s, ms) => waitFor(`!!${q(s)}`, `selector ${s}`, ms),
71
+ waitForText: (t, ms) => waitFor(`!!document.body && document.body.innerText.includes(${JSON.stringify(t)})`, `text "${t}"`, ms),
72
+ click: async s => { await waitFor(`!!${q(s)}`, `selector ${s}`); await evaluate(`${q(s)}.click()`); },
73
+ // Sets the value the way a framework expects, then fires input and change.
74
+ type: async (s, text) => {
75
+ await waitFor(`!!${q(s)}`, `selector ${s}`);
76
+ await evaluate(`(() => { const e = ${q(s)}; e.focus();
77
+ const set = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e), 'value')?.set;
78
+ set ? set.call(e, ${JSON.stringify(text)}) : (e.value = ${JSON.stringify(text)});
79
+ e.dispatchEvent(new Event('input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); })()`);
80
+ },
81
+ text: (s = 'body') => evaluate(`${q(s)}?.innerText ?? ''`),
82
+ screenshot: async () => Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'),
83
+ close: async () => { try { ws.close(); } catch {} proc.kill(); await sleep(150); rmSync(dir, { recursive: true, force: true }); },
84
+ };
85
+ }
package/package.json CHANGED
@@ -8,8 +8,8 @@
8
8
  "url": "https://github.com/bekirdag/mcoda/issues"
9
9
  },
10
10
  "dependencies": {
11
- "@mcoda/db": "0.1.135-codali.40",
12
- "@mcoda/shared": "0.1.135-codali.40",
11
+ "@mcoda/db": "0.1.135-codali.42",
12
+ "@mcoda/shared": "0.1.135-codali.42",
13
13
  "@modelcontextprotocol/sdk": "1.30.0",
14
14
  "ajv": "8.20.0",
15
15
  "browser-use": "0.9.0",
@@ -67,5 +67,5 @@
67
67
  },
68
68
  "type": "module",
69
69
  "types": "dist/server.d.ts",
70
- "version": "0.1.135-codali.40"
70
+ "version": "0.1.135-codali.42"
71
71
  }