@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -0,0 +1,121 @@
1
+ const LIMITS = Object.freeze({ trials: 500, steps: 500, actions: 1000, replay: 20000 });
2
+
3
+ function integer(name, value, maximum) {
4
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {
5
+ throw new RangeError(name + ' must be an integer between 0 and ' + maximum);
6
+ }
7
+ return value;
8
+ }
9
+
10
+ function failure(value) {
11
+ if (value && typeof value.then === 'function') throw new TypeError('Async invariants are not supported');
12
+ return value === true ? null : (typeof value === 'string' ? value : 'Invariant returned false');
13
+ }
14
+
15
+ function nextRandom(state) {
16
+ let value = state.value >>> 0;
17
+ value ^= value << 13;
18
+ value ^= value >>> 17;
19
+ value ^= value << 5;
20
+ state.value = value >>> 0;
21
+ return state.value;
22
+ }
23
+
24
+ function runPath(initial, transition, invariant, path) {
25
+ let state;
26
+ try {
27
+ state = initial();
28
+ if (state && typeof state.then === 'function') {
29
+ throw new TypeError('Async initial state is not supported');
30
+ }
31
+ } catch (error) {
32
+ return { failed: true, reason: String(error?.message || error), step: -1 };
33
+ }
34
+ try {
35
+ const error = failure(invariant(state));
36
+ if (error) return { failed: true, reason: error, step: -1 };
37
+ } catch (error) {
38
+ return { failed: true, reason: String(error?.message || error), step: -1 };
39
+ }
40
+ for (let i = 0; i < path.length; i++) {
41
+ try {
42
+ const action = structuredClone(path[i]);
43
+ const next = transition(state, action);
44
+ if (next && typeof next.then === 'function') throw new TypeError('Async transitions are not supported');
45
+ if (next !== undefined) state = next;
46
+ const error = failure(invariant(state));
47
+ if (error) return { failed: true, reason: error, step: i };
48
+ } catch (error) {
49
+ return { failed: true, reason: String(error?.message || error), step: i };
50
+ }
51
+ }
52
+ return { failed: false, reason: null, step: path.length };
53
+ }
54
+
55
+ function shrinkPath(path, fails, budget) {
56
+ let current = path.slice();
57
+ let chunk = Math.ceil(current.length / 2);
58
+ while (chunk > 0 && budget.left > 0) {
59
+ let changed = false;
60
+ for (let offset = 0; offset < current.length && budget.left > 0; offset += chunk) {
61
+ const candidate = current.slice(0, offset).concat(current.slice(offset + chunk));
62
+ budget.left--;
63
+ if (fails(candidate)) {
64
+ current = candidate;
65
+ changed = true;
66
+ break;
67
+ }
68
+ }
69
+ if (!changed) chunk = Math.floor(chunk / 2);
70
+ }
71
+ return current;
72
+ }
73
+
74
+ /**
75
+ * Deterministic bounded property exploration for real transition handlers.
76
+ * Pass a fresh initial() per replay; never report a bounded pass as a proof.
77
+ */
78
+ export function verifyActionSequences(options = {}) {
79
+ const { initial, transition, invariant, actions } = options;
80
+ if (typeof initial !== 'function' || typeof transition !== 'function'
81
+ || typeof invariant !== 'function') {
82
+ throw new TypeError('initial, transition, and invariant must be functions');
83
+ }
84
+ if (!Array.isArray(actions) || actions.length === 0 || actions.length > LIMITS.actions) {
85
+ throw new RangeError('actions must be a nonempty bounded array');
86
+ }
87
+ const seed = integer('seed', options.seed ?? 1, 0xffffffff);
88
+ const trials = integer('trials', options.trials ?? 100, LIMITS.trials);
89
+ const maxSteps = integer('maxSteps', options.maxSteps ?? 32, LIMITS.steps);
90
+ if (trials === 0) throw new RangeError('trials must be positive');
91
+ const random = { value: seed === 0 ? 0x6d2b79f5 : seed };
92
+ let executed = 0;
93
+
94
+ for (let trial = 0; trial < trials; trial++) {
95
+ const path = [];
96
+ for (let step = 0; step < maxSteps; step++) {
97
+ path.push(actions[nextRandom(random) % actions.length]);
98
+ }
99
+ executed += path.length;
100
+ const observed = runPath(initial, transition, invariant, path);
101
+ if (!observed.failed) continue;
102
+ const originalTrace = path.slice(0, Math.max(0, observed.step + 1));
103
+ const budget = { left: LIMITS.replay };
104
+ const trace = shrinkPath(originalTrace, candidate => {
105
+ const result = runPath(initial, transition, invariant, candidate);
106
+ return result.failed && result.reason === observed.reason;
107
+ }, budget);
108
+ const minimized = runPath(initial, transition, invariant, trace);
109
+ return {
110
+ status: 'counterexample', seed, trial, maxSteps, trialsRun: trial + 1,
111
+ transitionsGenerated: executed, trace, originalTrace,
112
+ reason: minimized.reason, shrinkReplays: LIMITS.replay - budget.left,
113
+ evidence: 'replayable transition-handler counterexample, not a formal proof'
114
+ };
115
+ }
116
+ return {
117
+ status: 'bounded-pass', seed, trialsRun: trials, maxSteps,
118
+ transitionsGenerated: executed,
119
+ evidence: 'deterministic seeded action-sequence sampling only; not exhaustive or a formal proof'
120
+ };
121
+ }
@@ -0,0 +1,125 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const DRIVER = String.raw`
6
+ import base64, json, os, pty, select, signal, sys, time
7
+ cfg=json.loads(sys.argv[1])
8
+ pid,fd=pty.fork()
9
+ if pid==0:
10
+ os.chdir(cfg["cwd"])
11
+ os.execvpe(cfg["argv"][0],cfg["argv"],os.environ)
12
+ start=time.monotonic()
13
+ sent=not bool(cfg["input"])
14
+ closed=False
15
+ done=False
16
+ status=None
17
+ overflow=False
18
+ out=bytearray()
19
+ while True:
20
+ elapsed=time.monotonic()-start
21
+ if not sent and elapsed>=cfg["delay"]/1000:
22
+ if cfg["input"]:
23
+ try: os.write(fd,base64.b64decode(cfg["input"]))
24
+ except OSError: pass
25
+ sent=True
26
+ readable,_,_=select.select([fd],[],[],0.04)
27
+ if readable and not closed:
28
+ try: chunk=os.read(fd,8192)
29
+ except OSError: chunk=b""
30
+ if not chunk: closed=True
31
+ else:
32
+ remaining=cfg["limit"]-len(out)
33
+ if len(chunk)>remaining: overflow=True
34
+ out.extend(chunk[:max(0,remaining)])
35
+ if not done:
36
+ got,info=os.waitpid(pid,os.WNOHANG)
37
+ if got:
38
+ done=True
39
+ status=os.waitstatus_to_exitcode(info)
40
+ if done and closed: break
41
+ if elapsed>cfg["timeout"]/1000:
42
+ if not done:
43
+ try: os.killpg(pid,signal.SIGKILL)
44
+ except ProcessLookupError: pass
45
+ got,info=os.waitpid(pid,0)
46
+ status=os.waitstatus_to_exitcode(info)
47
+ done=True
48
+ break
49
+ os.write(1,bytes(out))
50
+ os.write(2,("PTY_RESULT:"+json.dumps({"exit":status,"timeout":elapsed>cfg["timeout"]/1000,"truncated":overflow,"inputSent":sent})+"\n").encode())
51
+ `;
52
+
53
+ function resolveCommand(workspace, program) {
54
+ const base = realpathSync(workspace);
55
+ if (program === 'node') return process.execPath;
56
+ if (typeof program !== 'string' || !path.isAbsolute(program)) {
57
+ throw new Error('Only node or an absolute workspace executable is permitted');
58
+ }
59
+ const resolved = realpathSync(program);
60
+ const relative = path.relative(base, resolved);
61
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
62
+ throw new Error('Executable must be inside workspace');
63
+ }
64
+ return resolved;
65
+ }
66
+
67
+ export async function runPtyProbe(options = {}) {
68
+ const { workspace, program = 'node', args = [], input = '', contains = null,
69
+ timeoutMs = 5000, inputDelayMs = 100, outputLimit = 65536,
70
+ expectedExitCode = 0 } = options;
71
+ if (typeof workspace !== 'string' || !Array.isArray(args)
72
+ || !args.every(a => typeof a === 'string') || typeof input !== 'string') {
73
+ throw new TypeError('workspace, argv, and input must be valid strings');
74
+ }
75
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 60000
76
+ || !Number.isSafeInteger(inputDelayMs) || inputDelayMs < 0 || inputDelayMs >= timeoutMs
77
+ || !Number.isSafeInteger(outputLimit) || outputLimit < 128 || outputLimit > 1048576) {
78
+ throw new RangeError('Invalid PTY probe limits');
79
+ }
80
+ if (!Number.isInteger(expectedExitCode) || expectedExitCode < 0 || expectedExitCode > 255
81
+ || (contains !== null && (typeof contains !== 'string' || contains.length > 1024))) {
82
+ throw new TypeError('Invalid PTY probe assertion');
83
+ }
84
+ const cwd = realpathSync(workspace);
85
+ const executable = resolveCommand(workspace, program);
86
+ if (process.platform === 'win32') {
87
+ return { status: 'unavailable', success: false,
88
+ reason: 'Windows ConPTY adapter is not installed', surface: 'none' };
89
+ }
90
+ const config = { cwd, argv: [executable, ...args],
91
+ input: Buffer.from(input).toString('base64'), delay: inputDelayMs,
92
+ timeout: timeoutMs, limit: outputLimit };
93
+ return new Promise(resolve => {
94
+ let stdout = '';
95
+ let stderr = '';
96
+ let spawnedError = null;
97
+ const child = spawn('python3', ['-c', DRIVER, JSON.stringify(config)], {
98
+ cwd, shell: false, windowsHide: true,
99
+ stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, CAUSYNE_VERIFY_PROBE: '1' }
100
+ });
101
+ child.stdout.on('data', bytes => { stdout += bytes.toString('utf8'); });
102
+ child.stderr.on('data', bytes => { stderr += bytes.toString('utf8'); });
103
+ child.on('error', error => { spawnedError = String(error.message || error); });
104
+ child.on('close', () => {
105
+ if (spawnedError && /ENOENT/.test(spawnedError)) {
106
+ resolve({ status: 'unavailable', success: false, surface: 'none',
107
+ reason: 'python3 is required for POSIX PTY verification' });
108
+ return;
109
+ }
110
+ const marker = stderr.match(/PTY_RESULT:(\{[^\n]+\})/);
111
+ let detail;
112
+ try { detail = marker ? JSON.parse(marker[1]) : null; } catch { detail = null; }
113
+ const success = Boolean(detail && !detail.timeout && !detail.truncated
114
+ && detail.exit === expectedExitCode && detail.inputSent
115
+ && (contains === null || stdout.includes(contains)));
116
+ resolve({ status: success ? 'observed-pass' : 'observed-fail', success,
117
+ surface: detail ? 'posix-pty' : 'unverified', stdout,
118
+ stderr: stderr.replace(/PTY_RESULT:\{[^\n]+\}\n?/, ''),
119
+ exitCode: detail?.exit ?? null, timedOut: detail?.timeout ?? null,
120
+ truncated: detail?.truncated ?? null, inputSent: detail?.inputSent ?? false,
121
+ reason: detail ? null : (spawnedError || 'PTY driver produced no valid exit evidence'),
122
+ limitation: 'PTY verifies terminal input/output, not desktop pixels or host mouse settings' });
123
+ });
124
+ });
125
+ }
@@ -0,0 +1 @@
1
+ export declare const VERIFICATION_SKILLS: Readonly<Record<string, { name: string; description: string; content: string }>>;
@@ -0,0 +1,60 @@
1
+ export const VERIFICATION_SKILLS = Object.freeze({
2
+ 'runtime-verification': {
3
+ name: 'runtime-verification',
4
+ description: 'Drive a real app or CLI and collect repeatable evidence. Use after UI, CLI, browser, or desktop changes before claiming completion.',
5
+ content: `# Runtime verification
6
+ 1. Identify one user-visible behavior and the actual launch command in the active workspace. Do not assume the Causyne repository is the workspace.
7
+ 2. Run the build and existing tests first. Launch the real binary or local app using sysRun and the current workspace scope.
8
+ 3. For a CLI, supply a real input and inspect the exit status and output. For a TUI, call runPtyProbe from src/verification/ptyProbe.js on POSIX when python3 is available. Treat unavailable as unverified; pipes do not establish terminal mouse or rendering behavior.
9
+ 4. For a web app, use browser_act for navigation, snapshot, and screenshot. For a desktop app, use computer_use and explicit screenshot/inspection tools. Do not invent an "app aria-click" command.
10
+ 5. Record the action, observed result, expected result, and artifact location. A screenshot alone does not prove the action took place. If an adapter or approval is unavailable, report unverified.
11
+ 6. Close the launched process, and ensure transient resources are released.
12
+ ## Verification
13
+ - Done when: the real user path was exercised, the assertion matched observed evidence, and cleanup succeeded. Build-only passes must be labeled build-only.`
14
+ },
15
+ 'formal-verification': {
16
+ name: 'formal-verification',
17
+ description: 'Check state-machine invariants, retries, and asynchronous races. Use when tests do not cover all important event orders.',
18
+ content: `# Formal verification
19
+ 1. Choose a concrete safety property from code and identify the production transition functions. Model only states and actions supported by the implementation.
20
+ 2. For small finite state spaces, run exhaustive bounded exploration on the production transition function. Record the depth, explored states, and assumptions.
21
+ 3. For cross-process interleavings, use an installed TLA+ TLC checker with a version-pinned model. For unbounded data properties, consider an installed Lean verifier. Never silently download a binary or assume Lean is installed.
22
+ 4. Run a deliberately broken variant in a scratch workspace to prove the invariant detects the bug. Restore the original and rerun.
23
+ 5. Present the shortest counterexample as real actions. Never call bounded model exploration an unbounded proof or imply a TLA+ model proves the TypeScript implementation.
24
+ ## Verification
25
+ - Done when: the check was actually executed, catches a deliberately failing case, and passes or reports a reproducible counterexample on unchanged production code.`
26
+ },
27
+ 'ui-property-testing': {
28
+ name: 'ui-property-testing',
29
+ description: 'Explore UI state and input sequences including long random-looking text, resize, and session changes. Use for regressions in chat or navigation.',
30
+ content: `# UI property testing
31
+ 1. Define user-observable invariants for the current interface: text stays within viewport width, hover cannot mutate messages, Escape closes only the intended layer, and scrolling never escapes the active surface.
32
+ 2. Use verifyActionSequences from src/verification/propertyProbe.js with a fresh state factory, seeded actions and real event handlers. Report the finite trials and shortened counterexample; a bounded pass is not a proof.
33
+ 3. Execute the real UI reducer or input handler for each sequence; use a PTY for claims about terminal behavior and browser_act for browser visuals.
34
+ 4. Save the shortest failing sequence and seed. Rerun the original sequence after a fix; do not lower the assertion to make it pass.
35
+ ## Verification
36
+ - Done when: the failing path was reproduced and is now a regression test, or the bounded sequence count and unverified host dependencies were reported.`
37
+ },
38
+ 'statechart-verification': {
39
+ name: 'statechart-verification',
40
+ description: 'Explain and validate reachable states for queues, approvals, retries, and UI overlays. Use for state-dependent behavior with invalid transitions.',
41
+ content: `# Statechart verification
42
+ 1. Locate the real reducer or transition map. List states, events, guards, and actions from code.
43
+ 2. Define forbidden states and transitions. Use bounded breadth-first exploration to reach every modeled state within the chosen bounds.
44
+ 3. Run npm run verify:statechart to render the bounded JavaScript panel model, and npm run verify:statechart -- --broken to confirm a counterexample can be found. This graph is not a TLC proof. Where a pinned TLA+ checker exists, separately run npm run verify:tla and report its status explicitly.
45
+ 4. Report shortest paths to violations; do not invent events or conflate a diagram with an executable verification result.
46
+ ## Verification
47
+ - Done when: each displayed transition has a code mapping and all reported counterexamples reproduce under the stated conditions.`
48
+ },
49
+ 'verification-maintenance': {
50
+ name: 'verification-maintenance',
51
+ description: 'Update runtime and formal checks after touched code changes. Use when prior passing evidence may no longer describe the current implementation.',
52
+ content: `# Verification maintenance
53
+ 1. Compare changed source files against tests, runtime evidence and model-covered functions.
54
+ 2. Invalidate prior evidence after behavior-changing edits. Reproduce the user path again, rather than reusing old screenshots, status flags, or test output.
55
+ 3. Execute affected tests, build, and the appropriate runtime or bounded formal checks; distinguish missing tools from successful checks.
56
+ 4. Preserve user scope, existing permissions, and unrelated files. Do not generate public documentation or commit private run reports.
57
+ ## Verification
58
+ - Done when: all relevant checks were rerun against the present commit and missing validation is clearly marked, not silently treated as success.`
59
+ }
60
+ });
@@ -0,0 +1,143 @@
1
+ const DEFAULT_MAX_STATES = 256;
2
+ const DEFAULT_MAX_DEPTH = 7;
3
+
4
+ function finiteBound(value, fallback, maximum, label) {
5
+ const bound = value === undefined ? fallback : value;
6
+ if (!Number.isSafeInteger(bound) || bound < 0 || bound > maximum) {
7
+ throw new RangeError('Invalid ' + label);
8
+ }
9
+ return bound;
10
+ }
11
+
12
+ function clone(value) {
13
+ try {
14
+ return structuredClone(value);
15
+ } catch {
16
+ throw new TypeError('State and actions must be structured-cloneable');
17
+ }
18
+ }
19
+
20
+ function textLabel(value, limit = 80) {
21
+ const cleaned = String(value ?? '')
22
+ .replace(/[\x00-\x1f\x7f<>"\x60\\|[\]{};#]/g, ' ')
23
+ .replace(/\s+/g, ' ')
24
+ .trim();
25
+ return (cleaned || 'unnamed').slice(0, limit);
26
+ }
27
+
28
+ function callSync(fn, value, label) {
29
+ const result = fn(clone(value));
30
+ if (result && typeof result.then === 'function') {
31
+ throw new TypeError('Async ' + label + ' is not supported');
32
+ }
33
+ return result;
34
+ }
35
+
36
+ function assertion(invariant, state) {
37
+ const value = callSync(invariant, state, 'invariant');
38
+ return value === true ? null : textLabel(
39
+ typeof value === 'string' ? value : 'Invariant returned false', 200
40
+ );
41
+ }
42
+
43
+ export function buildBoundedStatechart(options = {}) {
44
+ const { initial, actions, transition, invariant } = options;
45
+ const stateKey = options.stateKey || JSON.stringify;
46
+ const stateLabel = options.stateLabel || (value => JSON.stringify(value));
47
+ const actionLabel = options.actionLabel || (value => String(value));
48
+ const maxDepth = finiteBound(options.maxDepth, DEFAULT_MAX_DEPTH, 16, 'maxDepth');
49
+ const maxStates = finiteBound(options.maxStates, DEFAULT_MAX_STATES, 2000, 'maxStates');
50
+
51
+ if (!Array.isArray(actions) || actions.length < 1 || actions.length > 64) {
52
+ throw new RangeError('Action alphabet must contain 1..64 entries');
53
+ }
54
+ if (!maxStates) throw new RangeError('maxStates must be positive');
55
+ for (const fn of [transition, invariant, stateKey, stateLabel, actionLabel]) {
56
+ if (typeof fn !== 'function') throw new TypeError('Model callbacks must be functions');
57
+ }
58
+
59
+ const alphabet = actions.map(clone);
60
+ const root = clone(initial);
61
+ const nodes = [];
62
+ const edges = [];
63
+ const byKey = new Map();
64
+ const failures = [];
65
+ let incomplete = false;
66
+ let exploredDepth = 0;
67
+
68
+ function getKey(value) {
69
+ const key = callSync(stateKey, value, 'stateKey');
70
+ if (typeof key !== 'string') throw new TypeError('stateKey must return a string');
71
+ return key;
72
+ }
73
+
74
+ function addNode(state, trace) {
75
+ const id = 'S' + nodes.length;
76
+ const label = callSync(stateLabel, state, 'stateLabel');
77
+ const reason = assertion(invariant, state);
78
+ const node = { id, state: clone(state), trace, depth: trace.length,
79
+ label: textLabel(label), reason };
80
+ nodes.push(node);
81
+ byKey.set(getKey(state), node);
82
+ if (reason && failures.length < 32) {
83
+ failures.push({ state: id, trace: trace.map(item => item.label), reason });
84
+ }
85
+ return node;
86
+ }
87
+
88
+ addNode(root, []);
89
+ for (let head = 0; head < nodes.length && !incomplete; head++) {
90
+ const node = nodes[head];
91
+ exploredDepth = Math.max(exploredDepth, node.depth);
92
+ if (node.depth >= maxDepth) continue;
93
+
94
+ for (const action of alphabet) {
95
+ const label = textLabel(callSync(actionLabel, action, 'actionLabel'), 50);
96
+ const next = transition(clone(node.state), clone(action));
97
+ if (next && typeof next.then === 'function') {
98
+ throw new TypeError('Async transitions are not supported');
99
+ }
100
+ if (next === undefined || next === null) continue;
101
+ const stable = clone(next);
102
+ const nextKey = getKey(stable);
103
+ let target = byKey.get(nextKey);
104
+
105
+ if (target && !isEquivalent(target.state, stable)) {
106
+ throw new Error('stateKey collision: distinct states share a key');
107
+ }
108
+ if (!target && nodes.length >= maxStates) {
109
+ incomplete = true;
110
+ break;
111
+ }
112
+ if (!target) {
113
+ target = addNode(stable, node.trace.concat({ label }));
114
+ }
115
+ edges.push({ from: node.id, to: target.id, action: label });
116
+ }
117
+ }
118
+
119
+ const lines = ['stateDiagram-v2', ' [*] --> S0'];
120
+ for (const node of nodes) {
121
+ lines.push(' state "' + node.label + '" as ' + node.id);
122
+ }
123
+ for (const edge of edges) {
124
+ lines.push(' ' + edge.from + ' --> ' + edge.to + ': ' + edge.action);
125
+ }
126
+ for (const fail of failures) {
127
+ lines.push(' note right of ' + fail.state + ': ' + fail.reason);
128
+ }
129
+
130
+ return {
131
+ status: failures.length ? 'counterexample' : incomplete ? 'incomplete' : 'bounded-pass',
132
+ completeWithinBounds: !incomplete, maxDepth, maxStates,
133
+ stateCount: nodes.length, transitionCount: edges.length,
134
+ exploredDepth, counterexamples: failures, diagram: lines.join('\n') + '\n',
135
+ evidence: 'Bounded exploration of the supplied JavaScript transition function, not a TLA+ TLC run or an unbounded proof'
136
+ };
137
+ }
138
+
139
+ function isEquivalent(left, right) {
140
+ if (Object.is(left, right)) return true;
141
+ try { return JSON.stringify(left) === JSON.stringify(right); }
142
+ catch { return false; }
143
+ }
@@ -0,0 +1,57 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { runInteractivePty } from './interactivePty.js';
5
+
6
+ export async function verifyCausyneTui(options = {}) {
7
+ const workspace = options.workspace || process.cwd();
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-ui-verify-'));
9
+ try {
10
+ const result = await runInteractivePty({
11
+ workspace, script: 'tests/fixtures/liveTuiTarget.mjs',
12
+ timeoutMs: options.timeoutMs ?? 15000,
13
+ rows: options.rows ?? 42,
14
+ columns: options.columns ?? 126,
15
+ env: { CAUSYNE_HOME: home },
16
+ steps: [
17
+ { name: 'open-usage', waitFor: 'CAUSYNE_VERIFY_READY',
18
+ input: '/usage\r', contains: 'Usage & Context' },
19
+ { name: 'submit-while-pinned', waitFor: 'Usage & Context',
20
+ input: 'verification-message\r', contains: 'CAUSYNE_VERIFY_MESSAGE_OK' },
21
+ { name: 'switch-to-status', waitFor: 'CAUSYNE_VERIFY_MESSAGE_OK',
22
+ input: '/status\r', contains: 'Status' },
23
+ { name: 'submit-while-status-pinned', waitFor: 'Status',
24
+ input: 'verify-exit\r', contains: 'CAUSYNE_VERIFY_EXIT_OK' }
25
+ ]
26
+ });
27
+ return { ...result, feature: 'tui-usage',
28
+ evidence: 'Observed actual ChatPrompt and StageSurface terminal output at each input boundary' };
29
+ } finally {
30
+ fs.rmSync(home, { recursive: true, force: true });
31
+ }
32
+ }
33
+
34
+ export async function verifyCausyneChatMode(options = {}) {
35
+ const workspace = options.workspace || process.cwd();
36
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-chat-verify-'));
37
+ try {
38
+ const result = await runInteractivePty({
39
+ workspace, script: 'tests/fixtures/liveChatModeTarget.mjs',
40
+ timeoutMs: options.timeoutMs ?? 18000,
41
+ rows: options.rows ?? 42, columns: options.columns ?? 126,
42
+ env: { CAUSYNE_HOME: home },
43
+ steps: [
44
+ { name: 'open-real-chat', waitFor: 'enter send',
45
+ input: '/usage\r', contains: 'Usage & Context' },
46
+ { name: 'real-chat-status', waitFor: 'Usage & Context',
47
+ input: '/status\r', contains: 'Status' },
48
+ { name: 'real-chat-exit', waitFor: 'Status',
49
+ input: 'exit\r', contains: 'exit' }
50
+ ]
51
+ });
52
+ return { ...result, feature: 'tui-chat-mode',
53
+ evidence: 'Launched Causyne chatMode and observed command handling in real POSIX PTY' };
54
+ } finally {
55
+ fs.rmSync(home, { recursive: true, force: true });
56
+ }
57
+ }
@@ -91,7 +91,7 @@ function after(outcomes, domain) {
91
91
  return outcomes.slice(outcomes.findLastIndex(matches) + 1);
92
92
  }
93
93
  function satisfied(domain, evidence) {
94
- const ok = evidence.filter((outcome) => outcome.success);
94
+ const ok = evidence.filter((outcome) => outcome.success && (outcome.exitCode === null || outcome.exitCode === 0));
95
95
  switch (domain) {
96
96
  case 'code':
97
97
  return ok.some((outcome) => outcome.tool === 'code_verify_syntax'
@@ -114,7 +114,7 @@ function after(outcomes: readonly ToolOutcome[], domain: VerificationDomain): re
114
114
  }
115
115
 
116
116
  function satisfied(domain: VerificationDomain, evidence: readonly ToolOutcome[]): boolean {
117
- const ok = evidence.filter((outcome) => outcome.success);
117
+ const ok = evidence.filter((outcome) => outcome.success && (outcome.exitCode === null || outcome.exitCode === 0));
118
118
  switch (domain) {
119
119
  case 'code':
120
120
  return ok.some((outcome) => outcome.tool === 'code_verify_syntax'