@ligeti/testing 0.0.0-stage → 2.0.4

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 (81) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +242 -2
  3. package/bin/argv-recorder.mjs +53 -0
  4. package/bin/clean-test-databases.mjs +146 -0
  5. package/bin/fake-claude.mjs +560 -0
  6. package/bin/fake-herdr.mjs +468 -0
  7. package/bin/fake-opencode.mjs +45 -0
  8. package/dist/agents.d.ts +5 -0
  9. package/dist/agents.d.ts.map +1 -0
  10. package/dist/agents.js +21 -0
  11. package/dist/agents.js.map +1 -0
  12. package/dist/bitbucket.d.ts +26 -0
  13. package/dist/bitbucket.d.ts.map +1 -0
  14. package/dist/bitbucket.js +162 -0
  15. package/dist/bitbucket.js.map +1 -0
  16. package/dist/callback-server.d.ts +20 -0
  17. package/dist/callback-server.d.ts.map +1 -0
  18. package/dist/callback-server.js +79 -0
  19. package/dist/callback-server.js.map +1 -0
  20. package/dist/claude-profile.d.ts +3 -0
  21. package/dist/claude-profile.d.ts.map +1 -0
  22. package/dist/claude-profile.js +16 -0
  23. package/dist/claude-profile.js.map +1 -0
  24. package/dist/env.d.ts +2 -0
  25. package/dist/env.d.ts.map +1 -0
  26. package/dist/env.js +15 -0
  27. package/dist/env.js.map +1 -0
  28. package/dist/fake-http.d.ts +25 -0
  29. package/dist/fake-http.d.ts.map +1 -0
  30. package/dist/fake-http.js +129 -0
  31. package/dist/fake-http.js.map +1 -0
  32. package/dist/github.d.ts +184 -0
  33. package/dist/github.d.ts.map +1 -0
  34. package/dist/github.js +919 -0
  35. package/dist/github.js.map +1 -0
  36. package/dist/gitlab-merge-requests.d.ts +23 -0
  37. package/dist/gitlab-merge-requests.d.ts.map +1 -0
  38. package/dist/gitlab-merge-requests.js +228 -0
  39. package/dist/gitlab-merge-requests.js.map +1 -0
  40. package/dist/gitlab.d.ts +9 -0
  41. package/dist/gitlab.d.ts.map +1 -0
  42. package/dist/gitlab.js +13 -0
  43. package/dist/gitlab.js.map +1 -0
  44. package/dist/herdr.d.ts +9 -0
  45. package/dist/herdr.d.ts.map +1 -0
  46. package/dist/herdr.js +16 -0
  47. package/dist/herdr.js.map +1 -0
  48. package/dist/index.d.ts +17 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +19 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/jira.d.ts +7 -0
  53. package/dist/jira.d.ts.map +1 -0
  54. package/dist/jira.js +7 -0
  55. package/dist/jira.js.map +1 -0
  56. package/dist/postgres.d.ts +6 -0
  57. package/dist/postgres.d.ts.map +1 -0
  58. package/dist/postgres.js +122 -0
  59. package/dist/postgres.js.map +1 -0
  60. package/dist/recorded-turns.d.ts +9 -0
  61. package/dist/recorded-turns.d.ts.map +1 -0
  62. package/dist/recorded-turns.js +45 -0
  63. package/dist/recorded-turns.js.map +1 -0
  64. package/dist/repo.d.ts +6 -0
  65. package/dist/repo.d.ts.map +1 -0
  66. package/dist/repo.js +30 -0
  67. package/dist/repo.js.map +1 -0
  68. package/dist/telegram.d.ts +11 -0
  69. package/dist/telegram.d.ts.map +1 -0
  70. package/dist/telegram.js +37 -0
  71. package/dist/telegram.js.map +1 -0
  72. package/dist/wait.d.ts +2 -0
  73. package/dist/wait.d.ts.map +1 -0
  74. package/dist/wait.js +15 -0
  75. package/dist/wait.js.map +1 -0
  76. package/dist/worker.d.ts +19 -0
  77. package/dist/worker.d.ts.map +1 -0
  78. package/dist/worker.js +56 -0
  79. package/dist/worker.js.map +1 -0
  80. package/fixtures/claude-profile/settings.json +26 -0
  81. package/package.json +32 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Viktor "Bika" Nagy
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,243 @@
1
- # Temporary Holding Version
1
+ # @ligeti/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ligeti's test kit: throwaway Postgres databases, a fake `claude`, a fake `herdr`, fake GitLab,
4
+ GitHub, Bitbucket, Jira and Telegram servers, and helpers that run a workflow package under a real
5
+ `ligeti-worker`. It is a `devDependency` everywhere it appears — no package's runtime code imports
6
+ it. It is published, so a workflow package outside this repository can run its acceptance tests
7
+ against the same doubles; under
8
+ [ADR-0025](../../adr/0025-published-packages-are-public-contracts-product-workflows-live-in-their-product.md)
9
+ its exports are a public contract.
10
+
11
+ [ADR-0007](../../adr/0007-test-doubles-are-real-processes.md) decides that every test double in
12
+ this workspace is a real process or a real server the system under test talks to over a real
13
+ process boundary or socket, never a module mock — this package exists to make that possible for
14
+ `claude`, `herdr` and the GitLab REST API, the external tools/services whose real, workspace-wide
15
+ fakes it ships. (A step package's own test double for a tool only it drives — e.g.
16
+ `steps/beads/test/fixtures/fake-bd.mjs` — lives in that package instead, per the same ADR.)
17
+
18
+ ## What it exposes
19
+
20
+ - **`createTestDatabase`** (`src/postgres.ts`) — creates a uniquely named, empty Postgres
21
+ database against an admin connection and returns its URL plus a `drop()` that gives connections
22
+ up to 2s to close on their own, terminates the rest and drops it. One database per test file.
23
+ - **`fakeClaudePath`** / **`fakeOpencodePath`** / **`fakeHerdrPath`** (`src/agents.ts`) — absolute
24
+ paths to the fake `claude`, `opencode` and `herdr` executables shipped in `bin/`, resolved via `import.meta.url` so they work
25
+ from `src/` or `dist/`.
26
+ - `bin/fake-claude.mjs` parses the same CLI flags the real `claude` binary accepts and fires
27
+ real Stop/StopFailure hooks read from `$CLAUDE_CONFIG_DIR/settings.json`, exactly as the real
28
+ binary would. Interactive mode also writes a small Claude Code transcript JSONL (user prompt,
29
+ assistant text plus a `Bash` tool call, its result, a final assistant text) to
30
+ `$CLAUDE_CONFIG_DIR/projects/<cwd with every non-alphanumeric character replaced by "-">/<session id>.jsonl`
31
+ and reports that path as the hook payload's `transcript_path`.
32
+ - `bin/fake-opencode.mjs` prints the NDJSON event stream `opencode run --format json` prints
33
+ (`step_start`, `text`, a completed `tool_use`, `text`, `step_finish` with a cost), each event
34
+ carrying the session id `ses_fake`.
35
+ - `bin/fake-herdr.mjs` implements `workspace`/`pane` subcommands as a real subprocess, with its
36
+ `workspaces`/`panes` state persisted to a JSON file (`FAKE_HERDR_STATE`) so separate
37
+ invocations — as real `herdr` calls are — see consistent state.
38
+ - `bin/argv-recorder.mjs` is a generic stand-in binary that records the argv/env it was invoked
39
+ with, for tests asserting what a step actually executed.
40
+ - **A fake Bitbucket server** (`src/bitbucket.ts`) — the same kind of loopback server for
41
+ `steps/bitbucket-pr` tests, serving under `/2.0`. A route's response body is sent as JSON, or
42
+ verbatim as `text/plain` when it is a string; its headers (such as `Location`) override the
43
+ defaults, and its status may be any code, including 202 or a 302. Each recorded request carries its
44
+ method, path, query (first value in `query`, every value in `queryAll`), headers and parsed body.
45
+ - **A fake GitHub server** (`src/github.ts`) — started with `startFakeGitHub({ token?, login? })`, for
46
+ `steps/github-issue` and `steps/github-pr` tests. Unlike the canned-response fakes it keeps an
47
+ in-memory model, keyed by `owner/repo`, that the REST routes read and write. `apiUrl` is the
48
+ server's loopback origin, because GitHub's API is served from the host root; every web URL the
49
+ fake reports (`html_url`, `repositoryUrl()`, `issueUrl()`, `pullRequestUrl()`) is on
50
+ `https://github.com`, as on the real service, so URLs it hands out pass the steps' github.com-only
51
+ parsers. Every request must carry `Authorization: Bearer <token>` (`server.token`) or it is
52
+ answered 401 `Bad credentials`. An unknown repository, issue or pull request answers 404; a path
53
+ no route serves answers 501, so a wrong path cannot pass for GitHub's 404. Lists carry GitHub's
54
+ `Link` header (`next`, `last`, `prev`, `first`).
55
+ - **Issues**: `addIssue(owner, repo, seed)` seeds an issue (or, with `pullRequest: true`, a bare
56
+ pull request entry) and `issue(owner, repo, number)` reads back what the steps changed. Routes:
57
+ `GET .../issues/:number`, `GET .../issues` (`labels`, `state`, `per_page`, `page`; newest first),
58
+ `POST .../labels` (creating a missing label), `DELETE .../labels/:label` (404 when the issue
59
+ does not carry it), `POST .../comments`, `POST .../assignees`. Label names match
60
+ case-insensitively and the stored spelling is returned.
61
+ - **Pull requests**: `addBranch(owner, repo, branch, sha)` makes a head branch exist;
62
+ `addPullRequest(owner, repo, { title, headRef, headSha?, baseRef?, mergeable?, mergeableState? })`
63
+ seeds a pull request in the shared issue number space and `pullRequest(owner, repo, number)`
64
+ returns its mutable state (`headSha`, `mergeable`, `merged`, `mergeRequests`). Routes:
65
+ `GET /repos/:owner/:repo` (`default_branch`, settable through
66
+ `repository(owner, repo).defaultBranch`), `GET/POST .../pulls`, `GET .../pulls/:number`,
67
+ `PUT .../pulls/:number/merge` (409 when `sha` is not the head, 405 when already merged or not
68
+ mergeable), `DELETE .../git/refs/heads/<branch>` (204; 422 when the ref is gone) and `GET /user`
69
+ (the `login` option, default `fake-github-user`). Creating a pull request for a branch that
70
+ already has an open one answers 422 `A pull request already exists`.
71
+ - **Checks**: `addCheckRun(owner, repo, sha, { name, status?, conclusion?, appSlug?, title?,
72
+ summary?, detailsUrl? })` and `addStatus(owner, repo, sha, { context, state, ... })` return
73
+ mutable records, so a test can flip a check to completed. `onCheckPoll(owner, repo, sha, hook)`
74
+ calls `hook(pollIndex)` on every first-page read of that sha's check runs, before it answers, to
75
+ change checks over time. Routes: `GET .../commits/:sha/check-runs` (wrapped in `check_runs`) and
76
+ `GET .../commits/:sha/statuses` (newest first).
77
+ - **Actions**: `addActionsRun(owner, repo, { headSha, name?, status?, conclusion?, jobs? })` seeds a
78
+ workflow run whose jobs each get a `github-actions` check run with the same id, as on GitHub, and
79
+ a `log`. Routes: `GET .../actions/runs?head_sha=`, `GET .../actions/jobs/:id/logs` (302 to a
80
+ `/_logs/...` URL on the fake, which serves the log as plain text without a token, as GitHub's
81
+ signed log URLs are) and `POST .../actions/runs/:id/rerun` and `.../rerun-failed-jobs` (403 while
82
+ the run is not completed), recorded in `repository(owner, repo).reruns` and resetting the re-run
83
+ jobs to `queued`.
84
+ - `respond(method, path, handler)` still overrides one exact path with a canned response, a
85
+ response list or a function, for error injection; requests are recorded as in the other fakes.
86
+ - **A fake Jira server** (`src/jira.ts`) — started with `startFakeJira()`, for `steps/jira-issue`
87
+ tests. It is built on the same loopback recorder as the fake GitLab server, `src/fake-http.ts`.
88
+ - **A fake GitLab server** (`src/gitlab.ts`) — a real loopback `node:http` server on an ephemeral
89
+ port for `steps/gitlab-mr` and `steps/gitlab-issue` tests: serves canned responses per registered route and records every
90
+ request it received, including method, path, query, headers and body.
91
+ A handler may be a function returning its response or a promise of it, so a route can hold a
92
+ response until something else has happened. The recorder itself lives in `src/fake-http.ts`.
93
+ - **`serveGitBackedMergeRequests`** (`src/gitlab-merge-requests.ts`) — registers merge request
94
+ routes on it that act on a real bare repository: `POST` opens a merge request, `GET` reports its
95
+ head sha and a successful head pipeline, and `PUT .../merge` fast-forwards the target branch with
96
+ `git update-ref`. It checks the guarding sha first, answering 409 when it is not the source
97
+ head, then refuses with 405 when the source does not descend from the target tip. That is the
98
+ fake's own simplification: real GitLab answers 405 for a merge that is not allowed, 422 for one
99
+ that is not mergeable on current versions, and 409 for a sha mismatch. A hold that is not
100
+ released within 120 s answers 504 instead of merging. `holdMergeUntilMerged` makes one source
101
+ branch's merge wait until another's merge request has merged, and
102
+ `holdMergeUntilAttempted` until another's merge has been requested, and
103
+ `holdMergeUntilFile` makes a merge wait until a named file exists.
104
+ - **`fixtureClaudeProfileDir`** / **`copyClaudeProfile`** (`src/claude-profile.ts`) — the path to
105
+ the Claude profile shipped in `fixtures/claude-profile`, whose `settings.json` declares the
106
+ Stop/StopFailure hooks of `@ligeti/step-agent`'s `claude-profile-hooks.json`, and a copier into a
107
+ throwaway directory, because fake claude writes transcripts into the profile it runs under.
108
+ - **`startWorker`** / **`describeWorkflowPackage`** / **`ligetiWorkerBin`** (`src/worker.ts`) — run
109
+ a workflow package under a real `ligeti-worker run`, or print its manifest with `ligeti-worker
110
+ describe`. The binary is the one declared by the `@ligeti/sdk` installed next to this package.
111
+ - **`startCallbackServer`** (`src/callback-server.ts`) — a loopback stand-in for the shell's
112
+ callback endpoint: verifies callback tokens, validates each payload against the manifest and
113
+ forwards it through any `send(workflowId, message, topic, idempotencyKey)`, such as a
114
+ `DBOSClient`. With `attest`, it also answers `POST /attest`.
115
+ - **`startFakeTelegram`** (`src/telegram.ts`) — a loopback Telegram Bot API that records every
116
+ request and answers each with a successful `sendMessage` result.
117
+ - **`makeRepo`** / **`git`** (`src/repo.ts`) — a throwaway repository with a bare `origin` and one
118
+ pushed commit, and a `git -C` runner.
119
+ - **`writeHerdrShim`** / **`readHerdrWorktrees`** (`src/herdr.ts`) — a shim that runs the fake
120
+ herdr with a given state and log file, and the worktrees the fake recorded.
121
+ - **`readRecordedTurns`** (`src/recorded-turns.ts`) — every agent turn under a state directory:
122
+ prompt, agent, session id and `--resume` flag, oldest first.
123
+ - **`waitUntil`** (`src/wait.ts`) — polls a condition until it holds, or rejects with
124
+ `waitUntil: timed out`.
125
+ - **`sanitizedEnv`** (`src/env.ts`) — `process.env` with every `LIGETI_*` variable and
126
+ `CLAUDE_CONFIG_DIR` stripped, then overrides applied. Tests pass the env a scenario actually
127
+ needs explicitly, rather than risk inheriting a ligeti-launched agent's own session env if the
128
+ outer test process happens to be running inside one.
129
+
130
+ ## The fake executables
131
+
132
+ Both fakes are driven through explicit CLI arguments or their own environment variables, never
133
+ through inherited `LIGETI_*` variables.
134
+
135
+ ### `bin/fake-claude.mjs`
136
+
137
+ Flags shared by both modes:
138
+
139
+ | Flag | Effect |
140
+ | ------------------------- | -------------------------------------------------------------------------------------------- |
141
+ | `--fake-sleep SECONDS` | Sleep before writing output or firing hooks (default 0). |
142
+ | `--fake-exit-code N` | Process exit code (default 0). |
143
+ | `--fake-hang` | Never return until killed. |
144
+ | `--invocations-file PATH` | Append one line (pid and ISO timestamp) to `PATH` on every invocation: a spawn-count oracle. |
145
+
146
+ `-p` / `--output-format json` mode reads the prompt from stdin, writes a JSON result to stdout and exits:
147
+
148
+ | Flag | Effect |
149
+ | ----------------------- | ------------------------------------------------------ |
150
+ | `--fake-error` | Write an `is_error: true` result instead of a success. |
151
+ | `--fake-invalid-output` | Write non-JSON garbage to stdout instead of a result. |
152
+
153
+ Interactive mode (the default, no `-p`) fires the fake's own Stop or StopFailure hooks, read from
154
+ `$CLAUDE_CONFIG_DIR/settings.json`, then stays alive until killed. `CLAUDE_CONFIG_DIR` must be set:
155
+ the fake never falls back to `~/.claude/settings.json`, so a test can never run a developer's
156
+ personal hooks. A 30 second safety timeout ends every interactive run.
157
+
158
+ | Flag | Effect |
159
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
160
+ | `--fake-background-tasks N` | Fire Stop with `N` fake running background tasks, wait briefly, then fire Stop again with empty arrays. |
161
+ | `--fake-stop-failure` | Fire StopFailure (with a fake `error`) instead of Stop. |
162
+ | `--fake-stop-failure-error REASON` | Fire StopFailure with `error: REASON` (implies `--fake-stop-failure`; default reason `server_error`). |
163
+ | `--fake-no-hooks` | Fire no hook; exit with `--fake-exit-code`, as if claude had crashed. |
164
+ | `--session-id ID` | Session id echoed in every hook payload (default: a fixed fake id). Always wins over `--resume`. |
165
+ | `--resume ID` | Without `--session-id`, `ID` is the hook payload's session id, as with real claude's non-forking resume. |
166
+ | `--continue` | Accepted; only relevant to the `--session-id` rejection below. |
167
+ | `--fork-session` | Accepted alongside `--resume` / `--continue`. |
168
+ | `--fake-foreign-session` | Fire one extra Stop first, carrying a session id other than `--session-id`, as a nested claude invocation would. |
169
+ | `--fake-ignore-sigterm` | Ignore SIGTERM so only SIGKILL ends the process. |
170
+ | `--fake-commit-file PATH` | Write a fixed line to `PATH` (relative to the cwd) and commit it if that leaves anything uncommitted; a repeat invocation is a no-op. |
171
+
172
+ `--fake-script FILE` reads `{ "rules": [...] }` from `FILE` and applies the first rule whose `match`
173
+ regular expression matches the interactive prompt, instead of `--fake-commit-file`; a prompt no rule
174
+ matches behaves as without the flag. A rule's fields run in this order, all optional: `touch` (paths
175
+ created empty), `waitFor` (paths to wait for, up to `waitTimeoutSeconds`, default 60, after which
176
+ the process exits 3 without firing a hook), `files` (relative path to content, written in the cwd),
177
+ `run` (a list of commands run in the cwd, in order, each as an argv array — never a shell string —
178
+ in which `$1`, `$2`, … are replaced by the `match` capture groups; an entry may instead be
179
+ `{ "argv": [...], "allowFailure": true }` or `{ "files": {...} }` to write files between commands),
180
+ `commit` (`git add -A` and commit with that message) and `stopFailure` (fire StopFailure instead of
181
+ Stop) and `error` (a string: the StopFailure `error` reason, which implies `stopFailure`). Commands get only `PATH`, `HOME`, `TMPDIR`, `LANG`, `LC_ALL` and `GIT_*` from the
182
+ environment and a 30 s timeout. A command that exits non-zero (without `allowFailure`) or a failing
183
+ `git commit` fails the turn: a message on stderr, StopFailure instead of Stop, exit code 1 with
184
+ `--fake-no-hooks`.
185
+
186
+ `--session-id` together with `--resume` or `--continue`, without `--fork-session`, exits 2 with real
187
+ claude's own message on stderr, before anything else happens. Everything after a literal `--` is the
188
+ prompt in interactive mode, and `-p` is print mode only when it appears before `--`.
189
+
190
+ ### `bin/fake-herdr.mjs`
191
+
192
+ `FAKE_HERDR_STATE` (required) is the path of the JSON state file this process reads and writes.
193
+ Each invocation holds a lock, the directory `<FAKE_HERDR_STATE>.lock`, for its whole run so that
194
+ concurrent invocations do not lose updates; it waits up to 30 s for it, and releases it on exit,
195
+ SIGTERM (exit 143) and SIGINT (exit 130).
196
+
197
+ | Variable | Effect |
198
+ | ----------------------- | --------------------------------------------------------------------------------------------- |
199
+ | `FAKE_HERDR_LOG` | Path; appends one JSON line with the argv of every invocation. |
200
+ | `FAKE_HERDR_FAIL_PHASE` | Makes one subcommand always fail with a JSON error on stderr. One of the phases listed below. |
201
+ | `FAKE_HERDR_FAIL_CODE` | The error code `FAKE_HERDR_FAIL_PHASE` reports (default `boom`). |
202
+
203
+ Failure phases: `create`, `tab_create`, `run`, `rename` (`workspace rename` and `tab rename`),
204
+ `close` (`workspace close`, `tab close` and `pane close`), `reclaim` (only a `tab close` of a tab
205
+ still showing herdr's default label), `tab_create_and_close` (both `tab create` and `tab close`),
206
+ `worktree_create` and `worktree_remove`.
207
+
208
+ `pane exit <pane_id>` is not a real herdr command. It models an agent process finishing inside its
209
+ pane: the pane goes idle while the pane, its tab and its label stay as they are.
210
+
211
+ A tab's displayed default label is its live position, so it renumbers after an earlier tab closes.
212
+ `tab focus` is globally exclusive: focusing a tab unfocuses every other tab. `worktree remove`
213
+ prints JSON on success because `@ligeti/step-git-worktree`'s `runHerdr` rejects empty stdout.
214
+
215
+ `worktree create/list/remove` run a real `git` for the checkout, so the directory exists on disk
216
+ afterwards. `--branch` is tried as a new branch first, then as an existing one. Closing a tab's last
217
+ pane closes the tab, and closing a workspace's last tab closes the workspace.
218
+
219
+ ## Environment variables
220
+
221
+ | Variable | Required | Default | Purpose |
222
+ | -------------------------- | -------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
223
+ | `LIGETI_TEST_DATABASE_URL` | no | `postgresql://ligeti:ligeti@localhost:5434/postgres` | Admin connection `createTestDatabase` creates and drops throwaway databases against; defaults to the local `compose.yaml` instance. |
224
+
225
+ `src/postgres.ts` reads this variable directly from `process.env`, with no `settings.ts` module —
226
+ an enumerated exception under [ADR-0003](../../adr/0003-configuration-is-a-settings-module.md),
227
+ permitted because this package is test infrastructure only and never reaches a production code
228
+ path. `CI_COMMIT_REF_SLUG` is also read directly, under the same exception, to name a throwaway
229
+ database after the branch that created it (see below).
230
+
231
+ ## Throwaway databases and cleanup
232
+
233
+ `LIGETI_TEST_DATABASE_URL` supplies only the host, port and credentials — the admin connection is
234
+ always made to the `postgres` database, so the URL's own database component may name anything or
235
+ nothing. Each throwaway database `createTestDatabase` creates is called
236
+ `ligeti_test_<branch slug>_<random>`, so one left behind by a crashed run names the branch that
237
+ made it. `pnpm test:db:clean` (`bin/clean-test-databases.mjs`) drops the leftovers: it skips any
238
+ database with an open connection or younger than `--max-age-hours` (24 by default), and
239
+ `--dry-run` lists what it would drop. Run it by hand — never while other worktrees are testing.
240
+
241
+ The `real-claude` test tier's own prerequisites (`LIGETI_TEST_AGENT_WORKDIR`,
242
+ `LIGETI_CLAUDE_CONFIG_DIR`) are that tier's own facts, not this package's — see
243
+ [`tests/acceptance/README.md`](../../tests/acceptance/README.md).
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ // ABOUTME: Records its own argv/env/cwd (and stdin, if any) to a JSON file for assertions in
3
+ // ABOUTME: subprocess-backend tests (spawn env allow-list, argv passed through, cwd honoured).
4
+
5
+ function readStdinIfPiped() {
6
+ if (process.stdin.isTTY) {
7
+ return Promise.resolve("");
8
+ }
9
+ return new Promise((resolve) => {
10
+ const chunks = [];
11
+ let settled = false;
12
+ const finish = (value) => {
13
+ if (!settled) {
14
+ settled = true;
15
+ resolve(value);
16
+ }
17
+ };
18
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
19
+ process.stdin.on("end", () => {
20
+ finish(Buffer.concat(chunks).toString("utf8"));
21
+ });
22
+ process.stdin.on("error", () => {
23
+ finish("");
24
+ });
25
+ setTimeout(() => {
26
+ finish("");
27
+ }, 200).unref();
28
+ });
29
+ }
30
+
31
+ async function main() {
32
+ const outPath = process.env.AGENT_RECORDER_OUT ?? process.argv[2];
33
+ if (!outPath) {
34
+ console.error("argv-recorder: AGENT_RECORDER_OUT env var or first argv required");
35
+ process.exitCode = 2;
36
+ return;
37
+ }
38
+ const stdin = await readStdinIfPiped();
39
+ const record = {
40
+ argv: process.argv.slice(2),
41
+ env: { ...process.env },
42
+ cwd: process.cwd(),
43
+ stdin,
44
+ pid: process.pid,
45
+ };
46
+ const { writeFileSync } = await import("node:fs");
47
+ writeFileSync(outPath, JSON.stringify(record));
48
+ }
49
+
50
+ main().catch((err) => {
51
+ console.error(err);
52
+ process.exitCode = 1;
53
+ });
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env node
2
+ // ABOUTME: Sweeps throwaway `ligeti_test_*` databases left behind by crashed test runs, skipping
3
+ // ABOUTME: any that still has a connection or is younger than --max-age-hours. Run by hand.
4
+
5
+ import { Client } from "pg";
6
+
7
+ const DEFAULT_ADMIN_URL = "postgresql://ligeti:ligeti@localhost:5434/postgres";
8
+ const ADMIN_DATABASE = "postgres";
9
+
10
+ const NAME_PATTERN = "ligeti\\_test\\_%";
11
+
12
+ const DEFAULT_MAX_AGE_HOURS = 24;
13
+
14
+ const USAGE =
15
+ "usage: node packages/testing/bin/clean-test-databases.mjs [--max-age-hours=N] [--dry-run]";
16
+
17
+ function parseArgs(argv) {
18
+ let maxAgeHours = DEFAULT_MAX_AGE_HOURS;
19
+ let dryRun = false;
20
+
21
+ for (const arg of argv) {
22
+ if (arg === "--dry-run") {
23
+ dryRun = true;
24
+ continue;
25
+ }
26
+ const age = /^--max-age-hours=(\d+(?:\.\d+)?)$/.exec(arg);
27
+ if (age) {
28
+ maxAgeHours = Number(age[1]);
29
+ continue;
30
+ }
31
+ throw new Error(`unknown argument ${JSON.stringify(arg)}`);
32
+ }
33
+
34
+ return { maxAgeHours, dryRun };
35
+ }
36
+
37
+ function adminUrl() {
38
+ const url = new URL(process.env.LIGETI_TEST_DATABASE_URL ?? DEFAULT_ADMIN_URL);
39
+ url.pathname = `/${ADMIN_DATABASE}`;
40
+ return url.toString();
41
+ }
42
+
43
+ function withoutPassword(url) {
44
+ const parsed = new URL(url);
45
+ if (parsed.password) {
46
+ parsed.password = "***";
47
+ }
48
+ return parsed.toString();
49
+ }
50
+
51
+ const WITH_AGE = `
52
+ SELECT d.datname,
53
+ (pg_stat_file('base/' || d.oid || '/PG_VERSION')).modification AS created,
54
+ (SELECT count(*) FROM pg_stat_activity a WHERE a.datname = d.datname) AS connections
55
+ FROM pg_database d
56
+ WHERE d.datname LIKE $1
57
+ ORDER BY created`;
58
+
59
+ const WITHOUT_AGE = `
60
+ SELECT d.datname,
61
+ NULL AS created,
62
+ (SELECT count(*) FROM pg_stat_activity a WHERE a.datname = d.datname) AS connections
63
+ FROM pg_database d
64
+ WHERE d.datname LIKE $1
65
+ ORDER BY d.datname`;
66
+
67
+ async function listCandidates(client) {
68
+ try {
69
+ const result = await client.query(WITH_AGE, [NAME_PATTERN]);
70
+ return { rows: result.rows, ageKnown: true };
71
+ } catch (error) {
72
+ if (error.code !== "42501") {
73
+ throw error;
74
+ }
75
+ const result = await client.query(WITHOUT_AGE, [NAME_PATTERN]);
76
+ return { rows: result.rows, ageKnown: false };
77
+ }
78
+ }
79
+
80
+ async function main() {
81
+ const { maxAgeHours, dryRun } = parseArgs(process.argv.slice(2));
82
+ const url = adminUrl();
83
+ const client = new Client({ connectionString: url });
84
+
85
+ try {
86
+ await client.connect();
87
+ } catch (cause) {
88
+ throw new Error(`could not connect to ${withoutPassword(url)}. Is Postgres running?`, {
89
+ cause,
90
+ });
91
+ }
92
+
93
+ let dropped = 0;
94
+ let kept = 0;
95
+
96
+ try {
97
+ const { rows, ageKnown } = await listCandidates(client);
98
+ if (!ageKnown) {
99
+ console.warn(
100
+ "warning: not permitted to read database creation times, so --max-age-hours is ignored " +
101
+ "and only databases with no open connection are dropped.",
102
+ );
103
+ }
104
+
105
+ const cutoff = Date.now() - maxAgeHours * 60 * 60 * 1000;
106
+
107
+ for (const row of rows) {
108
+ const connections = Number(row.connections);
109
+ if (connections > 0) {
110
+ console.log(`keep ${row.datname} (${connections} open connection(s))`);
111
+ kept += 1;
112
+ continue;
113
+ }
114
+ if (ageKnown && row.created.getTime() > cutoff) {
115
+ console.log(`keep ${row.datname} (created ${row.created.toISOString()})`);
116
+ kept += 1;
117
+ continue;
118
+ }
119
+ if (dryRun) {
120
+ console.log(`would drop ${row.datname}`);
121
+ dropped += 1;
122
+ continue;
123
+ }
124
+ try {
125
+ await client.query(`DROP DATABASE "${row.datname}"`);
126
+ console.log(`drop ${row.datname}`);
127
+ dropped += 1;
128
+ } catch (error) {
129
+ console.log(`keep ${row.datname} (${error.message})`);
130
+ kept += 1;
131
+ }
132
+ }
133
+ } finally {
134
+ await client.end();
135
+ }
136
+
137
+ console.log(`${dryRun ? "would drop" : "dropped"} ${dropped}, kept ${kept}`);
138
+ }
139
+
140
+ try {
141
+ await main();
142
+ } catch (error) {
143
+ console.error(`clean-test-databases: ${error.message}`);
144
+ console.error(USAGE);
145
+ process.exitCode = 1;
146
+ }