@tracedojo/sdk 0.1.0

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 (58) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +96 -0
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +356 -0
  6. package/dist/clock.d.ts +41 -0
  7. package/dist/clock.js +118 -0
  8. package/dist/compare.d.ts +20 -0
  9. package/dist/compare.js +147 -0
  10. package/dist/demo.d.ts +465 -0
  11. package/dist/demo.js +45 -0
  12. package/dist/index.d.ts +35 -0
  13. package/dist/index.js +515 -0
  14. package/dist/langchain.d.ts +9 -0
  15. package/dist/langchain.js +17 -0
  16. package/dist/langsmith-starter.d.ts +4 -0
  17. package/dist/langsmith-starter.js +77 -0
  18. package/dist/langsmith.d.ts +30 -0
  19. package/dist/langsmith.js +148 -0
  20. package/dist/matrix-cli.d.ts +107 -0
  21. package/dist/matrix-cli.js +154 -0
  22. package/dist/matrix.d.ts +138 -0
  23. package/dist/matrix.js +148 -0
  24. package/dist/privacy.d.ts +5 -0
  25. package/dist/privacy.js +51 -0
  26. package/dist/reports.d.ts +2 -0
  27. package/dist/reports.js +38 -0
  28. package/dist/schema.d.ts +715 -0
  29. package/dist/schema.js +433 -0
  30. package/dist/starter.d.ts +1 -0
  31. package/dist/starter.js +64 -0
  32. package/dist/summary.d.ts +2 -0
  33. package/dist/summary.js +50 -0
  34. package/dist/trends.d.ts +25 -0
  35. package/dist/trends.js +164 -0
  36. package/dist/upload.d.ts +8 -0
  37. package/dist/upload.js +73 -0
  38. package/dist/worlds.d.ts +9 -0
  39. package/dist/worlds.js +279 -0
  40. package/package.json +85 -0
  41. package/templates/README.md +65 -0
  42. package/templates/adapter.mjs +88 -0
  43. package/templates/ci-comment.yml +40 -0
  44. package/templates/ci.yml +100 -0
  45. package/templates/clock-adapter.mjs +42 -0
  46. package/templates/comment.cjs +209 -0
  47. package/templates/faults/duplicate-delivery/README.md +19 -0
  48. package/templates/faults/duplicate-delivery/adapter.mjs +40 -0
  49. package/templates/faults/duplicate-delivery/workflow.json +31 -0
  50. package/templates/faults/prompt-injection/README.md +17 -0
  51. package/templates/faults/prompt-injection/adapter.mjs +36 -0
  52. package/templates/faults/prompt-injection/workflow.json +43 -0
  53. package/templates/faults/stale-read/README.md +21 -0
  54. package/templates/faults/stale-read/adapter.mjs +59 -0
  55. package/templates/faults/stale-read/workflow.json +33 -0
  56. package/templates/langsmith-adapter.mjs +83 -0
  57. package/templates/workflow.json +106 -0
  58. package/templates/world-adapter.mjs +67 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ TraceDojo SDK
2
+ Copyright 2026 Syed Arman
3
+
4
+ The SDK and its starter templates are licensed under the Apache License,
5
+ Version 2.0. TraceDojo dashboard code and branding are not included in this grant.
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # TraceDojo SDK
2
+
3
+ A booking succeeds. Its confirmation times out. Your agent retries—and books twice.
4
+
5
+ TraceDojo injects tool failures, records actual state changes, and checks whether
6
+ your agent recovers correctly. Run the built-in failure and fix:
7
+
8
+ ```sh
9
+ npx @tracedojo/sdk demo
10
+ ```
11
+
12
+ Add the SDK to your application:
13
+
14
+ ```sh
15
+ npm install --save-dev @tracedojo/sdk
16
+ npx tracedojo init --ci
17
+ npx tracedojo test
18
+ ```
19
+
20
+ Use Node.js 22.23.1 or later. The starter is scripted and needs no API key.
21
+
22
+ Tools may return promises and receive `{ signal, clock }` as their third argument.
23
+ Transactions remain serialized and late results cannot commit after a trial stops.
24
+ Try `npx tracedojo init --virtual-time` for simulated service delays and retry
25
+ backoff. Use `clock.now()` / `await clock.sleep(ms)` in tools and agents. Reports
26
+ separate virtual elapsed time from actual runtime; native timers are unchanged.
27
+
28
+ Compare full batches with `npx tracedojo compare --base main-report.json --candidate pr-report.json --out comparison.json --summary comparison.md`.
29
+ Matching trials exit 0 for no new failures, 1 for regressions, and 3 for incomplete
30
+ or incompatible evidence. Known failures remain visible. Invalid input exits 2.
31
+
32
+ `init --ci` generates an exact-base regression check and a separate persistent PR
33
+ comment workflow. Merge the generated `.github/` files to the default branch first.
34
+ The comment script runs from that trusted branch; agent tests have read-only
35
+ permissions. Reports last 30 days, and missing baseline evidence blocks the gate.
36
+
37
+ List the starter worlds with `npx tracedojo templates`. Choose one with
38
+ `npx tracedojo init --template refunds --out dojo`. Available worlds: calendar,
39
+ payments, refunds, CRM (`crm`), email, files, SQL (`sql`), inventory, subscriptions,
40
+ and webhooks. Each includes five faults, a reference agent, state checks, and a
41
+ documented retry bug. These are synthetic fixtures, not full service emulators.
42
+
43
+ Use `init --template prompt-injection` for an additional tool-output attack fixture.
44
+ Its `prompt_injection` fault replaces successful response `data` with configured
45
+ JSON `replacement`; original results remain evaluator-only. The `forbidden_tool`
46
+ check catches an unsafe attempt even if it changes no state. Follow the generated
47
+ README to reproduce the scripted failure and fix; this is not a model security claim.
48
+
49
+ `init --template duplicate-delivery` tests a write request delivered twice. The
50
+ `duplicate_delivery` fault requires a write tool and preserves two transaction
51
+ records for one agent call. The fixture demonstrates service-side idempotency.
52
+
53
+ `init --template stale-read` tests version-based recovery after a write. The
54
+ `stale_read` fault substitutes the first captured successful response for identical
55
+ read inputs when a later response differs; fresh results and snapshot source stay
56
+ in evaluator evidence. Missing history or unchanged data does not trigger a fault.
57
+
58
+ Generate a fault matrix from your adapter's declared tools:
59
+
60
+ ```sh
61
+ npx tracedojo matrix --out dojo/matrix.json
62
+ npx tracedojo test-matrix dojo/matrix.json --out matrix-reports
63
+ ```
64
+
65
+ Generation imports trusted local code but does not invoke agents or tool handlers.
66
+ Review the editable matrix before running it: task, state, and outcome checks come
67
+ from your workflow, with matching scenario-specific checks preserved. The config
68
+ may omit `scenarios` entirely. Writes get six faults including lost confirmation
69
+ and duplicate delivery; reads get timeout, unavailability, and malformed output.
70
+ Use `--tools reserve_slot --faults timeout_after,duplicate_delivery` to narrow it.
71
+ Stale reads are opt-in (`--faults stale_read`); injection payloads require manual
72
+ review. Each tool gets a separate bounded suite and normal dashboard-compatible
73
+ report. `index.json` lists results and missing coverage; it is not a report import.
74
+ Unreached tools remain incomplete while other suites run. Interruptions and failed
75
+ controls stop remaining suites. This generates fault schedules, not business rules.
76
+
77
+ Start from a LangSmith JSON export with
78
+ `npx tracedojo import-langsmith trace.json --out imported-dojo`. This generates a
79
+ runnable playback adapter, observed signatures, and TODOs. Run it with
80
+ `npx tracedojo test --config imported-dojo/workflow.json --adapter imported-dojo/adapter.mjs`.
81
+ A successful, unambiguous trace passes its control and fails an injected timeout.
82
+ This demonstrates interrupted playback; connect your agent and define independent
83
+ state checks before treating it as an agent test. Use `--draft-only` to retain the
84
+ JSON-only import format.
85
+ Replace the task, in-memory tools, and outcome checks with your application's
86
+ behavior, and route your agent's tool calls through the SDK. LangChain JavaScript
87
+ tools are supported through `@tracedojo/sdk/langchain`.
88
+
89
+ The SDK, compiled distribution, documentation in this package, and starter
90
+ templates are licensed under [Apache-2.0](LICENSE). The hosted dashboard is
91
+ proprietary and is not included in this package.
92
+
93
+ [Setup guide](https://github.com/syedarman1/TraceDojo/blob/main/docs/WORKFLOWS.md)
94
+ · [Security](https://github.com/syedarman1/TraceDojo/blob/main/docs/SECURITY.md)
95
+ · [Limitations](https://github.com/syedarman1/TraceDojo/blob/main/LIMITATIONS.md)
96
+ · [Dashboard](https://tracedojo.com)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,356 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Copyright 2026 Syed Arman
4
+ import { parseArgs } from 'node:util';
5
+ import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
6
+ import { dirname, resolve } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { runWorkflow } from './index.js';
10
+ import { boundedJson, parseWorkflow, workflowExitCode, commitShaSchema, } from './schema.js';
11
+ import { sanitizeWorkflowBatch } from './privacy.js';
12
+ import { importLangSmithTrace } from './langsmith.js';
13
+ import { uploadWorkflowReports } from './upload.js';
14
+ import { createStarter } from './starter.js';
15
+ import { workflowSummary } from './summary.js';
16
+ import { runDemo } from './demo.js';
17
+ import { starterWorlds } from './worlds.js';
18
+ import { createLangSmithStarter } from './langsmith-starter.js';
19
+ import { writeFaultMatrix, testFaultMatrix } from './matrix-cli.js';
20
+ import { compareWorkflowBatches, comparisonExitCode, comparisonSummary, } from './compare.js';
21
+ const help = `TraceDojo — test your agent against controlled tool failures
22
+
23
+ tracedojo demo
24
+ tracedojo init --out dojo --ci
25
+ tracedojo templates
26
+ tracedojo init --template refunds --out dojo
27
+ tracedojo init --virtual-time --out dojo
28
+ tracedojo test
29
+ tracedojo matrix --out dojo/matrix.json
30
+ tracedojo matrix --tools reserve_slot --faults timeout_after,duplicate_delivery --out dojo/matrix.json
31
+ tracedojo test-matrix dojo/matrix.json --adapter dojo/adapter.mjs --out matrix-reports
32
+ tracedojo test --config dojo/workflow.json --adapter dojo/adapter.mjs --out dojo-report.json
33
+ tracedojo compare --base main-report.json --candidate pr-report.json --out comparison.json --summary comparison.md
34
+ tracedojo import-langsmith trace.json --out imported-dojo
35
+ tracedojo import-langsmith trace.json --draft-only --out trace-draft.json
36
+ tracedojo upload dojo-report.json --url https://tracedojo.com --project PROJECT_UUID
37
+
38
+ Uploads use TRACEDOJO_UPLOAD_TOKEN from your environment; credentials stay local.
39
+
40
+ test runs a no-fault control followed by every configured scenario.
41
+ --trials 1–20 independent attempts per scenario (default 1)
42
+ --out New JSON file; existing evidence is never overwritten
43
+ Default: .tracedojo/reports/<unique-id>.json
44
+ --summary Optional new Markdown summary file for CI
45
+ --commit Full lowercase Git SHA to label test/test-matrix reports for trends
46
+
47
+ matrix reads declared tool kinds and generates editable suites without running an agent.
48
+ --config Task, starting state, checks, and optional existing scenarios
49
+ --tools Optional comma-separated tool names (default: every declared tool)
50
+ --faults Optional comma-separated fault types; stale_read is opt-in
51
+ test-matrix saves a normal report per suite plus index.json in a NEW directory.
52
+ Review generated scenarios and expected outcomes before running paid model adapters.
53
+
54
+ init --ci creates test/comment workflows and a trusted comment script under .github/.
55
+ Existing files are never overwritten. Merge this setup to the default branch first.
56
+ Install the SDK in your npm project and commit its lockfile before enabling CI.
57
+
58
+ The adapter is trusted local JavaScript (.mjs/.js). It can access your environment
59
+ and network. Simulated tools may be async and must operate only on their state
60
+ draft. Deadlines are cooperative, not process isolation. Model API calls in your
61
+ adapter may incur provider charges; the shipped reference agent uses no API.
62
+
63
+ LangSmith imports create a runnable playback scaffold with TODOs and observed signatures.
64
+ Use --draft-only for a JSON review draft. Recorded outputs do not establish correctness.
65
+ Review the task, starting state, tool implementations, and outcome checks.
66
+
67
+ Exit codes: 0 pass, 1 failed checks, 2 invalid input, 3 incomplete/inconclusive.
68
+ demo exits 0 when it reproduces both the expected failure and the passing fix.
69
+ `;
70
+ async function readJson(file) {
71
+ if ((await stat(file)).size > 5_000_000)
72
+ throw new Error('JSON exceeds the 5 MB limit.');
73
+ const input = JSON.parse(await readFile(file, 'utf8'));
74
+ boundedJson(input);
75
+ return input;
76
+ }
77
+ async function main() {
78
+ const { values, positionals } = parseArgs({
79
+ allowPositionals: true,
80
+ options: {
81
+ config: { type: 'string' },
82
+ adapter: { type: 'string' },
83
+ out: { type: 'string' },
84
+ trials: { type: 'string' },
85
+ help: { type: 'boolean', short: 'h' },
86
+ url: { type: 'string' },
87
+ project: { type: 'string' },
88
+ ci: { type: 'boolean' },
89
+ summary: { type: 'string' },
90
+ template: { type: 'string' },
91
+ 'draft-only': { type: 'boolean' },
92
+ base: { type: 'string' },
93
+ candidate: { type: 'string' },
94
+ 'base-sha': { type: 'string' },
95
+ 'head-sha': { type: 'string' },
96
+ 'virtual-time': { type: 'boolean' },
97
+ tools: { type: 'string' },
98
+ faults: { type: 'string' },
99
+ commit: { type: 'string' },
100
+ },
101
+ });
102
+ const command = positionals[0];
103
+ if (!command || values.help) {
104
+ console.log(help);
105
+ return;
106
+ }
107
+ if (command === 'matrix' || command === 'test-matrix') {
108
+ const allowed = command === 'matrix'
109
+ ? ['config', 'adapter', 'out', 'tools', 'faults']
110
+ : ['adapter', 'out', 'trials', 'commit'];
111
+ if (positionals.length !== (command === 'matrix' ? 1 : 2) ||
112
+ Object.keys(values).some((key) => !allowed.includes(key)))
113
+ throw new Error('Unsupported matrix arguments. See --help.');
114
+ const input = await readJson(resolve(command === 'matrix'
115
+ ? (values.config ?? 'dojo/workflow.json')
116
+ : positionals[1]));
117
+ const adapter = resolve(values.adapter ?? 'dojo/adapter.mjs');
118
+ if (!/\.(?:mjs|js)$/.test(adapter) || !(await stat(adapter)).isFile())
119
+ throw new Error('Use a trusted local .mjs or .js adapter module.');
120
+ if (command === 'matrix') {
121
+ const destination = resolve(values.out ?? `.tracedojo/matrices/${randomUUID()}.json`);
122
+ const matrix = await writeFaultMatrix(input, adapter, destination, {
123
+ ...(values.tools !== undefined
124
+ ? { tools: values.tools.split(',').map((tool) => tool.trim()) }
125
+ : {}),
126
+ ...(values.faults !== undefined
127
+ ? {
128
+ faults: values.faults
129
+ .split(',')
130
+ .map((fault) => fault.trim()),
131
+ }
132
+ : {}),
133
+ });
134
+ console.log(`Generated ${matrix.suites.length} tool suites, ${matrix.suites.reduce((count, suite) => count + suite.workflow.scenarios.length, 0)} scenarios. Generation does not invoke agents or tool handlers; importing the adapter still executes local code.`);
135
+ console.log(`Matrix: ${destination}`);
136
+ console.log('Review expectations before running test-matrix. Original scenarios are preserved in your source config; only exact-match check overrides carry into generated cases. Prompt injections need a reviewed payload; stale reads are opt-in and require history.');
137
+ }
138
+ else {
139
+ const destination = resolve(values.out ?? `.tracedojo/matrix-reports/${randomUUID()}`);
140
+ const controller = new AbortController();
141
+ const cancel = () => controller.abort();
142
+ process.once('SIGINT', cancel);
143
+ process.once('SIGTERM', cancel);
144
+ try {
145
+ const result = await testFaultMatrix(input, adapter, destination, Number(values.trials ?? 1), controller.signal, values.commit);
146
+ for (const suite of result.suites)
147
+ console.log(`${suite.tool}: ${suite.status}`);
148
+ if (result.reason)
149
+ console.log(result.reason);
150
+ console.log(`Completed ${result.completed}/${result.planned} suites. Reports: ${destination}`);
151
+ process.exitCode = result.exitCode;
152
+ }
153
+ finally {
154
+ process.removeListener('SIGINT', cancel);
155
+ process.removeListener('SIGTERM', cancel);
156
+ }
157
+ }
158
+ return;
159
+ }
160
+ if (command === 'upload') {
161
+ if (positionals.length !== 2 ||
162
+ Object.keys(values).some((key) => !['url', 'project'].includes(key)))
163
+ throw new Error('upload takes one report file and --url/--project.');
164
+ const receipt = await uploadWorkflowReports(await readJson(resolve(positionals[1])), {
165
+ url: values.url ?? process.env.TRACEDOJO_URL ?? '',
166
+ project: values.project ?? process.env.TRACEDOJO_PROJECT_ID ?? '',
167
+ token: process.env.TRACEDOJO_UPLOAD_TOKEN ?? '',
168
+ });
169
+ console.log(`Uploaded ${receipt.count} reports. ${receipt.url}`);
170
+ return;
171
+ }
172
+ if (command === 'compare') {
173
+ if (positionals.length !== 1 ||
174
+ !values.base ||
175
+ !values.candidate ||
176
+ Object.keys(values).some((key) => ![
177
+ 'base',
178
+ 'candidate',
179
+ 'out',
180
+ 'summary',
181
+ 'base-sha',
182
+ 'head-sha',
183
+ ].includes(key)))
184
+ throw new Error('compare requires --base and --candidate report files.');
185
+ if ((values['base-sha'] || values['head-sha']) &&
186
+ (!/^[a-f0-9]{40}$/.test(values['base-sha'] ?? '') ||
187
+ !/^[a-f0-9]{40}$/.test(values['head-sha'] ?? '')))
188
+ throw new Error('Provide both --base-sha and --head-sha as full commit hashes.');
189
+ const readOptional = async (file) => {
190
+ try {
191
+ return await readJson(resolve(file));
192
+ }
193
+ catch (error) {
194
+ if (error.code === 'ENOENT')
195
+ return undefined;
196
+ throw error;
197
+ }
198
+ };
199
+ const result = compareWorkflowBatches(await readOptional(values.base), await readOptional(values.candidate));
200
+ const destination = resolve(values.out ?? `.tracedojo/comparisons/${randomUUID()}.json`);
201
+ await mkdir(dirname(destination), { recursive: true });
202
+ const output = await open(destination, 'wx', 0o600);
203
+ let summary;
204
+ let saved = false;
205
+ try {
206
+ if (values.summary) {
207
+ await mkdir(dirname(resolve(values.summary)), { recursive: true });
208
+ summary = await open(resolve(values.summary), 'wx', 0o600);
209
+ }
210
+ const source = values['base-sha']
211
+ ? { baseSha: values['base-sha'], headSha: values['head-sha'] }
212
+ : undefined;
213
+ await output.writeFile(JSON.stringify({ ...result, ...(source ? { source } : {}) }, null, 2) +
214
+ '\n');
215
+ if (summary)
216
+ await summary.writeFile(comparisonSummary(result));
217
+ saved = true;
218
+ console.log(result.reason);
219
+ process.exitCode = comparisonExitCode(result);
220
+ }
221
+ finally {
222
+ await output.close();
223
+ await summary?.close();
224
+ if (!saved) {
225
+ await unlink(destination);
226
+ if (summary)
227
+ await unlink(resolve(values.summary));
228
+ }
229
+ }
230
+ return;
231
+ }
232
+ const allowed = command === 'test'
233
+ ? ['config', 'adapter', 'out', 'trials', 'summary', 'commit']
234
+ : command === 'init'
235
+ ? ['out', 'ci', 'template', 'virtual-time']
236
+ : command === 'templates'
237
+ ? []
238
+ : command === 'import-langsmith'
239
+ ? ['out', 'draft-only']
240
+ : ['out'];
241
+ if (Object.keys(values).some((key) => !allowed.includes(key)) ||
242
+ positionals.length !== (command === 'import-langsmith' ? 2 : 1))
243
+ throw new Error('Unsupported arguments. See --help.');
244
+ if (command === 'templates') {
245
+ for (const world of starterWorlds)
246
+ console.log(`${world.id.padEnd(16)} ${world.title}`);
247
+ return;
248
+ }
249
+ if (command === 'init') {
250
+ const directory = resolve(values.out ?? 'dojo');
251
+ await createStarter(directory, values.ci ?? false, values.template, values['virtual-time'] ?? false);
252
+ console.log(`Created ${directory}. See its README.md to run the example and connect your agent.${values.ci ? '\nCreated test/comment workflows and .github/tracedojo/comment.cjs. Commit these files, your SDK dependency, and lockfile to the default branch before running PR checks.' : ''}`);
253
+ return;
254
+ }
255
+ if (command === 'demo') {
256
+ const directory = resolve(values.out ?? `.tracedojo/demo-${randomUUID()}`);
257
+ await mkdir(dirname(directory), { recursive: true });
258
+ const { before, after } = await runDemo(directory);
259
+ console.log('A booking succeeded. Its confirmation timed out. The agent retried.');
260
+ console.log(`Before: ${before.runs[0].status} — ${before.runs[0].metrics.mutations} committed writes; duplicate booking.`);
261
+ console.log(`After: ${after.runs[0].status} — ${after.runs[0].metrics.mutations} committed write; the retry reused the original booking.`);
262
+ console.log('Both no-fault controls passed. Scripted example; no model calls.');
263
+ console.log(`Open before.json and after.json from ${directory} in the Workflows dashboard.`);
264
+ return;
265
+ }
266
+ if (!['test', 'import-langsmith'].includes(command))
267
+ throw new Error('Unknown command. See --help.');
268
+ if (!values.out && command === 'import-langsmith')
269
+ throw new Error('Choose a new --out directory (or file with --draft-only). Existing files are never overwritten.');
270
+ if (command === 'import-langsmith' && !values['draft-only']) {
271
+ const result = await createLangSmithStarter(await readJson(resolve(positionals[1])), resolve(values.out));
272
+ console.log(`Created a runnable playback scaffold: ${result.tools} tool stubs, ${result.calls} observed calls. See README.md for the test command and TODOs. This does not test your actual agent yet.`);
273
+ return;
274
+ }
275
+ let workflow;
276
+ const trials = Number(values.trials ?? 1);
277
+ if (command === 'test') {
278
+ if (values.commit !== undefined)
279
+ commitShaSchema.parse(values.commit);
280
+ values.config ??= 'dojo/workflow.json';
281
+ values.adapter ??= 'dojo/adapter.mjs';
282
+ workflow = parseWorkflow(await readJson(resolve(values.config)));
283
+ if (!Number.isInteger(trials) || trials < 1 || trials > 20)
284
+ throw new Error('--trials must be from 1 to 20.');
285
+ if (!/\.(?:mjs|js)$/.test(values.adapter) ||
286
+ !(await stat(resolve(values.adapter))).isFile())
287
+ throw new Error('Use a trusted local .mjs or .js adapter module.');
288
+ }
289
+ const destination = resolve(values.out ?? `.tracedojo/reports/${randomUUID()}.json`);
290
+ await mkdir(dirname(destination), { recursive: true });
291
+ const output = await open(destination, 'wx', 0o600);
292
+ let saved = false;
293
+ let summaryOutput;
294
+ const controller = new AbortController();
295
+ const cancel = () => controller.abort();
296
+ process.once('SIGINT', cancel);
297
+ process.once('SIGTERM', cancel);
298
+ try {
299
+ // Reserve every destination before invoking customer code or a paid model.
300
+ if (values.summary) {
301
+ await mkdir(dirname(resolve(values.summary)), { recursive: true });
302
+ summaryOutput = await open(resolve(values.summary), 'wx', 0o600);
303
+ }
304
+ if (command === 'import-langsmith') {
305
+ const draft = importLangSmithTrace(await readJson(resolve(positionals[1])));
306
+ await output.writeFile(JSON.stringify(draft, null, 2) + '\n');
307
+ saved = true;
308
+ console.log(`Saved a review draft with ${draft.observedCalls.length} observed tool calls. Supply starting state, tools, and checks before running.`);
309
+ return;
310
+ }
311
+ let adapter;
312
+ try {
313
+ adapter = await import(pathToFileURL(resolve(values.adapter)).href);
314
+ }
315
+ catch {
316
+ throw new Error('Could not load the adapter. Check its syntax and installed dependencies.');
317
+ }
318
+ const batch = sanitizeWorkflowBatch(await runWorkflow(workflow, adapter, {
319
+ trials,
320
+ signal: controller.signal,
321
+ commitSha: values.commit,
322
+ }));
323
+ await output.writeFile(JSON.stringify(batch, null, 2) + '\n');
324
+ saved = true;
325
+ if (summaryOutput)
326
+ await summaryOutput.writeFile(workflowSummary(batch));
327
+ console.log(`Control: ${batch.baseline.status}`);
328
+ for (const run of batch.runs) {
329
+ console.log(`${run.scenario.title}: ${run.status}`);
330
+ for (const check of run.assertions.filter((c) => !c.passed))
331
+ console.log(` ${check.label}: ${check.detail}`);
332
+ }
333
+ if (batch.skippedReason)
334
+ console.log(batch.skippedReason);
335
+ console.log(`Completed ${batch.runs.length}/${batch.planned} fault trials. Report: ${destination}`);
336
+ process.exitCode = workflowExitCode(batch);
337
+ }
338
+ finally {
339
+ process.removeListener('SIGINT', cancel);
340
+ process.removeListener('SIGTERM', cancel);
341
+ await output.close();
342
+ await summaryOutput?.close();
343
+ if (!saved)
344
+ await unlink(destination);
345
+ if (!saved && summaryOutput)
346
+ await unlink(resolve(values.summary));
347
+ }
348
+ }
349
+ main().catch((error) => {
350
+ // Schema validation errors can contain customer inputs; never print them.
351
+ const safe = error instanceof Error && error.constructor === Error
352
+ ? error.message
353
+ : 'Invalid input or output. Check the file paths, JSON, and workflow contract.';
354
+ console.error(safe);
355
+ process.exitCode = 2;
356
+ });