@r5n/ariadne 0.0.0-stage → 0.2.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.
- package/LICENSE +201 -0
- package/README.md +110 -2
- package/dist/cli.js +148 -0
- package/package.json +41 -4
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 R5N Labs
|
|
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,111 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/r5n-labs/clis/develop/packages/ariadne/assets/logo.svg" width="128" alt="Ariadne logo: a thread winding through a labyrinth to its centre">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
# Ariadne
|
|
6
|
+
|
|
7
|
+
**Give coding agents a thread through every task.**
|
|
8
|
+
|
|
9
|
+
Ariadne (`ari`) gives each task a contract that says what "done" means, gates that the CLI evaluates itself, and a memory that stays small as the project grows. An agent never closes a task by describing it: `ari done` runs the contract's checks, compares the diff with the declared scope and records the evidence, and CI can verify that evidence later. It works with any agent that can run a shell command, and with people.
|
|
10
|
+
|
|
11
|
+
Requires [Bun](https://bun.sh) and git.
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
Install it with Bun, then initialise it in a repository that has at least one commit:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
bun add -g @r5n/ariadne
|
|
19
|
+
ari init --agents claude --git-hooks
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
To try an unreleased change, build it from this repository and link the single-file CLI onto your `PATH` instead:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
bun install
|
|
26
|
+
bun --filter @r5n/ariadne build
|
|
27
|
+
ln -s "$PWD/packages/ariadne/dist/cli.js" ~/.local/bin/ari
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`ari init` creates `.ari/config.json`, writes a short managed block into `AGENTS.md` that teaches any agent the loop below, and installs the hooks you ask for. Running it again changes nothing.
|
|
31
|
+
|
|
32
|
+
Create a task and write its contract:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
ari new "Add profile inheritance" --scope "src/profiles/**"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Edit `.ari/tasks/add-profile-inheritance.md`: list acceptance criteria, bind each one to a check command, and optionally lock files that must not change. Then:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
ari ready add-profile-inheritance
|
|
42
|
+
ari start add-profile-inheritance
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## The loop
|
|
46
|
+
|
|
47
|
+
| Step | Command | What happens |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| Ask what to do | `ari next` | Prints exactly one next action, from the records alone |
|
|
50
|
+
| Work | | Change only files inside the task's `scope` |
|
|
51
|
+
| Check | `ari check` | Evaluates the current stage's gates without recording an attempt |
|
|
52
|
+
| Finish the stage | `ari done` | Records evidence and advances, or prints every failing gate with its output and exits 1 |
|
|
53
|
+
| Ask a human | `ari block <id> --reason <question>` | A person answers with `ari resolve <id> --answer <text>` |
|
|
54
|
+
| Remember | `ari note "<text>"` | Adds a task note; `--global` adds project knowledge |
|
|
55
|
+
| Reload context | `ari context` | Prints the task's context pack within a token budget |
|
|
56
|
+
|
|
57
|
+
After a failed `ari done` the task keeps its attempt; when the attempt budget (3 by default) is spent, the task is blocked for a human. A changed contract, pack or gate configuration needs `ari amend <id> --reason <text>`. `ari approve <id>` records a human approval for stages that need one; it holds for the working tree the person approved, so a later change needs a new approval, whether a person, an agent or a check makes it.
|
|
58
|
+
|
|
59
|
+
## Packs
|
|
60
|
+
|
|
61
|
+
A pack is a methodology written as data: an ordered list of stages, each with an instruction and gates.
|
|
62
|
+
|
|
63
|
+
| Pack | Stages |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `basic` | implement |
|
|
66
|
+
| `sdlc` | design (needs a design document and an approval), implement, review (which runs every check again) |
|
|
67
|
+
| `tdd` | red (the checks must fail), green, refactor (tests unchanged) |
|
|
68
|
+
| `bugfix` | reproduce, fix (a regression check fails on the base commit and passes now) |
|
|
69
|
+
| `spec-driven` | specify (approved), implement |
|
|
70
|
+
| `refactor` | refactor (tests unchanged) |
|
|
71
|
+
| `spike` | explore (a write-up in `.ari/designs/`) |
|
|
72
|
+
|
|
73
|
+
Choose the default with `ari init --pack tdd`, or per task with `ari new --pack bugfix`. A project can add its own packs in `.ari/packs/<name>.yaml`.
|
|
74
|
+
|
|
75
|
+
## Memory
|
|
76
|
+
|
|
77
|
+
Memory is tiered by how often it changes:
|
|
78
|
+
|
|
79
|
+
| Tier | Where | Lifetime |
|
|
80
|
+
| --- | --- | --- |
|
|
81
|
+
| Journal | the worktree's git directory (untracked) | until the task is done and consolidated |
|
|
82
|
+
| Task notes | the task record | with the task |
|
|
83
|
+
| Knowledge | `.ari/knowledge/*.md` | until archived |
|
|
84
|
+
|
|
85
|
+
`ari sleep` consolidates memory: it runs after every finished task and before an agent compacts its context. It prunes journals, archives duplicates and stale entries, keeps the knowledge within its byte budget and reports what needs judgement.
|
|
86
|
+
|
|
87
|
+
## Integrations
|
|
88
|
+
|
|
89
|
+
| Layer | Works with | Set up with |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| Instructions | every agent that reads `AGENTS.md` | `ari init` |
|
|
92
|
+
| Self-description | every agent with a shell | `ari --help --json` |
|
|
93
|
+
| Git hooks | every agent and person | `ari hooks install --agent git` (`pre-commit` runs `ari scope --staged`, `pre-push` runs `ari verify`) |
|
|
94
|
+
| CI | everything merged | `ari verify --base <ref>` as a required check, on a checkout with the full history |
|
|
95
|
+
| Agent hooks | Claude Code, Codex CLI, Gemini CLI; Cursor and GitHub Copilot CLI in part | `ari hooks install --agent <name>` |
|
|
96
|
+
| Headless runs | agents with a non-interactive mode | `ari run --agent <name>` with `agents.<name>.command` in `.ari/config.json` |
|
|
97
|
+
|
|
98
|
+
Agent hooks give early feedback: they deny edits and plain shell writes outside the scope, inside locked files or to ari's own records, refuse `ari approve` and commits that skip git hooks, keep the agent working until `ari done` has passed, and load the context pack when a session starts. The shell hook catches common mistakes. It [does not resolve shell code](https://github.com/r5n-labs/clis/blob/develop/packages/ariadne/docs/design.md#what-the-shell-hook-is-for), so an agent can get past it; `ari done`, `ari verify`, the git hooks and CI decide. `ari hooks uninstall --agent <name>` removes the hooks again. Ariadne never adds permission-bypass flags to an agent command.
|
|
99
|
+
|
|
100
|
+
Every command that reports data accepts the global `--json` flag and then writes exactly one JSON document to stdout. Exit code 1 means a failure, including failing gates; exit code 2 means a usage error such as an unknown option.
|
|
101
|
+
|
|
102
|
+
## Documentation
|
|
103
|
+
|
|
104
|
+
- [Command reference](https://github.com/r5n-labs/clis/blob/develop/packages/ariadne/docs/reference.md): every command, its options, JSON output, exit codes and the hook adapters
|
|
105
|
+
- [Design](https://github.com/r5n-labs/clis/blob/develop/packages/ariadne/docs/design.md): contracts, gates, packs, memory and verification in detail
|
|
106
|
+
|
|
107
|
+
Checks, invariants and review commands are shell commands from the repository, run with the same trust as package scripts. Review a repository's `.ari/` before running `ari done` inside it.
|
|
108
|
+
|
|
109
|
+
## Licence
|
|
110
|
+
|
|
111
|
+
[Apache 2.0](LICENSE).
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
+
// @bun
|
|
3
|
+
import{homedir as wA}from"os";import{join as $A}from"path";class _t extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function L(t){return t}function so(t){return t==null?[]:Array.isArray(t)?t:[t]}function Tf(t,e,n,r){var s,o=t[e],i=~r.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((s=+n,s*0===0)?s:n),!!n):(s=+n,s*0===0)?s:n;t[e]=o==null?i:Array.isArray(o)?o.concat(i):[o,i]}function oo(t,e){t=t||[],e=e||{};var n,r,s,o,i,a={_:[]},c=0,l=0,u=0,d=t.length;let p=e.alias!==void 0,f=e.unknown!==void 0,m=e.default!==void 0;if(e.alias=e.alias||{},e.string=so(e.string),e.boolean=so(e.boolean),p)for(n in e.alias){r=e.alias[n]=so(e.alias[n]);for(c=0;c<r.length;c++)(e.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=e.boolean.length;c-- >0;){r=e.alias[e.boolean[c]]||[];for(l=r.length;l-- >0;)e.boolean.push(r[l])}for(c=e.string.length;c-- >0;){r=e.alias[e.string[c]]||[];for(l=r.length;l-- >0;)e.string.push(r[l])}if(m){for(n in e.default)if(o=typeof e.default[n],r=e.alias[n]=e.alias[n]||[],e[o]!==void 0){e[o].push(n);for(c=0;c<r.length;c++)e[o].push(r[c])}}let h=f?Object.keys(e.alias):[];for(c=0;c<d;c++){if(s=t[c],s==="--"){a._=a._.concat(t.slice(++c));break}for(l=0;l<s.length;l++)if(s.charCodeAt(l)!==45)break;if(l===0)a._.push(s);else if(s.substring(l,l+3)==="no-"){if(o=s.substring(l+3),f&&!~h.indexOf(o))return e.unknown(s);a[o]=!1}else{for(u=l+1;u<s.length;u++)if(s.charCodeAt(u)===61)break;o=s.substring(l,u),i=s.substring(++u)||(c+1===d||(""+t[c+1]).charCodeAt(0)===45||t[++c]),r=l===2?[o]:o;for(u=0;u<r.length;u++){if(o=r[u],f&&!~h.indexOf(o))return e.unknown("-".repeat(l)+o);Tf(a,o,u+1<r.length||i,e)}}}if(m){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(p)for(n in a){r=e.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var ft=0,kn=1,Ma=2,Ga=255;function ir(t){return Number.isInteger(t)&&t>=0&&t<=255}class g extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class v extends g{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var Fa=1,vf=2,cr="--",Ka="-",de="no-",Cf=new Set(["false","true"]),bn=/^--([^=]+)(?:=(.*))?$/s,xn=/^-([^-=][^=]*)(?:=(.*))?$/s,co=/^(?:---|-no-|-_|-[^-=][^=]*_)/,Af="_",wn="\x00";function Pt(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function We(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(t)){if(r.type==="boolean")e.boolean.push(n);else e.string.push(n);if(r.alias)e.alias[r.alias]=n;let s=Pt(n);if(s!==n)e.alias[s]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function ar(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...s}=oo(pr(t,Of),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),o=Object.entries(s).map(([i,a])=>[io(i),io(a)]);return{...Object.fromEntries(o),_:r.map(io)}}function Of(t){if(t===Ka)return`${wn}${t}`;let e=bn.exec(t);if(co.test(t)||Rf(e?.[1]))return`--${wn}${t}`;return(e?e[2]:xn.exec(t)?.[2])===""?`${t}${wn}`:t}function Rf(t){if(t===void 0)return!1;let e=t.startsWith(de)?t.slice(de.length):t;return e===Af||e in Object.prototype}function io(t){return typeof t==="string"&&t.startsWith(wn)?t.slice(wn.length):t}function $n(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function Be(t,e){if(Object.hasOwn(e,t))return`--${Pt(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${Pt(n)}`;return t.length===Fa?`-${t}`:`--${t}`}function lr(t,e,n,r){let{alias:s}=We(e),o=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(s,i));if(o!==void 0)throw new v(`Unknown option: ${If(o,r)}`,n)}function If(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(cr);for(let r of n<0?e:e.slice(0,n)){let s=bn.exec(r)?.[1];if(s===t||r===`--${de}${t}`)return`--${s}`;if(s===void 0&&xn.exec(r)?.[1]?.includes(t))return`-${t}`}return Be(t,{})}function Ua(t,e){for(let[r,s]of Object.entries(t))if(Array.isArray(s))throw new v(`${Be(r,e)} can only be provided once`);let n={...t};for(let[r,s]of Object.entries(e)){let o=t[r];if(o===void 0)continue;if(s.type==="string"&&typeof o==="boolean")throw Ba(Be(r,e));if(s.type!=="number")continue;let i=Number(o);if(typeof o==="boolean"||typeof o==="string"&&o.trim().length===0||!Number.isFinite(i)){let a=Be(r,e);throw new v(`Invalid number for ${a}: "${o}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Ba(t){return new v(`${t} needs a value`,`Use ${t}=<value>`)}function ur(t,e){let n=We(e),r=uo([...t],n),s=ar(r,n)._[0],o=s===void 0?-1:r.indexOf(s);return{before:o>=0?t.slice(0,o):[...t],command:s,restArgs:o>=0?t.slice(o+1):[]}}function Wa(t,e){let n=We(e);for(let r=0;r<t.length;r+=1){let s=t[r]??"";if(s===cr)return-1;if(s===Ka||!s.startsWith("-"))return r;if(_f(s,n,e))r+=1}return-1}function _f(t,e,n){if(t.startsWith(`--${de}`))return!1;let r=bn.exec(t),s=r??xn.exec(t);if(!s||s[2]!==void 0)return!1;let o=r?s[1]??"":s[1]?.at(-1)??"",i=n[$n(o,e)]?.type;return i==="string"||i==="number"}function lo(t,e,n=e){let r=We(e),{before:s,command:o,restArgs:i}=ur(t,e),a=We(n);ao(s,r,e,!0),ao(t,a,n,!0);let{_:c,...l}=ar(Va(s,r,e),r);lr(l,e,"Place command options after the command name",s);let{_:u,...d}=ar(uo(i,a),a),p=Ua({...Ha(l,e,r),...Ha(d,n,a)},e);return{command:o,flags:p,restArgs:i}}function Ha(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function dr(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function Sn(t,e={}){let n=We(e),r=Pf(t,n);ao(r,n,e);let s=ar(Va(r,n,e),n),{_:o,...i}=s;return{args:Ua(i,e),rawPositionals:o.map(String)}}function ao(t,e,n,r=!1){let s=new Set;for(let o of t){if(o===cr)break;let i=o.match(/^-+/)?.[0];if(!i||co.test(o))continue;let a=o.slice(i.length),c=a.split("=",Fa)[0]??"",l=a.startsWith(de)?[a.slice(de.length)]:i.length===vf?[c]:[...c];for(let u of l){let d=$n(u,e);if(r&&!Object.hasOwn(n,d))continue;if(s.has(d))throw new v(`${Be(d,n)} can only be provided once`);s.add(d)}}}function pr(t,e){let n=t.indexOf(cr);return t.map((r,s)=>n>=0&&s>=n?r:e(r,t[s+1]))}function uo(t,e){return pr(t,(n)=>{let r=bn.exec(n)??xn.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${de}`))return n;let s=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes($n(s,e))?`${n}=true`:n})}function Va(t,e,n){let r=(i)=>n[$n(i,e)]?.type,s=(i)=>i!==void 0&&!i.startsWith("-"),o=pr(t,(i,a)=>{let c=bn.exec(i),l=c?null:xn.exec(i);if(i.startsWith(`--${de}`)||co.test(i))return i;let u=c?[c[1]??""]:[...l?.[1]??""],d=c?c[2]:l?.[2];for(let[p,f]of u.entries()){let m=r(f),h=p===u.length-1,y=Be($n(f,e),n),x=!h||d===void 0&&!s(a);if(m==="string"&&(x||d===""))throw Ba(y);if(m==="number"&&x)throw new v(`${y} needs a value`,`Use ${y}=<number>`);if(m==="boolean"&&h&&d!==void 0&&!Cf.has(d))throw new v(`Invalid value for ${y}: "${d}"`,`Use ${y}=true or ${y}=false`)}return i});return uo(o,e)}function Pf(t,e){return pr(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,s,o)=>{let i=e.alias[s];return i&&e.boolean.includes(i)?`--${i}${o??""}`:r}))}function mr(t,e){let n={},r=Object.entries(e);for(let[s,[o,i]]of r.entries())n[o]=i.variadic?t.slice(s):t[s];return n}function fr(t,e){for(let[n,r]of Object.entries(e)){if(!r.required)continue;let s=t[n];if(Array.isArray(s)?s.length===0:!s)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function Ja(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var Nf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Df=new Set(["help","json"]),jf=/^[a-zA-Z0-9]$/,Lf=new Set(["h","j"]);function gr(){return(t)=>{let e={args:t.args??{},description:t.description,examples:t.examples??[],json:t.json??!1,name:t.name,passthrough:t.passthrough??!1,positionals:t.positionals??{},prompts:t.prompts??!1,run:t.run,strict:t.strict??!0,subcommands:t.subcommands??[]};return Mf(e),Object.freeze(e)}}function hr(t,e){let n=po(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function Mf(t){let e=`Command "${t.name}"`;if(!Nf.test(t.name))throw Error(`${e} must be named with a lower-case word such as "list" or "dry-run"`);if(!t.run&&t.subcommands.length===0)throw Error(`${e} needs run or subcommands`);for(let[u,d]of Object.entries(t.args)){if(Df.has(Pt(u)))throw Error(`${e} cannot define the option "${u}": --${Pt(u)} is a global flag`);if(d.alias!==void 0&&Lf.has(d.alias))throw Error(`${e} cannot give "${u}" the alias -${d.alias}: it belongs to a global flag`)}let n=Object.keys(t.args).map(Pt),r=po(n);if(r!==void 0)throw Error(`${e} has more than one option named --${r}`);let s=Object.values(t.args).flatMap((u)=>u.alias??[]),o=s.find((u)=>!jf.test(u));if(o!==void 0)throw Error(`${e} uses the alias "${o}": an alias is one letter or digit`);let i=s.find((u)=>n.includes(u));if(i!==void 0)throw Error(`${e} uses the alias -${i}, which is also an option's name`);let a=po(s);if(a!==void 0)throw Error(`${e} uses the alias -${a} more than once`);let c=Object.keys(t.positionals),l=c.find((u)=>t.positionals[u]?.variadic);if(l!==void 0&&l!==c.at(-1))throw Error(`${e} declares the variadic positional "${l}" before other positionals`);if(t.passthrough&&(!t.run||l===void 0))throw Error(`${e} uses passthrough, which needs run and a variadic last positional`);hr(e,t.subcommands)}function po(t){return t.find((e,n)=>t.indexOf(e)!==n)}function nt(t){return t}import{Console as qf}from"console";import{Writable as Yf}from"stream";import{format as Xf,stripVTControlCharacters as zf}from"util";var pe={active:!1};var Gf=new Set(["0","false"]);function kr(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!Gf.has(e);return t?.isTTY===!0}var Hf=kr(process.stdout),Xa=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ff=["bold","dim","italic","underline","reset"],za={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Kf={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},Uf={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},qa={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function yr(t){return(e)=>Hf&&!pe.active?`${t}${e}${za.reset}`:e}function Bf(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Ya({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&Bf(n)?n:Kf[e];if(!r)return"";return t&&r in qa?qa[r]:r}var Wf=Xa.reduce((t,e)=>{let n=Ya({color:e});if(n)t[e]=yr(n);let r=Ya({bright:!0,color:e});if(r)t[`${e}Bright`]=yr(r);return t},{}),Vf=Ff.reduce((t,e)=>(t[e]=yr(za[e]),t),{}),Jf=Xa.reduce((t,e)=>{let n=Uf[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=yr(n)}return t},{}),G={...Wf,...Vf,...Jf};var Zf=2,tc=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],Qf=[...tc,"trace","write"],tg=1,eg="EPIPE",ng="EIO",B={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function En(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function mo(t){return En()&&!pe.active&&t?.json!==!0}function ec(){return pe.active}function me(t){let e=JSON.stringify(t??null,null,Zf);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
|
|
4
|
+
`}function nc(){return B.documentWritten}function rc(){B.sealed=!0}function Jt(t){if(B.documentWritten=!0,B.sealed||B.stdoutClosed)return;let e=B.stdoutWrite??process.stdout.write;try{e.call(process.stdout,t)}catch(n){if(!wr(n,process.stdout))throw n;B.stdoutClosed=!0}}function sc(){if(B.outputGuarded)return;B.outputGuarded=!0,process.stdout.write=Za(process.stdout.write,!0),console.write=Za(console.write,0),process.stdout.on("error",(t)=>{if(!wr(t,process.stdout))throw t;B.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!wr(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>B.closedStreams.add(t))}function Za(t,e){let n=(r)=>{let s=r.at(-1);if(typeof s==="function")queueMicrotask(()=>s());return e};return function(...s){if(B.stdoutClosed)return n(s);try{return t.apply(this,s)}catch(o){if(!wr(o,process.stdout))throw o;return B.stdoutClosed=!0,n(s)}}}function wr(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===eg||n===ng&&e.isTTY===!0}function $r(){let t=kr(process.stderr);return new Yf({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:zf(e)),r()}})}async function oc(t,e){if(!t)return e();B.jsonRuns+=1,B.restoreStdout??=rg(),pe.active=!0;try{return await e()}finally{if(B.jsonRuns-=1,pe.active=B.jsonRuns>0,!pe.active&&!B.outputGuarded)B.restoreStdout?.(),B.restoreStdout=void 0}}async function ic(t){let e=Promise.all([B.stdoutClosed?void 0:Qa(process.stdout),Qa(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Qa(t){if(t.writableFinished||B.closedStreams.has(t))return Promise.resolve();return new Promise((e)=>{t.once("close",e),t.once("finish",e),t.once("error",()=>e()),t.end(()=>e())})}function rg(){let t=process.stdout.write,e=new qf({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(Qf.map((s)=>[s,console[s]])),r=Object.fromEntries(tc.map((s)=>[s,e[s].bind(e)]));return B.stdoutWrite=t,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:sg(e),write:og}),()=>{process.stdout.write=t,Object.assign(console,n),B.stdoutWrite=void 0}}function sg(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let s=r.stack?.split(`
|
|
5
|
+
`).slice(tg)??[];t.error([`Trace: ${Xf(...n)}`,...s].join(`
|
|
6
|
+
`))};return e}function og(...t){let e=Buffer.concat(t.map(ig));return process.stderr.write(e),e.byteLength}function ig(t){if(typeof t==="string")return Buffer.from(t);return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t)}var Et={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},Ve={help:Et.help,json:Et.json},Te="help",br={[ft]:"success",[kn]:"failure",[Ma]:"usage error"};import{stripVTControlCharacters as So}from"util";import{stdout as bc,stdin as $g}from"process";import bg from"readline";var ac=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),cc=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,lc=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var ag=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,cg=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,uc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,lg=/\t{1,1000}/y,dc=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,ug=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,dg=/\p{M}+/gu,pg={limit:1/0,ellipsis:""},pc=(t,e={},n={})=>{let r=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?pc(s,pg,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,u=2,d=n.regularWidth??1,p=n.wideWidth??2,f=[[ug,d],[ag,0],[cg,a],[lg,c],[dc,l],[uc,p]],m=0,h=0,y=t.length,x=0,b=!1,H=y,M=Math.max(0,r-o),T=0,D=0,S=0,w=0;t:while(!0){if(D>T||h>=y&&h>m){let j=t.slice(T,D)||t.slice(m,h);x=0;for(let ct of j.replaceAll(dg,"")){let kt=ct.codePointAt(0)||0;if(cc(kt))w=2;else if(lc(kt))w=p;else w=d;if(S+w>M)H=Math.min(H,Math.max(T,m)+x);if(S+w>r){b=!0;break t}x+=ct.length,S+=w}T=D=0}if(h>=y)break t;for(let j=0,ct=f.length;j<ct;j++){let[kt,La]=f[j];if(kt.lastIndex=h,kt.test(t)){if(x=kt===uc?ac(t.slice(h,kt.lastIndex)):kt===dc?1:kt.lastIndex-h,w=x*La,S+w>M)H=Math.min(H,h+Math.floor((M-S)/La));if(S+w>r){b=!0;break t}S+=w,T=m,D=h,h=m=kt.lastIndex;continue t}}h+=1}return{width:b?M:S,index:b?H:y,truncated:b,ellipsed:b&&r>=o}},mc=pc;var mg={limit:1/0,ellipsis:"",ellipsisWidth:0},fg=(t,e={})=>mc(t,mg,e).width,Tt=fg;var xr="\x1B",kc="\x9B",gg=39,go="\x07",wc="[",hg="]",$c="m",ho=`${hg}8;;`,fc=new RegExp(`(?:\\${wc}(?<code>\\d+)m|\\${ho}(?<uri>.*)${go})`,"y"),gc=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},hc=(t)=>`${xr}${wc}${t}${$c}`,yc=(t)=>`${xr}${ho}${t}${go}`,fo=(t,e,n)=>{let r=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:Tt(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=Tt(d);if(a+p<=n)t[t.length-1]+=d;else t.push(d),a=0;if(d===xr||d===kc)s=!0,o=e.startsWith(ho,u+1);if(s){if(o){if(d===go)s=!1,o=!1}else if(d===$c)s=!1}else if(a+=p,a===n&&!l.done)t.push(""),a=0;c=l,l=r.next(),u+=d.length}if(i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1)t[t.length-2]+=t.pop()},yg=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Tt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},kg=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",s,o,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=Tt(h)}if(d!==0){if(c>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let f=Tt(p);if(n.hard&&f>e){let m=e-c,h=1+Math.floor((f-m-1)/e);if(Math.floor((f-1)/e)<h)a.push("");fo(a,p,e),c=Tt(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(n.wordWrap===!1&&c<e){fo(a,p,e),c=Tt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&n.wordWrap===!1){fo(a,p,e),c=Tt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}if(n.trim!==!1)a=a.map((d)=>yg(d));let l=a.join(`
|
|
7
|
+
`),u=!1;for(let d=0;d<l.length;d++){let p=l[d];if(r+=p,!u){if(u=p>="\uD800"&&p<="\uDBFF",u)continue}else u=!1;if(p===xr||p===kc){fc.lastIndex=d+1;let m=fc.exec(l)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);s=h===gg?void 0:h}else if(m?.uri!==void 0)o=m.uri.length===0?void 0:m.uri}if(l[d+1]===`
|
|
8
|
+
`){if(o)r+=yc("");let f=s?gc(s):void 0;if(s&&f)r+=hc(f)}else if(p===`
|
|
9
|
+
`){if(s&&gc(s))r+=hc(s);if(o)r+=yc(o)}}return r},wg=/\r?\n/;function Je(t,e,n){return String(t).normalize().split(wg).map((r)=>kg(r,e,n)).join(`
|
|
10
|
+
`)}var Nt={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var Tn={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Nt.up():"");if(t)e+=Nt.left;return e}};function Er(t,e,n){if(!n.some((i)=>!i.disabled))return t;let r=t+e,s=Math.max(n.length-1,0),o=r<0?s:r>s?0:r;return n[o]?.disabled?Er(o,e<0?-1:1,n):o}var xg=["up","down","left","right","space","enter","cancel"],Sg=["January","February","March","April","May","June","July","August","September","October","November","December"],vt={actions:new Set(xg),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...Sg],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function xc(t){if(t!==void 0)return t;if(vt.accessible!==void 0)return vt.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function Sc(t,e){if(typeof t=="string")return vt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Sc(n,e))return!0;return!1}function Eg(t,e){if(t===e)return;let n=t.split(`
|
|
11
|
+
`),r=e.split(`
|
|
12
|
+
`),s=Math.max(n.length,r.length),o=[];for(let i=0;i<s;i++)n[i]!==r[i]&&o.push(i);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:s}}var cO=globalThis.process.platform.startsWith("win"),Tr=Symbol("clack:cancel");function vr(t){return t===Tr}function Sr(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var vn=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,yo=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function Cn(t,e,n,r=n,s=n,o){let i=vn(t??bc),a=Tt(n);return Je(e,i-a,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).map((c,l,u)=>{let d=o?o(c,l):c;return l===0?`${r}${d}`:l===u.length-1?`${s}${d}`:`${n}${d}`}).join(`
|
|
14
|
+
`)}function Ec(t,e){if("~standard"in t){let n=t["~standard"].validate(e);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return t(e)}var Tg=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return xc(this.opts.accessible)}constructor(e,n=!0){let{input:r=$g,output:s=bc,render:o,signal:i,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=n,this._abortSignal=i,this.input=r,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let r=this._subscribers.get(e)??[];r.push(n),this._subscribers.set(e,r)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let r=this._subscribers.get(e)??[],s=[];for(let o of r)o.cb(...n),o.once&&s.push(()=>r.splice(r.indexOf(o),1));for(let o of s)o()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Tr);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=bg.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Sr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Nt.show),this.output.off("resize",this.render),Sr(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Nt.show),this.output.off("resize",this.render),Sr(this.input,!1),e(Tr)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(e,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&vt.aliases.has(n.name)&&this.emit("cursor",vt.aliases.get(n.name)),vt.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let r=Ec(this.opts.validate,this.value),s;r instanceof Promise?(this.state="validating",this.render(),s=await r):s=r,s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Sc([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
15
|
+
`),Sr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Je(this._prevFrame,vn(this.output),{hard:!0,trim:!1}).split(`
|
|
16
|
+
`).length-1;this.output.write(Nt.move(-999,e*-1))}render(){let e=Je(this._render(this)??"",vn(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Nt.hide);else{let n=Eg(this._prevFrame,e),r=yo(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-r),o=Math.max(0,n.numLinesBefore-r),i=n.lines.find((a)=>a>=s);if(i===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(Nt.move(0,i-o)),this.output.write(Tn.lines(1));let a=e.split(`
|
|
17
|
+
`);this.output.write(a[i]),this._prevFrame=e,this.output.write(Nt.move(0,a.length-i-1));return}else if(n.lines.length>1){if(s<o)i=s;else{let c=i-o;c>0&&this.output.write(Nt.move(0,c))}this.output.write(Tn.down());let a=e.split(`
|
|
18
|
+
`).slice(i);this.output.write(a.join(`
|
|
19
|
+
`)),this._prevFrame=e;return}}this.output.write(Tn.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var Tc=class extends Tg{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:s})=>s===e.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?Er(r,1,this.options):r,this.changeValue(),this.on("cursor",(s)=>{switch(s){case"left":case"up":this.cursor=Er(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Er(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as C,stripVTControlCharacters as SO}from"util";import Dt from"process";function vg(){if(Dt.platform!=="win32")return Dt.env.TERM!=="linux";return Boolean(Dt.env.CI)||Boolean(Dt.env.WT_SESSION)||Boolean(Dt.env.TERMINUS_SUBLIME)||Dt.env.ConEmuTask==="{cmd::Cmder}"||Dt.env.TERM_PROGRAM==="Terminus-Sublime"||Dt.env.TERM_PROGRAM==="vscode"||Dt.env.TERM==="xterm-256color"||Dt.env.TERM==="alacritty"||Dt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Oc=vg();var F=(t,e)=>Oc?t:e,vc=F("\u25C6","*"),Rc=F("\u25A0","x"),Ic=F("\u25B2","x"),ko=F("\u25C7","o"),Cg=F("\u250C","T"),ut=F("\u2502","|"),wo=F("\u2514","\u2014"),AO=F("\u2510","T"),OO=F("\u2518","\u2014"),Ag=F("\u25CF",">"),Cc=F("\u25CB"," "),RO=F("\u25FB","[\u2022]"),IO=F("\u25FC","[+]"),_O=F("\u25FB","[ ]"),PO=F("\u25AA","\u2022"),NO=F("\u2500","-"),DO=F("\u256E","+"),jO=F("\u251C","+"),LO=F("\u256F","+"),MO=F("\u2570","+"),GO=F("\u256D","+"),Og=F("\u25CF","\u2022"),Rg=F("\u25C6","*"),Ig=F("\u25B2","!"),_g=F("\u25A0","x"),Pg=(t)=>{switch(t){case"initial":case"active":return C("cyan",vc);case"cancel":return C("red",Rc);case"error":return C("yellow",Ic);case"submit":return C("green",ko);case"validating":return C("dim",vc)}},Ng=(t)=>{switch(t){case"initial":case"active":return C("cyan",ut);case"cancel":return C("red",ut);case"error":return C("yellow",ut);case"submit":return C("green",ut)}};function Dg(t,e,n){let r=n?`${C("cyan",ut)} `:"",s=Cn(t,e.join(" \u2022 "),r).split(`
|
|
20
|
+
`);return n&&s.push(C("cyan",wo)),s}var Ac=(t,e,n,r,s,o=!1)=>{let i=e,a=0;if(o)for(let c=r-1;c>=n;c--){let l=t[c];if(l&&(i-=l.length),a++,i<=s)break}else for(let c=n;c<r;c++){let l=t[c];if(l&&(i-=l.length),a++,i<=s)break}return{lineCount:i,removals:a}},jg=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:i=4})=>{let a=vn(r)-o,c=yo(r),l=C("dim","..."),u=Math.max(c-i,0),d=Math.max(Math.min(s,u),5),p=0;t>=d-3&&(p=Math.max(Math.min(t-d+3,e.length-d),0));let f=d<e.length&&p>0,m=d<e.length&&p+d<e.length,h=Math.min(p+d,e.length),y=[],x=0;f&&x++,m&&x++;let b=p+(f?1:0),H=h-(m?1:0);for(let T=b;T<H;T++){let D=e[T],S=D!==void 0?n(D,T===t):"",w=Je(S,a,{hard:!0,trim:!1}).split(`
|
|
21
|
+
`);y.push(w),x+=w.length}if(x>u){let T=0,D=0,S=x,w=t-b,j=u,ct=()=>Ac(y,S,0,w,j),kt=()=>Ac(y,S,w+1,y.length,j,!0);f?({lineCount:S,removals:T}=ct(),S>j&&(m||(j-=1),{lineCount:S,removals:D}=kt())):(m||(j-=1),{lineCount:S,removals:D}=kt(),S>j&&(j-=1,{lineCount:S,removals:T}=ct())),T>0&&(f=!0,y.splice(0,T)),D>0&&(m=!0,y.splice(y.length-D,D))}let M=[];f&&M.push(l);for(let T of y)for(let D of T)M.push(D);return m&&M.push(l),M};var HO=[`${C("dim","\u2191/\u2193")} to navigate`,`${C("dim","Space:")} select`,`${C("dim","Enter:")} confirm`];var lt={message:(t=[],{symbol:e=C("gray",ut),secondarySymbol:n=C("gray",ut),output:r=process.stdout,spacing:s=1,withGuide:o}={})=>{let i=[],a=o??vt.withGuide,c=a?n:"",l=a?`${e} `:"",u=a?`${n} `:"";for(let p=0;p<s;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
22
|
+
`);if(d.length>0){let[p,...f]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let m of f)m.length>0?i.push(`${u}${m}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
23
|
+
`)}
|
|
24
|
+
`)},info:(t,e)=>{lt.message(t,{...e,symbol:C("blue",Og)})},success:(t,e)=>{lt.message(t,{...e,symbol:C("green",Rg)})},step:(t,e)=>{lt.message(t,{...e,symbol:C("green",ko)})},warn:(t,e)=>{lt.message(t,{...e,symbol:C("yellow",Ig)})},warning:(t,e)=>{lt.warn(t,e)},error:(t,e)=>{lt.message(t,{...e,symbol:C("red",_g)})}};var _c=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??vt.withGuide?`${C("gray",Cg)} `:"";n.write(`${r}${t}
|
|
25
|
+
`)},Pc=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??vt.withGuide?`${C("gray",ut)}
|
|
26
|
+
${C("gray",wo)} `:"";n.write(`${r}${t}
|
|
27
|
+
|
|
28
|
+
`)};var FO={light:F("\u2500","-"),heavy:F("\u2501","="),block:F("\u2588","#")};var Lg=[`${C("dim","\u2191/\u2193")} to navigate`,`${C("dim","Enter:")} confirm`],Cr=(t,e)=>t.includes(`
|
|
29
|
+
`)?t.split(`
|
|
30
|
+
`).map((n)=>e(n)).join(`
|
|
31
|
+
`):e(t),Nc=(t)=>{let e=(r,s)=>{if(r===void 0)return"";let o=r.label??String(r.value);switch(s){case"disabled":return`${C("gray",Cc)} ${Cr(o,(i)=>C("gray",i))}${r.hint?` ${C("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Cr(o,(i)=>C("dim",i))}`;case"active":return`${C("green",Ag)} ${o}${r.hint?` ${C("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Cr(o,(i)=>C(["strikethrough","dim"],i))}`;default:return`${C("dim",Cc)} ${Cr(o,(i)=>C("dim",i))}`}},n=t.showInstructions??!0;return new Tc({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??vt.withGuide,s=`${Pg(this.state)} `,o=`${Ng(this.state)} `,i=Cn(t.output,t.message,o,s),a=`${r?`${C("gray",ut)}
|
|
32
|
+
`:""}${i}
|
|
33
|
+
`;switch(this.state){case"submit":{let c=r?`${C("gray",ut)} `:"",l=Cn(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${C("gray",ut)} `:"",l=Cn(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
|
|
34
|
+
${C("gray",ut)}`:""}`}default:{let c=r?`${C("cyan",ut)} `:"",l=a.split(`
|
|
35
|
+
`).length,u=n?Dg(t.output,Lg,r):r?[C("cyan",wo)]:[],d=u.join(`
|
|
36
|
+
`),p=u.length+1;return`${a}${c}${jg({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:l+p,style:(f,m)=>e(f,f.disabled?"disabled":m?"active":"inactive")}).join(`
|
|
37
|
+
${c}`)}
|
|
38
|
+
${d}
|
|
39
|
+
`}}}}).prompt()};var KO=`${C("gray",ut)} `;function Dc(t=process.stdin){return t.readableEnded||t.destroyed}async function jc({edits:t,input:e=process.stdin,signal:n},r){let s=new AbortController,o=()=>s.abort(),i=(c,l)=>{if(l.sequence==="\x04"&&(!t||e.isPaused()))o()},a=r(n?AbortSignal.any([s.signal,n]):s.signal);e.on("keypress",i),e.once("end",o),e.once("close",o);try{return await a}finally{e.off("keypress",i),e.off("end",o),e.off("close",o)}}var Gg=new Set;function Lc(){for(let t of[...Gg])t.error()}var Fg="Pass the value as an argument or option instead";function Kg(t){if(vr(t))throw new _t;return t}function Ug(t){if(mo())return;throw new v(`Cannot prompt for ${t} without a terminal`,Fg)}async function Bg(t,e,{edits:n=!1,hint:r}){if(Ug(e.message),Dc(e.input))throw new _t;return Vg(r),Kg(await jc({...e,edits:n},(s)=>t({...e,signal:s})))}function Wg(t){return t.map((e)=>e.key?`${G.bold(e.key)} ${G.dim(e.text)}`:G.dim(e.text)).join(G.dim(" \xB7 "))}function Vg(t){lt.info(Wg(t))}var Jg={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function $o(t){return Bg(Nc,{showInstructions:!1,...t},{hint:Jg.select})}function Ar(t){return ec()&&t.output===void 0?{...t,output:process.stderr}:t}function qe(t){return(e,n={})=>t(e,Ar(n))}var qt={error:qe(lt.error),info:qe(lt.info),message:(t,e={})=>lt.message(t,Ar(e)),step:qe(lt.step),success:qe(lt.success),warn:qe(lt.warn),warning:qe(lt.warning)};function bo(t,e={}){_c(t,Ar(e))}function xo(t,e={}){Pc(t,Ar(e))}import{inspect as qg}from"util";var Yg=4;function Or(t,e=[]){if(e.length>=Yg)return[];let n=t instanceof AggregateError?t.errors:[],r=[...e,t];return[...n,...t.cause!==void 0?[t.cause]:[]].filter((o)=>!r.includes(o)).flatMap((o)=>[{hint:Ir(o),message:Rr(o)},...o instanceof Error?Or(o,r):[]])}function Rr(t){return _r(t instanceof Error?t.message||t.name:t)}function Ir(t){return t instanceof g&&t.hint!==void 0?_r(t.hint):void 0}function _r(t){return typeof t==="string"?t:qg(t,{breakLength:Number.POSITIVE_INFINITY})}var Xg="Error",zg=27,Zg=new RegExp(`${String.fromCharCode(zg)}\\[[\\d;]*m`,"g"),Qg=9,th=10,eh=31,nh=127,rh=159,sh=16,oh=4;function fe(t,{json:e}){if(Lc(),ch(t),e)Jt(me({error:ih(t)}));return Mc(t)}function ih(t){let e=Mc(t),n=So(Rr(t));if(!(t instanceof Error))return{_tag:Xg,message:n,exitCode:e,causes:[]};let r=Ir(t);return{_tag:ah(t),message:n,hint:r===void 0?void 0:So(r),exitCode:e,causes:Or(t).map((s)=>So(s.message))}}function Mc(t){if(t instanceof _t)return ft;if(t instanceof g)return ir(t.exitCode)?t.exitCode:kn;return kn}function ah(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:_r(t.name)}function ch(t){if(t instanceof _t)return;let e=$r(),n=Pr(Rr(t));if(t instanceof g){let r=Ir(t);if(qt.warn(G.yellow(n),{output:e}),r)qt.info(G.dim(Pr(r)),{output:e})}else qt.error(G.red(n),{output:e});if(!(t instanceof Error))return;for(let r of Or(t))if(qt.info(G.dim(`caused by: ${Pr(r.message)}`),{output:e}),r.hint)qt.info(G.dim(` ${Pr(r.hint)}`),{output:e})}function Pr(t){return Array.from(t.replace(Zg,""),(e)=>{let n=e.charCodeAt(0);return n<=eh&&n!==Qg&&n!==th||n>=nh&&n<=rh?`\\u${n.toString(sh).padStart(oh,"0")}`:e}).join("")}var lh=500,uh="The command stopped before it finished because nothing was left for it to wait for";function Gc({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(s,o)=>(e.ending??=dh(s,o),e.ending),r=(s)=>{if(e.failed||e.ending)return;e.failed=!0;let o=fe(s,{json:t&&!nc()});rc(),n(o,e.settled?void 0:lh)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(uh))}),{exit:(s)=>n(s),settle(){e.settled=!0}}}async function dh(t,e){process.exitCode=t,await ic(e),process.exit(t)}var Yt=new Uint32Array(65536),ph=(t,e)=>{let n=t.length,r=e.length,s=1<<n-1,o=-1,i=0,a=n,c=n;while(c--)Yt[t.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=Yt[e.charCodeAt(c)],u=l|i;if(l|=(l&o)+o^o,i|=~(l|o),o&=l,i&s)a++;if(o&s)a--;i=i<<1|1,o=o<<1|~(u|i),i&=u}c=n;while(c--)Yt[t.charCodeAt(c)]=0;return a},mh=(t,e)=>{let n=e.length,r=t.length,s=[],o=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let m=0;m<i;m++)o[m]=-1,s[m]=0;let c=0;for(;c<a-1;c++){let m=0,h=-1,y=c*32,x=Math.min(32,r)+y;for(let b=y;b<x;b++)Yt[t.charCodeAt(b)]|=1<<b;for(let b=0;b<n;b++){let H=Yt[e.charCodeAt(b)],M=o[b/32|0]>>>b&1,T=s[b/32|0]>>>b&1,D=H|m,S=((H|T)&h)+h^h|H|T,w=m|~(S|h),j=h&S;if(w>>>31^M)o[b/32|0]^=1<<b;if(j>>>31^T)s[b/32|0]^=1<<b;w=w<<1|M,j=j<<1|T,h=j|~(D|w),m=w&D}for(let b=y;b<x;b++)Yt[t.charCodeAt(b)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let m=d;m<p;m++)Yt[t.charCodeAt(m)]|=1<<m;let f=r;for(let m=0;m<n;m++){let h=Yt[e.charCodeAt(m)],y=o[m/32|0]>>>m&1,x=s[m/32|0]>>>m&1,b=h|l,H=((h|x)&u)+u^u|h|x,M=l|~(H|u),T=u&H;if(f+=M>>>r-1&1,f-=T>>>r-1&1,M>>>31^y)o[m/32|0]^=1<<m;if(T>>>31^x)s[m/32|0]^=1<<m;M=M<<1|y,T=T<<1|x,u=T|~(b|M),l=M&b}for(let m=d;m<p;m++)Yt[t.charCodeAt(m)]=0;return f},Eo=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return ph(t,e);return mh(t,e)},Hc=(t,e)=>{let n=1/0,r=0;for(let s=0;s<e.length;s++){let o=Eo(t,e[s]);if(o<n)n=o,r=s}return e[r]};function Nr(t,e,n){let r=e.length>0?Hc(t,[...e]):void 0,s=`Run "${n} --help" for usage.`;return new v(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${s}`:s)}function An(t,e){if(Array.isArray(e))return[...e];if(!Fc(t)||!Fc(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,An(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function Fc(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Kc(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...br},options:Uc(Et),commands:e.map((n)=>Dr(n,`${t.bin} ${n.name}`))}}function Dr(t,e){return{name:t.name,path:e,description:t.description,json:t.json,prompts:t.prompts,passthrough:t.passthrough,positionals:Object.entries(t.positionals).map(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:Uc(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>Dr(n,`${e} ${n.name}`))}}function Uc(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${Pt(e)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as Bc}from"util";var fh=2,gh="0.0.0",hh=(t)=>t,P={arg:G.magenta,cmd:G.cyan,default:G.bold,desc:hh,flag:G.green,header:(t)=>G.bold(G.yellow(t)),hint:G.dim,name:(t)=>G.bold(G.cyan(t)),placeholder:G.magenta};function Wc(t){return`${P.name(t.name)} ${P.hint(t.version??gh)}`}function Vc(t,e){let n=`${P.name(t.name)}${t.version?` ${P.hint(`v${t.version}`)}`:""}`;return qc([[n,...t.description?[P.desc(t.description)]:[]],Ht("Usage:",[` ${P.cmd(t.bin)} ${P.placeholder("[command]")} ${P.placeholder("[options]")}`]),Ht("Commands:",Yc(e)),Ht("Options:",zc(Et)),Ht("Exit codes:",Xc()),[`${P.hint("Run")} ${P.cmd(`${t.bin} <command> --help`)} ${P.hint("for command details.")}`]])}function Jc(t,e){let n=t.json?{...t.args,json:Et.json}:t.args,r=[...t.subcommands.length>0?[` ${P.cmd(e)} ${P.placeholder("<command>")} ${P.placeholder("[options]")}`]:[],...t.run?[` ${yh(t,e).join(" ")}`]:[],...t.prompts&&Object.keys(t.positionals).length>0?[` ${P.hint("Omit positional arguments to run interactively.")}`]:[],...t.passthrough?[` ${P.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return qc([[P.name(e),P.desc(t.description)],Ht("Usage:",r),Ht("Commands:",Yc(t.subcommands)),Ht("Arguments:",wh(t.positionals)),Ht("Options:",zc(n)),Ht("Examples:",t.examples.map((s)=>` ${P.cmd(s)}`)),Ht("Exit codes:",Xc())])}function yh(t,e){let n=kh(t.positionals);return t.passthrough?[P.cmd(e),P.placeholder("[options]"),P.placeholder("[--]"),...n]:[P.cmd(e),...n,P.placeholder("[options]")]}function Ht(t,e){return e.length>0?[P.header(t),...e]:[]}function qc(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
|
|
40
|
+
`)).join(`
|
|
41
|
+
|
|
42
|
+
`)}function Yc(t){return jr(t.map((e)=>[` ${P.cmd(e.name)}`,P.desc(e.description)]))}function Xc(){return jr(Object.entries(br).map(([t,e])=>[` ${t}`,e]))}function To(t,e){return e.variadic?`${t}...`:t}function kh(t){return Object.entries(t).map(([e,n])=>n.required?P.arg(`<${To(e,n)}>`):P.arg(`[${To(e,n)}]`))}function wh(t){return jr(Object.entries(t).map(([e,n])=>[` ${P.arg(To(e,n))}`,`${P.desc(n.description??"")}${n.required?"":P.hint(" (optional)")}`]))}function zc(t){return jr(Object.entries(t).map(([e,n])=>{let r=n.alias?`${P.flag(`-${n.alias}`)}, `:" ",s=n.type==="boolean"?"":` ${P.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,o=$h(n),i=o===void 0?"":` (default: ${P.default(o)})`;return[` ${r}${P.flag(`--${Pt(e)}`)}${s}`,`${P.desc(n.description??"")}${i}`]}))}function $h(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}function jr(t){let e=Math.max(0,...t.map(([n])=>Bc(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Bc(n).length+fh)}${r}`)}function Lr(t){let e=!1;return{emitted:()=>e,json:t,result(n,r){if(e)throw Error("ctx.output.result was called more than once; a command emits one result");let s=bh(t,n,r);if(e=!0,s!==void 0)Jt(s)}}}function bh(t,e,n){if(t)return me(e);return n?`${n(e)}
|
|
43
|
+
`:void 0}function Mr(t,e,n){return{args:e.args,cli:t.info,config:t.config,interactive:e.interactive,json:e.json,output:n,positionals:e.positionals}}async function Gr(t,e,n,r){let s=await oc(n.json,async()=>{let o=await t.run?.(n);return typeof o==="number"?xh(e,o):ft});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return s}function xh(t,e){if(ir(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${ft} to ${Ga}`)}var vo="__exit__",Zc="__run__",Sh="Back",Eh="Return to previous menu";async function Qc(t,e){if(e)throw new v("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!En())throw new v("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t.interactive.clearOnStart)console.clear();let n=t.info.version?` v${t.info.version}`:"";bo(G.bgCyan(G.black(` ${t.info.name}${n} `)));let r={commands:t.commands,message:t.interactive.promptMessage,path:t.info.bin,root:!0};return await tl(t,new Map,r),xo(t.interactive.goodbyeMessage),ft}async function tl(t,e,n){while(!0){let r=await Th(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===Zc&&n.owner){await el(t,n.owner,n.path);continue}let s=n.commands.find((o)=>o.name===r);if(s)await vh(t,e,s,`${n.path} ${r}`)}}async function Th(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:vo}:{hint:Eh,label:Sh,value:vo};try{let s=await $o({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:Zc}]:[],...n.commands.map((o)=>({hint:o.description,label:o.name,value:o.name})),r]});return s===vo?void 0:s}catch(s){if(s instanceof _t)return;throw s}}async function vh(t,e,n,r){if(n.subcommands.length===0)return el(t,n,r);return tl(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function el(t,e,n){try{await Ch(t,e,n)}catch(r){if(r instanceof _t)return;if(!(r instanceof g))throw r;fe(r,{json:!1})}}async function Ch(t,e,n){let{args:r}=Sn([],e.args),s=mr([],e.positionals),o=e.prompts?null:fr(s,e.positionals);if(o)throw new v(o,`Run "${n} --help" for usage.`);let i=Lr(!1),a={args:dr(r,e.args),interactive:e.prompts,json:!1,positionals:s};await Gr(e,n,Mr(t,a,i),i)}var Ah="--",Oh=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,Rh=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function Co(t,e){try{return await Ih(t,e)}catch(n){return{code:fe(n,{json:Oo(e)}),menu:!1}}}function Ao(t,e){let{command:n,restArgs:r}=ur(e,Et),s=n===void 0||n===Te?void 0:sl(t,n,r);if(!s||s instanceof v||!s.command.passthrough)return{operands:[],options:[...e]};let o=Wa(s.tokens,{...s.command.args,...Ve}),i=o<0?[]:s.tokens.slice(o);return{operands:i,options:e.slice(0,e.length-i.length)}}async function Ih(t,{options:e,operands:n}){let{command:r,flags:s,restArgs:o}=lo(e,Et,Ve),i=s.json===!0,a={code:ft,menu:!1};if(r===void 0){if(s.interactive&&!s.help&&!s.version)return{code:await Qc(t,i),menu:!0};return Jt(s.version&&!s.help?Ph(t,i):nl(t,i)),a}let c=s.interactive?"--interactive":s.version?"--version":void 0;if(c)throw new v(`${c} cannot be combined with a command`,`Run "${t.info.bin} ${c}" on its own.`);if(r===Te)return Jt(Nh(t,o,i)),a;let l=Dh(t,r,o);if(s.help)return Jt(Ro(l.command,l.path,i)),a;return{code:await jh(t,l,n,i),menu:!1}}function Oo({options:t}){let{before:e,restArgs:n}=ur(t,Et);return[e,n].some((r)=>_h(r).some((s)=>Oh.test(s)))}function _h(t){let e=t.indexOf(Ah);return e<0?t:t.slice(0,e)}function Ph({info:t},e){return e?me({name:t.name,bin:t.bin,version:t.version}):`${Wc(t)}
|
|
44
|
+
`}function nl(t,e){return e?me(Kc(t.info,t.commands)):`${Vc(t.info,t.commands)}
|
|
45
|
+
`}function Ro(t,e,n){return n?me(Dr(t,e)):`${Jc(t,e)}
|
|
46
|
+
`}function Nh(t,e,n){let{args:r,rawPositionals:s}=Sn(e,Ve);if(lr(r,Ve,`Run "${t.info.bin} ${Te} [command]" for usage.`,e),s.length===0)return nl(t,n);let{command:o,path:i}=rl(t.commands,s,t.info.bin);return Ro(o,i,n)}function rl(t,e,n){let[r="",...s]=e,o=t.find((a)=>a.name===r);if(!o)throw Nr(r,Io(t),n);let i=`${n} ${r}`;return s.length===0?{command:o,path:i}:rl(o.subcommands,s,i)}function Io(t){return t.map((e)=>e.name)}function Dh(t,e,n){let r=sl(t,e,n);if(r instanceof v)throw r;return r}function sl(t,e,n){let r=t.commands.find((s)=>s.name===e);if(!r)return Nr(e,Io(t.commands),t.info.bin);return ol({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function ol(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let s=r.findIndex((a)=>!Rh.test(a)),o=r[s];if(o===void 0||o.startsWith("-"))return t;let i=e.subcommands.find((a)=>a.name===o);if(i)return ol({command:i,path:`${n} ${o}`,tokens:r.toSpliced(s,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return Nr(o,Io(e.subcommands),n)}async function jh(t,{command:e,path:n,tokens:r},s,o){let i=`Run "${n} --help" for usage.`,a={...e.args,...Ve},c=Sn(r,a),{args:l}=c,u=[...c.rawPositionals,...s];if(e.strict)lr(l,a,i,r);if(o&&!e.json)throw new v(`${n} does not support --json`,i);let d=e.strict?Ja(u,e.positionals):void 0;if(d!==void 0)throw new v(`Unexpected argument: ${d}`,i);if(!e.run)return Jt(Ro(e,n,o)),ft;let p=mr(u,e.positionals),f=fr(p,e.positionals);if(f)throw new v(f,i);let m=e.prompts&&u.length===0&&En()&&!o,h={args:dr(l,e.args),interactive:m,json:o,positionals:p},y=Lr(o);try{return await Gr(e,n,Mr(t,h,y),y)}catch(x){return fe(x,{json:o&&!y.emitted()})}}var Lh={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function _o(t){let e=`CLI "${t.name}"`;if(hr(e,t.commands),t.commands.some((r)=>r.name===Te))throw Error(`${e} cannot define a command named "${Te}": the framework provides it`);let n={commands:t.commands,config:t.config,info:{bin:t.bin??t.name,description:t.description,name:t.name,version:t.version},interactive:{...Lh,...t.interactive}};return{async main(r=process.argv.slice(2)){sc();let s=Ao(n,r),o=Gc({json:Oo(s)}),i=await Co(n,s);if(o.settle(),i.code===ft&&!i.menu)return;await o.exit(i.code)},async run(r=process.argv.slice(2)){return(await Co(n,Ao(n,r))).code}}}import Ft from"fs";import Mo from"path";var ve=(t)=>(t.map=(e)=>ve((n)=>e(t(n))),t.or=(e)=>ve((n)=>{try{return t(n)}catch(r){return e(n)}}),t),Hr=()=>"bad banditype"();var il=()=>ve((t)=>t),al=(t)=>ve((e)=>t.includes(e)?e:Hr()),Po=(t)=>ve((e)=>typeof e===typeof t?e:Hr()),Xt=()=>Po(""),cl=()=>Po(0),ll=()=>Po(!0);var Fr=()=>ve((t)=>t===null?t:Hr()),On=(t)=>ve((e)=>e instanceof t?e:Hr()),ul=(t)=>On(Object).map((e)=>{let n={};for(let r in e){let s=t(e[r]);s!==void 0&&(n[r]=s)}return n}),Kr=(t)=>On(Object).map((e)=>{let n={};for(let r in t){let s=t[r](e[r]);s!==void 0&&(n[r]=s)}return n});var dl=(t)=>On(Array).map((e)=>e.map(t));import Ye from"fs";var Mh=".lock",Gh=".break",pl=10,Hh=1e4,Fh=5000;function ml(t,e){let n=`${t}${Mh}`,r=crypto.randomUUID();Kh(n,r);try{return e()}finally{fl(n,r)}}function Kh(t,e){let n=Date.now()+Hh;while(!gl(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(No(t))Uh(t,e);else Bun.sleepSync(pl)}}function fl(t,e){if(Bh(t)===e)Ye.rmSync(t,{force:!0})}function Uh(t,e){let n=`${t}${Gh}`;if(!gl(n,e)){if(No(n))Ye.rmSync(n,{force:!0});else Bun.sleepSync(pl);return}try{if(No(t))Ye.rmSync(t,{force:!0})}finally{fl(n,e)}}function gl(t,e){try{return Ye.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(hl(n)==="EEXIST")return!1;throw n}}function No(t){let e=Ye.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>Fh}function Bh(t){try{return Ye.readFileSync(t,"utf8")}catch(e){if(hl(e)==="ENOENT")return;throw e}}function hl(t){return t instanceof Error?Reflect.get(t,"code"):void 0}import Do from"fs";import Ce from"path";var Wh="..",Vh=40;function kl(t){let{root:e}=Ce.parse(Ce.resolve(t)),n=yl(Ce.resolve(t)),r=e,s=0;for(let o=n.shift();o!==void 0;o=n.shift()){if(o===Wh){r=Ce.dirname(Do.realpathSync(r));continue}let i=Ce.join(r,o);if(!Do.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(s+=1,s>Vh)throw Error(`too many symbolic links in ${t}`);let a=Do.readlinkSync(i);if(Ce.isAbsolute(a))r=e;n.unshift(...yl(a))}return r}function yl(t){return t.split(Ce.sep).filter((e)=>e!==""&&e!==".")}function Lo(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=Jh(t),s=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",o=t.includes(`\r
|
|
47
|
+
`)?`\r
|
|
48
|
+
`:`
|
|
49
|
+
`,i=/\s/.test(t[r.start+1]??"")||r.entries.some((l)=>/:\s+$/.test(t.slice(l.start,l.node.start)))?" ":"";function a(l,u){let d=t.slice(l.start,l.end);if(JSON.stringify(l.value)===JSON.stringify(u))return d;let p=Array.isArray(u);if(u===null||typeof u!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==p)return c(u,l.start,d.includes(`
|
|
50
|
+
`));let f=p?u.map((w,j)=>String(j)):[...new Set([...l.entries.map((w)=>w.key).filter((w)=>Object.hasOwn(u,w)),...Object.keys(u)])];if(f.length===0)return p?"[]":"{}";let m=l.entries[0],h=l.entries.at(-1);if(!m||!h)return c(u,l.start,d.includes(`
|
|
51
|
+
`));let y=(w)=>p?u[Number(w)]:u[w];if(f.length===l.entries.length&&f.every((w,j)=>w===l.entries[j]?.key)){let w=l.start,j="";for(let ct of l.entries)j+=t.slice(w,ct.node.start)+a(ct.node,y(ct.key)),w=ct.node.end;return j+t.slice(w,l.end)}let x=t.slice(l.start+1,m.start),b=t.slice(h.node.end,l.end-1),H=l.entries[1],M=H?t.slice(m.node.end,H.start):`,${x.includes(`
|
|
52
|
+
`)?x:i}`,T=p?"":t.slice(m.start,m.node.start).match(/:\s*$/)?.[0]??": ",D=new Map(l.entries.map((w)=>[w.key,w])),S=f.map((w)=>{let j=D.get(w);if(j)return t.slice(j.start,j.node.start)+a(j.node,y(w));return(p?"":JSON.stringify(w)+T)+c(y(w),m.start,x.includes(`
|
|
53
|
+
`))});return`${p?"[":"{"}${x}${S.join(M)}${b}${p?"]":"}"}`}function c(l,u,d){if(!d)return jo(l,i);let p=t.lastIndexOf(`
|
|
54
|
+
`,u-1)+1,f=t.slice(p,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,s).replaceAll(`
|
|
55
|
+
`,o+f)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function jo(t,e){if(Array.isArray(t))return`[${t.map((s)=>jo(s,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let r=n.map(([s,o])=>`${JSON.stringify(s)}:${e}${jo(o,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function Jh(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let o=n;return n=e.next().value,o}function s(){let o=r(),i=[],a=o[0]==="{";if(!a&&o[0]!=="[")return{end:o.index+o[0].length,entries:i,start:o.index,value:JSON.parse(o[0])};let c=a?"}":"]";while(n&&n[0]!==c){let u=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:s(),start:u}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:i,start:o.index,value:JSON.parse(t.slice(o.index,l))}}return s()}var qh=2,Go="ConfigError",Yh=On(Object);class Ho{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Mo.resolve(t),this.defaultConfig=e,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(t){return this.current()[t]}set(t,e){let n=this.writable();this.update((r)=>({...r,[t]:e})),n.config={...n.config,[t]:e}}delete(t){let e=this.writable();this.update((n)=>(delete n[t],n)),delete e.config[t]}exists(){return Ft.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(t){let e=this.writable();if(t)e.config={...t};this.update(()=>e.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:t,failure:e}=this.state();if(e)throw e;return t}writable(){let t=this.state();if(t.failure)throw t.failure;if(t.error)throw this.unreadable(t.error);return t}unreadable(t){return new g(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:t,tag:Go})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return An(structuredClone(this.defaultConfig),wl(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();ml(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof g?e:this.saveFailure(e)}}savePath(){let t=this.exists()?Ft.realpathSync(this.configPath):kl(this.configPath);return Ft.mkdirSync(Mo.dirname(t),{recursive:!0}),t}write(t,e){let n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?Ft.statSync(this.configPath).mode:void 0,s=this.exists()?Lo(Ft.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,qh)}
|
|
56
|
+
`;if(Ft.writeFileSync(n,s,{flag:"wx",mode:r}),r!==void 0)Ft.chmodSync(n,r);Ft.renameSync(n,t)}finally{Ft.rmSync(n,{force:!0})}}saveFailure(t){return new g(`Cannot save config at ${this.configPath}: ${$l(t)}`,`Check that ${Mo.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:Go})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=An(structuredClone(this.defaultConfig),wl(n));return{config:t?t(r):r}}catch(n){if(e)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return qt.warn(G.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:$r()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new g(`Cannot read config at ${this.configPath}: ${$l(t)}`,"Repair the file and try again",void 0,{cause:t,tag:Go})}readConfigFile(){try{return Ft.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}function wl(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return Yh(e)}function $l(t){return t instanceof Error?t.message:String(t)}var bl="0.2.0";var R=gr();var zh=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],Ur=Object.fromEntries(zh.map((t)=>[t,void 0]));var Tl={SIGHUP:129,SIGINT:130,SIGTERM:143},xl=Object.keys(Tl),Sl={SIGHUP:()=>Fo("SIGHUP"),SIGINT:()=>Fo("SIGINT"),SIGTERM:()=>Fo("SIGTERM")},Xe=[],Ko={interrupted:!1};function ge(t){if(Xe.length===0)for(let e of xl)process.on(e,Sl[e]);return Xe.push(t),()=>{let e=Xe.indexOf(t);if(e===-1)return;if(Xe.splice(e,1),Xe.length===0)for(let n of xl)process.off(n,Sl[n])}}function vl(){return Ko.interrupted}function Fo(t){if(Ko.interrupted)return;Ko.interrupted=!0;let e=Tl[t],n=Xe.toReversed().flatMap((r)=>Zh(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function Zh(t){try{let e=t();return e instanceof Promise?e.catch(El):null}catch(e){return El(e),null}}function El(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
|
|
57
|
+
`)}var Qh=["ESRCH","EPERM"];function Rn(t,e){try{process.kill(-t,e)}catch(n){if(!Qh.includes(n.code))throw n}}var ty=1000,ey=2147483647,ny=60,Rl=8192,ry=Rl*2,sy=1000,oy=`exec 2>&1
|
|
58
|
+
`,iy=192,ay=128,Cl=`
|
|
59
|
+
`,cy=[126,127],Al=128,ly=31;async function Il(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${oy}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...Ur},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),s=ge(()=>Uo(r.pid));try{return await uy(r,t,e,n)}finally{s()}}async function uy(t,e,n,r){let s={hasher:new Bun.CryptoHasher("sha256"),window:new Uint8Array},o=[t.stdout.getReader(),t.stderr.getReader()],i=Promise.all(o.map((u)=>dy(u,s))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,Uo(t.pid)},Math.min(n.timeoutSeconds*ty,ey));await t.exited,clearTimeout(c);let l=await py(i,sy);if(Uo(t.pid),!l)await Promise.all(o.map((u)=>u.cancel()));return{command:e,durationMs:Math.round(performance.now()-r),exitCode:t.exitCode,outputSha256:s.hasher.digest("hex"),outputTail:my(s.window),timedOut:a.timedOut}}function _l(t){return t.exitCode===0&&!t.timedOut}function Pl(t){return t.exitCode!==0&&!t.timedOut&&!Bo(t)&&!Wo(t)}function Bo(t){let{exitCode:e}=t;return e===null||e>Al&&e<=Al+ly}function Wo(t){return t.exitCode!==null&&!t.timedOut&&cy.includes(t.exitCode)}async function dy(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=Nl(fy(e.window,r),ry)}}async function py(t,e){let n,r=new Promise((o)=>{n=setTimeout(()=>o(!1),e)}),s=await Promise.race([t.then(()=>!0),r]);return clearTimeout(n),s}function Uo(t){Rn(t,"SIGKILL")}function my(t){let n=new TextDecoder().decode(Ol(t)).split(Cl);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-ny).join(Cl));return new TextDecoder().decode(Ol(Nl(r,Rl)))}function Ol(t){let e=0;while(e<t.length&&((t[e]??0)&iy)===ay)e++;return t.subarray(e)}function Nl(t,e){return t.length<=e?t:t.subarray(t.length-e)}function fy(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function z(t,e,n,r=[],s=[]){return{checks:[...s],details:[...r],gate:t,ok:e,summary:n}}async function wt(t,e,n){let r=[];for(let s of t){let o=await Il(s.run,{cwd:n,timeoutSeconds:s.timeoutSeconds});r.push(gy(s.name,e,o))}return r}function gy(t,e,n){let r=e==="pass"?_l(n):Pl(n);return{...n,expect:e,name:t,ok:r}}function Vo(t){return`${t.name} should ${t.expect} but ${hy(t)}`}function Ae(t){return t.filter((e)=>!e.ok).map(Vo)}function Z(t,e,n){return t===1?e:n}function hy(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(Wo(t))return`could not run (exit code ${t.exitCode})`;if(!Bo(t))return`exited with ${t.exitCode}`;return t.exitCode===null?"was killed by a signal":`was killed by a signal (exit code ${t.exitCode})`}var Dl=new Map;function K(t,e){return e.some((n)=>ky(n).match(t))}function Jo(t){if(t.trim().length===0)return"is empty";if(t!==t.trim())return"has leading or trailing white space";if(t.includes("\x00"))return"contains a NUL character";if(t.startsWith("!"))return"must not be negated with a leading !";if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return"must be relative to the repository root";if(t.startsWith("./"))return"must not start with ./";if(t.split("/").includes(".."))return"must not contain a .. segment";return yy(t)}function Oe(t){let e=Jo(t);if(e!==null)return e;if(t.endsWith("/"))return"ends with /, so it matches no file; use a pattern such as dir/**";return t.split("/").includes("")?"has an empty path segment, so it matches no file":null}function yy(t){let e=0,n=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s==="\\"){if(r===t.length-1)return"ends with a lone backslash";r++;continue}if(n){n=s!=="]";continue}if(s==="[")n=!0;if(s==="{")e++;if(s==="}"){if(e===0)return"has an unmatched }";e--}}if(n)return"has an unclosed [";return e>0?"has an unclosed {":null}function ky(t){let e=Dl.get(t);if(e)return e;let n=new Bun.Glob(t);return Dl.set(t,n),n}import{copyFileSync as Ey,existsSync as Ty,mkdtempSync as vy,readFileSync as Cy,readlinkSync as Ay,rmSync as Oy,utimesSync as Ry}from"fs";import{tmpdir as Iy}from"os";import{join as Br,resolve as _y}from"path";function N(t,e){if(t<e)return-1;if(t>e)return 1;return 0}function $t(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}import{lstatSync as wy,statSync as $y}from"fs";import{dirname as by,join as xy}from"path";var Sy=["ENOENT","ENOTDIR","ELOOP"];function he(t){return jl(()=>wy(t))}function qo(t){return jl(()=>$y(t))}function ze(t,e,n=new Map){let r=by(e);if(r===".")return!1;let s=n.get(r);if(s!==void 0)return s;let o=he(xy(t,r))?.isSymbolicLink()===!0||ze(t,r,n);return n.set(r,o),o}function jl(t){try{return t()}catch(e){if(Sy.includes(e.code))return null;throw e}}var Wr="\x00",gt=0,Py=128,Ny=128,Kl=1,Ul=1,Dy=1,jy="ari-index-",Yo=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],Ly=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],Ll=1,My=/^(?:[a-z]|S) /,Ml=/^s/i,Gy=2,Hy="symlink:",Fy=["--no-assume-unchanged","--no-skip-worktree"],Gl="worktree ",Ky="bare",Uy="prunable",Hl=/^(?:error|fatal): /;async function A(t,e,n={}){let r=[...Ly,...e],s=Vy(r,t,n),[o,i,a]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]);if((n.allowedExitCodes??[gt]).includes(a))return{exitCode:a,stderr:i,stdout:o};let l=i.trim()||o.trim()||"no output";throw Error(`git ${e.join(" ")} failed in ${t} with exit code ${a}: ${l}`)}async function Bl(t){let e=await A(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[gt,Py]});if(e.exitCode!==gt)throw new g(`${t} is not inside a git working tree`,"Run ari from inside a git repository");return e.stdout.trim()}async function Re(t,e){let n=await A(t,["rev-parse","--git-path",e]);return _y(t,n.stdout.trim())}async function Vr(t){let e=await A(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[gt,Kl]});if(e.exitCode!==gt)throw new g("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function Wl(t){let e=await A(t,["config","user.name"],{allowedExitCodes:[gt,Ul]}),n=e.stdout.trim();return e.exitCode===gt&&n.length>0?n:null}async function Ct(t,e){let n=await Yl(t,async(o)=>(await ql(t,await qr(t),o),A(t,[...Yo,e,"--"],{env:o}))),r=await A(t,[...Yo,"--cached",e,"--"]),s=await A(t,["ls-files","--others","--exclude-standard","-z"]);return zo([n,r,s].flatMap((o)=>Zt(o.stdout)))}async function Jr(t,e,n){let r=await A(t,[...Yo,e,n,"--"]);return zo(Zt(r.stdout))}async function Ze(t,e){let n=await A(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[gt,Kl]});if(n.exitCode!==gt)throw new g(`"${e}" does not name a commit`,"Pass a branch, tag or commit that this repository has");return n.stdout.trim()}async function Vl(t,e,n){let r=await A(t,["merge-base",e,n],{allowedExitCodes:[gt,Dy]});if(r.exitCode!==gt)throw new g(`${e} and ${n} share no history`,"Pass a ref that the current branch was integrated with");return r.stdout.trim()}async function Jl(t){let e=await A(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let s of[...e.stdout.split(Wr),""])if(s.startsWith(Gl))r=s.slice(Gl.length);else if(s===Ky||s.startsWith(Uy))r=null;else if(s===""&&r!==null)n.push(r),r=null;return n}async function Qe(t,e){return Yl(t,async(n)=>{await ql(t,await qr(t),n);let r=await A(t,["add","--all","--sparse","--","."],{allowedExitCodes:[gt,Ny],env:n});if(r.exitCode!==gt)throw new g(`git cannot hash the working tree: ${Xo(r.stderr)}`,"Commit, remove or ignore those paths (an embedded repository needs a commit), then run the command again");if(e.length>0){let o=e.map((i)=>`:(glob)${i}`);await A(t,["rm","--cached","-r","-q","--sparse","--ignore-unmatch","--",...o],{env:n})}return(await A(t,["write-tree"],{env:n})).stdout.trim()})}async function zt(t,e){if(e.length===0)return{};let n=await A(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,s=zo(Zt(n.stdout)).filter((o)=>K(o,e)&&!ze(t,o,r));return Object.fromEntries(s.flatMap((o)=>{let i=Wy(Br(t,o));return i===null?[]:[[o,i]]}))}function Xo(t){let e=t.split(`
|
|
60
|
+
`).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Hl.test(r)).map((r)=>r.replace(Hl,""));return(n.length>0?n:e).join("; ")||"no output"}async function qr(t){let e=await A(t,["ls-files","-v","-z"]),n=Zt(e.stdout).filter((s)=>My.test(s)),r=n.some((s)=>Ml.test(s))&&await By(t);return n.filter((s)=>!(r&&Ml.test(s))||he(Br(t,Fl(s)))!==null).map(Fl)}async function By(t){return(await A(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[gt,Ul]})).stdout.trim()==="true"}function Fl(t){return t.slice(Gy)}async function ql(t,e,n){if(e.length===0)return;let r=`${e.join(Wr)}${Wr}`;for(let s of Fy)await A(t,["update-index",s,"-z","--stdin"],{env:n,stdin:r})}async function Yl(t,e){let n=vy(Br(Iy(),jy)),r=Br(n,"index"),s=()=>Oy(n,{force:!0,recursive:!0}),o=ge(s);try{let i=await Re(t,"index");if(Ty(i))Ey(i,r),Ry(r,Ll,Ll);return await e({GIT_INDEX_FILE:r})}finally{s(),o()}}function Wy(t){let e=he(t);if(e?.isSymbolicLink())return`${Hy}${$t(Ay(t))}`;return e?.isFile()?$t(Cy(t)):null}function Vy(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n.env?{...process.env,...n.env}:process.env,stderr:"pipe",stdin:n.stdin===void 0?"ignore":new TextEncoder().encode(n.stdin),stdout:"pipe"})}catch(r){throw Error(`Could not run ${t.join(" ")} in ${e}`,{cause:r})}}function Zt(t){return t.split(Wr).filter((e)=>e.length>0)}function zo(t){return[...new Set(t)].sort(N)}import{randomUUID as i$}from"crypto";import{appendFileSync as a$,existsSync as Bt,linkSync as c$,mkdirSync as Ou,readdirSync as l$,readFileSync as Ln,renameSync as Ru,rmSync as ps,writeFileSync as Iu}from"fs";import{basename as u$,dirname as _u,join as X}from"path";function In(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))In(e);return Object.freeze(t)}class O extends Error{_tag="ValidationError"}var Jy=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,qy=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Yy="must be lower-case letters and digits separated by single hyphens",Xy=new Set(Object.getOwnPropertyNames(Object.prototype)),zy=Xt(),Zy=ll(),Yr=cl(),Qy=dl(il()),tk=Xt().or(Fr());function st(t,e,n){try{return n()}catch(r){if(r instanceof O)throw new g(`Invalid ${t}: ${r.message}`,e);throw r}}function k(t,e){if(typeof e==="number")return`${t}[${e}]`;if(!qy.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function I(t,e,n){let r=Zl(t,e),s=Object.keys(r).find((o)=>!n.includes(o));if(s!==void 0)throw new O(`${e} has unknown key ${JSON.stringify(s)}; expected ${n.join(", ")}`);return r}function ye(t,e,n){return Object.entries(Zl(t,e)).map(([r,s])=>{if(Xy.has(r))throw new O(`${k(e,r)} uses a reserved name`);return[r,n(s,k(e,r),r)]})}function J(t,e,n){return t===void 0?e:n(t)}function q(t,e,n){return t===void 0||t===null?e:n(t)}function ht(t,e,n){if(t===void 0||t===null)throw new O(`${e} is required`);return n(t,e)}function E(t,e){return te(zy,t,e,"must be a string")}function Qt(t,e){let n=E(t,e);if(n.trim().length===0)throw new O(`${e} must not be empty`);return n}function bt(t,e){return te(tk,t,e,"must be a string or null")}function tn(t,e){let n=E(t,e);if(!Jy.test(n))throw new O(`${e} ${Yy}, got ${JSON.stringify(n)}`);return n}function Ie(t,e){return te(Zy,t,e,"must be true or false")}function _e(t,e){let n=te(Yr,t,e,"must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new O(`${e} must be a positive integer`);return n}function At(t,e){let n=te(Yr,t,e,"must be a non-negative integer");if(!Number.isInteger(n)||n<0)throw new O(`${e} must be a non-negative integer`);return n}function Xr(t,e){let n=te(Yr,t,e,"must be a positive number");if(!Number.isFinite(n)||n<=0)throw new O(`${e} must be a positive number`);return n}function Zo(t,e){let n=te(Yr,t,e,"must be a number greater than 0 and at most 1");if(!(n>0&&n<=1))throw new O(`${e} must be a number greater than 0 and at most 1`);return n}function rt(t,e,n){return te(al(t),e,n,`must be one of ${t.join(", ")}`)}function U(t,e,n){return te(Qy,t,e,"must be a list").map((s,o)=>n(s,k(e,o)))}function xt(t,e){return U(t,e,E)}function zr(t,e){return U(t,e,(n,r)=>zl(n,r,Jo))}function Xl(t,e){return U(t,e,(n,r)=>zl(n,r,Oe))}function zl(t,e,n){let r=E(t,e),s=n(r);if(s!==null)throw new O(`${e} ${s}`);return r}function Zl(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new O(`${e} must be an object`);return t}function te(t,e,n,r){try{return t(e)}catch{throw new O(`${n} ${r}`)}}var ek="basic",nk=300,rk=6000,sk=20,ok=1200,ik=60000,ak=25,ck=0.95,lk=0.75,uk=["**/*.test.*","**/*.spec.*","**/*_test.*","**/*-test.{js,cjs,mjs,ts,cts,mts}","**/test-*.{js,cjs,mjs,ts,cts,mts}","**/test.{js,cjs,mjs,ts,cts,mts}","**/test_*.py","**/test/**","**/tests/**","**/__tests__/**"],dk="Fix the reported value in .ari/config.json",pk=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","agents"],mk=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity"],dt=In({agents:{},checkTimeoutSeconds:nk,context:{budget:rk,journalTail:sk},knowledge:{decayAfterTasks:ak,duplicateSimilarity:ck,maxBytes:ik,maxEntryBytes:ok,mergeSimilarity:lk},pack:ek,regression:{setup:[]},requireTask:!1,review:{command:null},testGlobs:uk});function Pn(t){return structuredClone(st("config",dk,()=>fk(t)))}function fk(t){let e=I(t,"config",pk);if(e.$schema!==void 0)E(e.$schema,"$schema");return{agents:J(e.agents,dt.agents,wk),checkTimeoutSeconds:J(e.checkTimeoutSeconds,dt.checkTimeoutSeconds,(n)=>Xr(n,"checkTimeoutSeconds")),context:J(e.context,dt.context,gk),knowledge:J(e.knowledge,dt.knowledge,hk),pack:J(e.pack,dt.pack,(n)=>tn(n,"pack")),regression:J(e.regression,dt.regression,yk),requireTask:J(e.requireTask,dt.requireTask,(n)=>Ie(n,"requireTask")),review:J(e.review,dt.review,kk),testGlobs:J(e.testGlobs,dt.testGlobs,(n)=>Xl(n,"testGlobs"))}}function gk(t){let e=I(t,"context",["budget","journalTail"]),n=dt.context;return{budget:J(e.budget,n.budget,(r)=>_e(r,"context.budget")),journalTail:J(e.journalTail,n.journalTail,(r)=>At(r,"context.journalTail"))}}function hk(t){let e=I(t,"knowledge",mk),n={decayAfterTasks:_n(e,"decayAfterTasks",_e),duplicateSimilarity:_n(e,"duplicateSimilarity",Zo),maxBytes:_n(e,"maxBytes",_e),maxEntryBytes:_n(e,"maxEntryBytes",_e),mergeSimilarity:_n(e,"mergeSimilarity",Zo)};if(n.mergeSimilarity>n.duplicateSimilarity)throw new O("knowledge.mergeSimilarity must not exceed knowledge.duplicateSimilarity");if(n.maxEntryBytes>n.maxBytes)throw new O("knowledge.maxEntryBytes must not exceed knowledge.maxBytes");return n}function _n(t,e,n){return J(t[e],dt.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function yk(t){let e=I(t,"regression",["setup"]);return{setup:J(e.setup,dt.regression.setup,(n)=>U(n,"regression.setup",Qt))}}function kk(t){let e=I(t,"review",["command"]),n=J(e.command,dt.review.command,(r)=>bt(r,"review.command"));if(n!==null&&n.trim().length===0)throw new O("review.command must be a command or null");return{command:n}}function wk(t){let e=ye(t,"agents",$k);for(let[n]of e)tn(n,"agent name");return Object.fromEntries(e)}function $k(t,e){let n=I(t,e,["command"]),r=U(n.command,k(e,"command"),Qt);if(r.length===0)throw new O(`${k(e,"command")} must not be empty`);return{command:r}}var Nn='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',bk=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,xk=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,Sk=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,Ek=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,Tk=/[ \t\n,[\]{}]/;function ti(t){return`defines "${t}" twice`}function ei(t,e){return Zr(bk,t,e)}function ni(t){return String(Bun.YAML.parse(t))}function Ql(t,e){let n=[],r=e,s=!1;while(r<t.length){let o=Ck(t,r,s);if(r+=o.text.length,o.kind==="space")continue;let i=vk(o,n);if(i!==null)return{end:r,problem:i};if(n.length===0)return{end:r,problem:null};s=o.kind==="quoted"||o.kind==="close"}return{end:r,problem:null}}function vk(t,e){let n=e.at(-1),r=n?.keys!=null&&n.inKey;switch(t.kind){case"open":{if(r)return'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys';let s=t.text==="{"?new Set:null;return e.push({inKey:s!==null,key:null,keys:s}),null}case"close":return e.pop(),r?Qo(n):null;case"comma":{let s=r?Qo(n):null;if(n!==void 0)Object.assign(n,{inKey:n.keys!==null,key:null});return s}case"colon":if(!r)return null;return n.inKey=!1,Qo(n);case"special":return r?'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys':null;case"quoted":case"plain":if(r)n.key=t.kind==="quoted"?ni(t.text):t.text.trim();return null;case"space":return null}}function Qo(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return ti(e);return n.add(e),null}function Ck(t,e,n){let r=t[e]??"";if(r==="{"||r==="[")return{kind:"open",text:r};if(r==="}"||r==="]")return{kind:"close",text:r};if(r===",")return{kind:"comma",text:r};if(r===":"&&(n||Tk.test(t[e+1]??" ")))return{kind:"colon",text:r};let s=Zr(Sk,t,e);if(s!==null)return{kind:"space",text:s};let o=ei(t,e);if(o!==null)return{kind:"quoted",text:o};let i=Zr(Ek,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:Zr(xk,t,e)??r}}function Zr(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var Ak=/^(?:---|\.\.\.)(?=[ \t]|$)/,Ok=/^( *)((?:-(?: +|$))*)(.*)$/s,tu=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,Rk=/^#/,Ik=/^[{[]/,_k=/^\?(?:[ \t]|$)/,Pk=/^\*.*:(?:[ \t]|$)/s,eu=/^[ \t]*:(?:[ \t]+|$)/,Nk=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,nu=-1;function ru(t){let e=[],n=null,r=0,s=0;for(let o of t.split(`
|
|
61
|
+
`)){let i=s;if(s+=o.length+1,i<r)continue;let a=o.match(Ak)?.[0];if(a!==void 0)e.length=0,n=null;let c=a===void 0?o:o.replace(a," ".repeat(a.length)),[,l="",u="",d=""]=c.match(Ok)??[];if(n!==null&&l.length>n)continue;if(u===""&&su(d))continue;let p=l.length+u.length;Mk(e,u===""?p:l.length);let f=Dk(d);if(f===Nn)return f;if(f!==null){let{keys:x}=Gk(e,p);if(x.has(f.name))return ti(f.name);x.add(f.name)}let m=Lk(f===null?d:f.value),h=u===""?e.at(-1)?.column??nu:c.lastIndexOf("-",p-1);if(n=m.kind==="text"?f===null?h:p:null,m.kind!=="flow")continue;let y=Ql(t,i+c.length-m.text.length);if(y.problem!==null)return y.problem;if(r=y.end,f===null&&eu.test(t.slice(y.end,s).trimEnd()))return Nn}return null}function Dk(t){if(_k.test(t)||Pk.test(t))return Nn;let e=t.replace(tu,""),n=jk(e);return n!==null&&e!==t?Nn:n}function jk(t){let e=ei(t,0);if(e===null){let[,r,s=""]=t.match(Nk)??[];return r===void 0?null:{name:r,value:s}}let n=t.slice(e.length).match(eu)?.[0];return n===void 0?null:{name:ni(e),value:t.slice(e.length+n.length)}}function Lk(t){let e=t.replace(tu,"");if(su(e))return{kind:"block",text:e};return{kind:Ik.test(e)?"flow":"text",text:e}}function su(t){return t.trim()===""||Rk.test(t)}function Mk(t,e){while((t.at(-1)?.column??nu)>e)t.pop()}function Gk(t,e){let n=t.at(-1);if(n?.column===e)return n;let r={column:e,keys:new Set};return t.push(r),r}var en="---",Hk=/^\uFEFF+/,Fk=/\r\n?/g;function Qr(t){return t.replace(Hk,"").replace(Fk,`
|
|
62
|
+
`)}function ts(t){let e=Qr(t).split(`
|
|
63
|
+
`);if(e[0]?.trimEnd()!==en)throw new O(`the file must start with a "${en}" line that opens the front matter`);let n=e.findIndex((r,s)=>s>0&&r.trimEnd()===en);if(n===-1)throw new O(`the front matter has no closing "${en}" line`);return{body:e.slice(n+1).join(`
|
|
64
|
+
`),data:ri(e.slice(1,n).join(`
|
|
65
|
+
`),"the front matter")}}function es(t,e){return`${en}
|
|
66
|
+
${t.join(`
|
|
67
|
+
`)}
|
|
68
|
+
${en}
|
|
69
|
+
${e}`}function Kt(t){return JSON.stringify(t.toWellFormed())}function nn(t){return`[${t.map(Kt).join(", ")}]`}function ri(t,e){let n=Qr(t),r=Kk(n,e),s=ru(n);if(s===null)return r;throw new O(`${e} ${s}`)}function Kk(t,e){try{return Bun.YAML.parse(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new O(`${e} is not valid YAML (${r})`)}}var oi=3,iu="spike",Uk=/^[A-Za-z][A-Za-z0-9._-]*$/,Bk=["pass","fail","regression"],Wk={all:"check",criteria:"check bound to a criterion","expect:fail":"check with expect: fail","expect:pass":"check with expect: pass","expect:regression":"check with expect: regression"},Vk=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],Jk="AC-1",qk="Describe the change, its constraints and how a reviewer can verify it.";function ns(t,e,n){return st(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>Yk(t,e,n))}function ee(t){return $t(Qr(t))}function au(t,e){let n=e===iu?["criteria: []"]:["criteria:",` - id: ${Kt(Jk)}`,' text: ""'," checks: []"],r=[`title: ${Kt(t)}`,`pack: ${Kt(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${oi}`];return es(r,`${qk}
|
|
70
|
+
`)}function rn(t,e){let n=e.find((s)=>s.name===t.pack),r=[...rw(t),...ii(t)];return[...Qk(t),...tw(t,n,e,r.length>0),...ou("scope",t.scope,!0),...ou("lock",t.lock,!1),...nw(t),...r,...sw(t),...ow(t)]}function sn(t,e){switch(e){case"all":return t.checks;case"criteria":{let n=new Set(t.criteria.flatMap((r)=>r.checks));return t.checks.filter((r)=>n.has(r.name))}case"expect:pass":return si(t,"pass");case"expect:fail":return si(t,"fail");case"expect:regression":return si(t,"regression")}}function si(t,e){return t.checks.filter((n)=>n.expect===e)}function ii(t){let e=new Set(t.checks.map((n)=>n.name));return t.criteria.flatMap((n)=>{if(n.checks.length===0)return[`criterion ${n.id} must name at least one check`];return n.checks.filter((r)=>!e.has(r)).map((r)=>`criterion ${n.id} names unknown check "${r}"`)})}function Yk(t,e,n){let{body:r,data:s}=ts(e),o=I(s,"front matter",Vk);return{body:r.trim(),budget:q(o.budget,{attempts:oi},Xk),checks:q(o.checks,[],(i)=>Zk(i,n.checkTimeoutSeconds)),criteria:q(o.criteria,[],(i)=>U(i,"criteria",zk)),depends:q(o.depends,[],(i)=>xt(i,"depends")),id:t,invariants:q(o.invariants,[],(i)=>xt(i,"invariants")),lock:q(o.lock,[],(i)=>xt(i,"lock")),pack:q(o.pack,n.pack,(i)=>E(i,"pack")),scope:ht(o.scope,"scope",xt),title:ht(o.title,"title",E)}}function Xk(t){let e=I(t,"budget",["attempts"]);return{attempts:q(e.attempts,oi,(n)=>_e(n,"budget.attempts"))}}function zk(t,e){let n=I(t,e,["id","text","checks"]);return{checks:q(n.checks,[],(r)=>xt(r,k(e,"checks"))),id:ht(n.id,k(e,"id"),E),text:ht(n.text,k(e,"text"),E)}}function Zk(t,e){return ye(t,"checks",(n,r,s)=>{if(!Uk.test(s))throw new O(`${r} must be named with a letter followed by letters, digits, ".", "_" or "-"`);let o=I(n,r,["run","expect","timeout"]);return{expect:q(o.expect,"pass",(i)=>rt(Bk,i,k(r,"expect"))),name:s,run:ht(o.run,k(r,"run"),E),timeoutSeconds:q(o.timeout,e,(i)=>Xr(i,k(r,"timeout")))}}).map(([,n])=>n)}function Qk(t){return t.title.trim().length===0?["title must not be empty"]:[]}function tw(t,e,n,r){if(!e){let o=n.map((i)=>i.name).join(", ");return[`pack "${t.pack}" is not a built-in or project pack (available: ${o})`]}return[...new Set(e.stages.flatMap((o)=>o.gates.flatMap(ew)))].filter((o)=>!r||o!=="all"&&o!=="criteria").filter((o)=>sn(t,o).length===0).map((o)=>`pack "${e.name}" needs at least one ${Wk[o]}`)}function ew(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function ou(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],s=e.flatMap((o)=>{let i=Oe(o);return i===null?[]:[`${t} glob ${JSON.stringify(o)} ${i}`]});return[...r,...s]}function nw(t){return t.depends.flatMap((e)=>{if(e.trim().length===0)return["depends must not contain an empty task id"];return e===t.id?[`depends must not name the task itself ("${t.id}")`]:[]})}function rw(t){let n=t.pack!==iu&&t.criteria.length===0?[`criteria must list at least one criterion for pack "${t.pack}"`]:[],r=t.criteria.map((o)=>o.id),s=t.criteria.flatMap((o,i)=>{if(o.id.trim().length===0)return[`criteria[${i}] must have an id`];let a=r.indexOf(o.id)<i?[`criterion id "${o.id}" is used more than once`]:[],c=o.text.trim().length===0?[`criterion ${o.id} must have text`]:[];return[...a,...c]});return[...n,...s]}function sw(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function ow(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var iw=2;function ot(t){return`${JSON.stringify(t,aw,iw)}
|
|
71
|
+
`}function aw(t,e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;return Object.fromEntries(Object.entries(e).sort(([n],[r])=>N(n,r)))}var Pe=["fact","decision","constraint","pattern","gotcha"],cw=["active","archived"],lw=/^\d{4}-\d{2}-\d{2}$/,uw=/\s+/g,dw=["kind","scope","sources","status","supersedes","supersededBy","created"];function rs(t,e){return st(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>pw(t,e))}function ss(t){let e=[`kind: ${Kt(t.kind)}`,`scope: ${nn(t.scope)}`,`sources: ${nn(t.sources)}`,`status: ${Kt(t.status)}`,`supersedes: ${nn(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":Kt(t.supersededBy)}`,`created: ${Kt(t.created)}`];return es(e,`${t.text.trim()}
|
|
72
|
+
`)}function ai(t){return t.normalize("NFC").toLowerCase().replace(uw," ").trim()}function pw(t,e){let{body:n,data:r}=ts(e),s=I(r,"front matter",dw),o=ht(s.created,"created",E);if(!lw.test(o))throw new O(`created must be a YYYY-MM-DD date, got "${o}"`);let i=n.trim();if(i.length===0)throw new O("the entry text is empty");return{created:o,id:t,kind:ht(s.kind,"kind",(a,c)=>rt(Pe,a,c)),scope:q(s.scope,[],(a)=>zr(a,"scope")),sources:q(s.sources,[],(a)=>xt(a,"sources")),status:q(s.status,"active",(a)=>rt(cw,a,"status")),supersededBy:q(s.supersededBy,null,(a)=>bt(a,"supersededBy")),supersedes:q(s.supersedes,[],(a)=>xt(a,"supersedes")),text:i}}var du=200,mw=/\{id\}/g,fw="Fix the pack file; see the packs section of the Ariadne design",gw=["all","criteria","expect:pass","expect:fail","expect:regression"],hw=["pass","fail"],os={kind:"criteria"},ke={kind:"invariants"},jt={kind:"scope"},ne={kind:"locked"},ci={kind:"tests-unchanged"},yw={kind:"regression"},cu={kind:"approval"},kw={kind:"review"};function Lt(t,e){return{expect:e,kind:"checks",select:t}}function lu(t){return{kind:"artifact",minBytes:du,path:t}}var uu=In([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[os,Lt("criteria","pass"),ke,jt,ne],instruction:"Implement the change inside the scope until every criterion's checks pass.",name:"implement"}]},{description:"Approved design, implementation, then review",name:"sdlc",stages:[{gates:[lu(".ari/designs/{id}.md"),cu],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[os,Lt("all","pass"),ke,jt,ne],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[kw,Lt("all","pass"),ke,jt,ne],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]},{description:"Red, green, refactor with frozen tests",name:"tdd",stages:[{gates:[os,Lt("criteria","fail"),jt],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[Lt("all","pass"),ci,ke,jt,ne],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[Lt("all","pass"),ci,ke,jt,ne],instruction:"Improve the code while every check stays green. Do not edit the tests.",name:"refactor"}]},{description:"Reproduce the bug with a regression check, then fix it",name:"bugfix",stages:[{gates:[Lt("expect:regression","fail"),jt],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[yw,Lt("all","pass"),ke,jt,ne],instruction:"Fix the bug so the regression check passes here and still fails on the base commit.",name:"fix"}]},{description:"Approved specification, then implementation",name:"spec-driven",stages:[{gates:[os,cu],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[Lt("all","pass"),ke,jt,ne],instruction:"Implement the approved specification inside the scope until every check passes.",name:"implement"}]},{description:"Change the structure without changing behaviour",name:"refactor",stages:[{gates:[ci,Lt("all","pass"),ke,jt,ne],instruction:"Restructure the code without changing behaviour. Keep the tests unchanged and every check green.",name:"refactor"}]},{description:"Exploration that ends in written findings",name:"spike",stages:[{gates:[lu(".ari/designs/{id}.md"),jt,ne],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]}]),pu={approval:(t,e)=>we(t,e,"approval"),artifact:Ew,checks:Sw,command:(t,e)=>{let n=I(t,e,["kind","run"]);return{kind:"command",run:Qt(n.run,k(e,"run"))}},criteria:(t,e)=>we(t,e,"criteria"),invariants:(t,e)=>we(t,e,"invariants"),locked:(t,e)=>we(t,e,"locked"),regression:(t,e)=>we(t,e,"regression"),review:(t,e)=>we(t,e,"review"),scope:(t,e)=>we(t,e,"scope"),"tests-unchanged":(t,e)=>we(t,e,"tests-unchanged")},ww=Object.keys(pu);function is(t,e="pack"){return st(e,fw,()=>$w(ri(t,"the pack file")))}function Ne(t){let e=new Map(t.map((o)=>[o.name,o])),n=uu.map((o)=>e.get(o.name)??o),r=new Set(uu.map((o)=>o.name)),s=t.filter((o)=>!r.has(o.name)).sort((o,i)=>N(o.name,i.name));return[...n,...s]}function De(t,e){let n=Ne(e),r=n.find((o)=>o.name===t);if(r)return r;let s=n.map((o)=>o.name).join(", ");throw new g(`Unknown pack "${t}"`,`Use one of ${s}, or add .ari/packs/${t}.yaml`)}function as(t,e){let{regression:n,review:r,testGlobs:s}=e,o=t.stages.map(({gates:i,name:a})=>({gates:i,name:a}));return $t(ot({regression:n,review:r,stages:o,testGlobs:s}))}function on(t,e){return t.instruction.replace(mw,e)}function $w(t){let e=I(t,"pack",["name","description","stages"]),n=U(e.stages,"stages",bw);if(n.length===0)throw new O("stages must list at least one stage");let r=new Set;for(let[s,o]of n.entries()){if(r.has(o.name))throw new O(`stages[${s}].name repeats "${o.name}"`);r.add(o.name)}return{description:q(e.description,"",(s)=>E(s,"description")),name:tn(e.name,"name"),stages:n}}function bw(t,e){let n=I(t,e,["name","instruction","gates"]),r=U(n.gates,k(e,"gates"),xw);if(r.length===0)throw new O(`${k(e,"gates")} must list at least one gate`);let s=new Set(r.map((o)=>o.kind));if(s.has("tests-unchanged")&&!s.has("scope"))throw new O(`${k(e,"gates")} has tests-unchanged without scope; tests-unchanged covers the test files inside the scope and relies on the scope gate for the rest`);return{gates:r,instruction:Qt(n.instruction,k(e,"instruction")),name:tn(n.name,k(e,"name"))}}function xw(t,e){let n=I(t,e,["kind","select","expect","path","minBytes","run"]),r=rt(ww,n.kind,k(e,"kind"));return pu[r](n,e)}function we(t,e,n){return I(t,e,["kind"]),{kind:n}}function Sw(t,e){let n=I(t,e,["kind","select","expect"]);return Lt(q(n.select,"all",(r)=>rt(gw,r,k(e,"select"))),q(n.expect,"pass",(r)=>rt(hw,r,k(e,"expect"))))}function Ew(t,e){let n=I(t,e,["kind","path","minBytes"]),r=Qt(n.path,k(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new O(`${k(e,"path")} must stay inside the repository`);return{kind:"artifact",minBytes:q(n.minBytes,du,(o)=>At(o,k(e,"minBytes"))),path:r}}var mu="attempt budget exhausted",fu="failedAttempts",Tw={active:()=>"Run 'ari done' to finish the current stage",blocked:(t)=>`Run 'ari resolve ${t} --answer <text>'`,done:()=>`Done tasks are final; create a follow-up with 'ari new "<title>"'`,draft:(t)=>`Complete the contract, then run 'ari ready ${t}'`,ready:(t)=>`Run 'ari start ${t}'`};function Ut(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function li(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[Ut("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function hu(t){let e=t.history[0]?.at??"";return ot(t)===ot(li(t.id,e))}function ui(t,e){return re(t,["draft"],"mark ready"),{...t,history:[...t.history,Ut("ready",e)],status:"ready"}}function yu(t,e,n,r){return re(t,["ready"],"start"),{...t,attempts:0,...Tu(n),base:e,history:[...t.history,Ut("started",r,{detail:e})],stage:0,status:"active"}}function ku(t,e,n,r){if(re(t,["active"],"record a passed stage for"),!Number.isInteger(n)||t.stage>=n)throw Error(`Stage ${t.stage} of task "${t.id}" is outside a pack of ${n} stages`);let s=t.stage+1>=n,o=Ut(s?"done":"advanced",e.at,{stage:e.stage});return{...t,evidence:[...t.evidence,e],history:[...t.history,o],lastFailure:null,stage:s?t.stage:t.stage+1,stageTestHashes:{...r},status:s?"done":"active"}}function wu(t,e,n){if(re(t,["active"],"record a failed attempt for"),!Number.isInteger(n)||n<=0)throw Error(`Attempt budget must be a positive integer: ${n}`);let r=t.attempts+1,s=e.gates.filter((c)=>!c.ok).map((c)=>c.gate),o=Ut("failed",e.at,{detail:`attempt ${r} of ${n}: ${s.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=Ut("blocked",e.at,{detail:mu,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,o,a]:[...t.history,o],lastFailure:e,question:i?mu:t.question,status:i?"blocked":"active"}}function di(t,e,n){re(t,["draft","ready","active","blocked"],"amend");let r=Dn(e.reason,"Amending a task needs a reason","Pass --reason <text>"),s=e.base!==null&&e.base!==t.base;if(s)re(t,["active","blocked"],"move the base of");let o=s?e.base:t.base,i=`gates ${e.gatesHash}, locks ${gu(e.lockHashes)}, tests ${gu(e.stageTestHashes)}`,a=s?`, base ${t.base} -> ${o}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...Tu(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:o,history:[...t.history,Ut("amended",n,{detail:c})]}}function $u(t,e,n){re(t,["active"],"block");let r=Dn(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,Ut("blocked",n,{detail:r})],question:r,status:"blocked"}}function pi(t,e,n){re(t,["blocked"],"resolve");let r=Dn(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,Ut("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function bu(t,e,n){re(t,["active"],"approve");let{artifactHashes:r,stage:s,treeHash:o}=e,i=Dn(e.by,"An approval needs the approver's name","Set git user.name so the approval records who gave it");return{...t,approvals:[...t.approvals,{artifactHashes:{...r},at:n,by:i,stage:s,treeHash:o}],history:[...t.history,Ut("approved",n,{by:i,stage:s})]}}function xu(t,e,n){let r=Dn(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function cs(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([s])=>s!==fu));for(let s of e)n.set(s.type,(n.get(s.type)??0)+1);let r=t.history.filter((s)=>s.type==="failed").length;return{...t,journalStats:{...Object.fromEntries(n),[fu]:r}}}function Su(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(N);return{...t,knowledgeUsed:n}}function Eu(t,e){let n=`Run 'ari sleep' to list the unpromoted notes of "${t.id}"`;for(let s of e){let o=t.notes[s];if(o===void 0)throw new g(`Task "${t.id}" has no note ${s}`,n);if(o.promoted)throw new g(`Note ${s} of task "${t.id}" is already promoted`,n)}let r=new Set(e);return{...t,notes:t.notes.map((s,o)=>r.has(o)?{...s,promoted:!0}:s)}}function Tu({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function gu(t){return $t(ot(t))}function re(t,e,n){if(e.includes(t.status))return;throw new g(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,Tw[t.status](t.id))}function Dn(t,e,n){let r=t.trim();if(r.length===0)throw new g(e,n);return r}import{mkdirSync as vw,readFileSync as Cw,rmSync as ls,statSync as Aw,writeFileSync as Ow}from"fs";import{dirname as Rw}from"path";var Iw="EEXIST",_w="ENOENT",Pw="ESRCH",Nw=".break",Dw=20,jw=1e4,Lw=1000,Mw=10,Gw=0;function fi(t,e,n){Hw(t,e);try{return n()}finally{ls(t,{force:!0})}}function Hw(t,e){vw(Rw(t),{recursive:!0});let n=Date.now()+jw;while(!vu(t)){if(mi(t))Fw(t);if(Date.now()>=n)throw new g(`Another ari process is still changing task "${e}"`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(Dw)}}function Fw(t){let e=`${t}${Nw}`;if(!vu(e)){if(mi(e))ls(e,{force:!0});return}try{if(mi(t))ls(t,{force:!0})}finally{ls(e,{force:!0})}}function vu(t){try{return Ow(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(gi(e)===Iw)return!1;throw e}}function mi(t){let e=Kw(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>Lw;return!Uw(e.pid)}function Kw(t){try{return{modifiedMs:Aw(t).mtimeMs,pid:Number.parseInt(Cw(t,"utf8"),Mw)}}catch(e){if(gi(e)===_w)return null;throw e}}function Uw(t){try{return process.kill(t,Gw),!0}catch(e){return gi(e)!==Pw}}function gi(t){return t.code}var Bw=["draft","ready","active","blocked","done"],Ww=["pass","fail"],Vw=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],Jw=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],qw=["edit","shell","tool","check","done","context","note","stop","compact","session"],Yw=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],Xw=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Cu(t,e){return st(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=zw(e);if(n.id!==t)throw new O(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function ds(t){let e=I(t,"event",["at","detail","task","type"]);return{at:E(e.at,"at"),detail:Object.fromEntries(ye(e.detail,"detail",o$)),task:E(e.task,"task"),type:rt(qw,e.type,"type")}}function zw(t){let e=I(t,"record",Yw);return{approvals:U(e.approvals,"approvals",Zw),attempts:At(e.attempts,"attempts"),base:bt(e.base,"base"),contractHash:bt(e.contractHash,"contractHash"),evidence:U(e.evidence,"evidence",e$),gatesHash:J(e.gatesHash,null,(n)=>bt(n,"gatesHash")),history:U(e.history,"history",t$),id:E(e.id,"id"),journalStats:e.journalStats===null?null:s$(e.journalStats,"journalStats"),knowledgeUsed:xt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:n$(e.lastFailure,"lastFailure"),lockHashes:us(e.lockHashes,"lockHashes"),notes:U(e.notes,"notes",Qw),question:bt(e.question,"question"),stage:At(e.stage,"stage"),stageTestHashes:us(e.stageTestHashes,"stageTestHashes"),status:rt(Bw,e.status,"status")}}function Zw(t,e){let n=I(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:J(n.artifactHashes,{},(r)=>us(r,k(e,"artifactHashes"))),at:E(n.at,k(e,"at")),by:E(n.by,k(e,"by")),stage:E(n.stage,k(e,"stage")),treeHash:J(n.treeHash,null,(r)=>bt(r,k(e,"treeHash")))}}function Qw(t,e){let n=I(t,e,["at","promoted","text"]);return{at:E(n.at,k(e,"at")),promoted:Ie(n.promoted,k(e,"promoted")),text:E(n.text,k(e,"text"))}}function t$(t,e){let n=I(t,e,["at","by","detail","stage","type"]);return{at:E(n.at,k(e,"at")),by:bt(n.by,k(e,"by")),detail:bt(n.detail,k(e,"detail")),stage:bt(n.stage,k(e,"stage")),type:rt(Jw,n.type,k(e,"type"))}}function e$(t,e){let n=I(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:E(n.at,k(e,"at")),gates:U(n.gates,k(e,"gates"),Au),stage:E(n.stage,k(e,"stage")),testHashes:us(n.testHashes,k(e,"testHashes")),treeHash:E(n.treeHash,k(e,"treeHash"))}}function n$(t,e){let n=I(t,e,["at","gates","stage","treeHash"]);return{at:E(n.at,k(e,"at")),gates:U(n.gates,k(e,"gates"),Au),stage:E(n.stage,k(e,"stage")),treeHash:E(n.treeHash,k(e,"treeHash"))}}function Au(t,e){let n=I(t,e,["checks","details","gate","ok","summary"]);return{checks:U(n.checks,k(e,"checks"),r$),details:xt(n.details,k(e,"details")),gate:rt(Vw,n.gate,k(e,"gate")),ok:Ie(n.ok,k(e,"ok")),summary:E(n.summary,k(e,"summary"))}}function r$(t,e){let n=I(t,e,Xw),r=k(e,"exitCode");return{command:E(n.command,k(e,"command")),durationMs:At(n.durationMs,k(e,"durationMs")),exitCode:n.exitCode===null?null:At(n.exitCode,r),expect:rt(Ww,n.expect,k(e,"expect")),name:E(n.name,k(e,"name")),ok:Ie(n.ok,k(e,"ok")),outputSha256:E(n.outputSha256,k(e,"outputSha256")),outputTail:E(n.outputTail,k(e,"outputTail")),timedOut:Ie(n.timedOut,k(e,"timedOut"))}}function us(t,e){return Object.fromEntries(ye(t,e,E))}function s$(t,e){return Object.fromEntries(ye(t,e,At))}function o$(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return xt(t,e)}var W=".ari",je=".ari/tasks/*.json",Pu=".ari/tasks/*.md",jn=".ari/config.json",an="ids",d$=`${W}/`,ms="tasks",Nu="knowledge",Du="packs",p$="ari",yi="active.json",m$="journal",ju=".md",Lu=".json",Mu=".md",hi=".yaml",f$=".jsonl",ki=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Gu=`
|
|
73
|
+
`,g$=".ari-",h$=".tmp",y$="ENOENT",Hu="EEXIST",k$=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),w$="locks",$$=".lock";function cn(t){return t===W||t.startsWith(d$)}function yt(t){return t.filter((e)=>!cn(e))}function ln(t){if(Bt(X(t,W)))return;throw new g("Ariadne is not initialised in this repository","Run 'ari init'")}function Fu(t){let e=X(t,jn);if(Bt(e))return!1;return Ei(e,ot(dt)),!0}function Y(t){ln(t);let e=X(t,jn);if(!Bt(e))return Pn({});return Pn(Si(e,jn,"Fix the JSON syntax of .ari/config.json"))}function wi(t){return ki.test(t)}function un(t){if(wi(t))return t;throw new g(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function pt(t){return`${W}/${ms}/${un(t)}${ju}`}function se(t){return`${W}/${ms}/${un(t)}${Lu}`}function $i(t){return`${W}/${Du}/${t}${hi}`}function Mt(t){return ln(t),hs(X(t,W,ms),ju)}function Mn(t){return ln(t),hs(X(t,W,ms),Lu)}function Q(t,e,n){ln(t);let r=X(t,pt(e));if(!Bt(r))throw new g(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let s=Ln(r,"utf8");return{contractText:s,task:{contract:ns(e,s,n),record:Me(t,e)}}}function Gt(t,e){let n={invalid:[],tasks:[]};for(let r of Mt(t))try{n.tasks.push(Q(t,r,e).task)}catch(s){if(!(s instanceof g))throw s;n.invalid.push({hint:s.hint??"",id:r,problem:s.message})}return n}function Ku(t,e,n,r){let{id:s}=n,o=pt(s),i=()=>new g(`Task "${s}" already exists at ${o}`,"Run 'ari list'");fi(qu(e,s),s,()=>{if(Bt(X(t,o))||!Ju(t,s))throw i();Bu(t,n),Xu(X(t,o),r,i)})}function Uu(t){let e=Mt(t);return[...e,...Mn(t).filter((n)=>!e.includes(n)&&!Ju(t,n))]}function Bu(t,e){Ei(X(t,se(e.id)),ot(e))}function Ot(t,e,n,r){return fi(qu(e,n),n,()=>{let s=r(Me(t,n));return Bu(t,s),s})}function $e(t){ln(t);let e=X(t,W,Du);return hs(e,hi).map((n)=>{let r=$i(n),s=is(Ln(X(t,r),"utf8"),r);if(s.name===n)return s;throw new g(`${r} declares the pack "${s.name}"`,`Rename the file to ${s.name}${hi} or fix its name`)})}function oe(t){return ln(t),hs(X(t,W,Nu),Mu)}function ie(t){return oe(t).map((e)=>rs(e,Ln(Yu(t,e),"utf8")))}function fs(t,e){if(!ki.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=Yu(t,e.id);Xu(n,ss(e),()=>Error(`Knowledge entry ${n} already exists`))}async function tt(t){return Re(t,p$)}function it(t){let e=X(t,yi);if(!Bt(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Si(e,e,n);return st("active task pointer",n,()=>{let s=I(r,"pointer",["since","task"]);return{since:E(s.since,"since"),task:E(s.task,"task")}})}function bi(t,e){Ei(X(t,yi),ot(e))}function Wu(t){ps(X(t,yi),{force:!0})}function Le(t,e){let n=xi(t,e.task);Ou(_u(n),{recursive:!0});let r=JSON.stringify(JSON.parse(ot(e)));a$(n,`${r}${Gu}`)}function gs(t,e){ps(xi(t,e),{force:!0})}function Vu(t,e){let n=xi(t,e);if(!Bt(n))return[];return Ln(n,"utf8").split(Gu).flatMap((r)=>{if(r.trim().length===0)return[];let s=b$(r);return s===null||s.task!==e?[]:[s]})}function b$(t){try{return ds(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof O)return null;throw e}}function xi(t,e){return X(t,m$,`${un(e)}${f$}`)}function Me(t,e){let n=se(e),r=X(t,n);if(!Bt(r))throw new g(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Cu(e,Si(r,n,`Restore ${n} from git; only ari writes it`))}function Ju(t,e){if(!Bt(X(t,se(e))))return!0;try{return hu(Me(t,e))}catch(n){if(n instanceof g)return!1;throw n}}function qu(t,e){return X(t,w$,`${un(e)}${$$}`)}function Yu(t,e){return X(t,W,Nu,`${e}${Mu}`)}function Si(t,e,n){let r=Ln(t,"utf8");try{return JSON.parse(r)}catch(s){let o=s instanceof Error?s.message:String(s);throw new g(`${e} is not valid JSON (${o})`,n)}}function hs(t,e){return x$(t).filter((r)=>r.endsWith(e)).map((r)=>u$(r,e)).filter((r)=>ki.test(r)).sort(N)}function x$(t){try{return l$(t)}catch(e){if(e.code===y$)return[];throw e}}function Ei(t,e){let n=zu(t);try{Iu(n,e),Ru(n,t)}catch(r){throw ps(n,{force:!0}),r}}function Xu(t,e,n){let r=zu(t);try{Iu(r,e),S$(r,t)}catch(s){if(s.code===Hu)throw n();throw s}finally{ps(r,{force:!0})}}function S$(t,e){try{c$(t,e)}catch(n){if(!k$.has(n.code??""))throw n;if(Bt(e))throw Object.assign(Error(`${e} already exists`),{code:Hu});Ru(t,e)}}function zu(t){let e=_u(t);return Ou(e,{recursive:!0}),X(e,`${g$}${i$()}${h$}`)}async function ys(t){let e=Y(t),n=await tt(t),r={config:e,drift:null,root:t,state:n,task:null},s=it(n)?.task??null;if(s===null)return r;if(!Mt(t).includes(s)){if(Mn(t).includes(s)&&Zu(Me(t,s)))throw E$(s);return r}let{contractText:o,task:i}=Q(t,s,e);if(!Zu(i.record))return r;return{...r,drift:T$(i,o),task:i}}function Zu({status:t}){return t==="active"||t==="blocked"}function E$(t){return new g(`the contract of the active task "${t}" is missing`,`Restore ${pt(t)}`)}function T$({contract:t,record:e},n){if(e.contractHash===null||ee(n)===e.contractHash)return null;return`the contract of task "${t.id}" changed after its approval; run 'ari amend ${t.id} --reason <text>' or restore ${pt(t.id)}`}async function Qu(t,e={}){let n=e.staged??!1,{config:r,drift:s,task:o}=await ys(t);if(o===null){let d=r.requireTask?"config.requireTask is true, but no task is active in this worktree":null;return{checked:[],ok:d===null,outside:[],reason:d,staged:n,task:null}}let i=yt(n?await v$(t):await Ct(t,o.record.base??"HEAD")),a=i.filter((d)=>!K(d,o.contract.scope)),c=Z(a.length,"changed file lies","changed files lie"),l=a.length===0?null:`${a.length} ${c} outside the scope of "${o.contract.id}"`,u=i.length===0?null:s??l;return{checked:i,ok:u===null,outside:a,reason:u,staged:n,task:o.contract.id}}async function v$(t){let e=await A(t,["diff","--cached","--name-only","--no-renames","-z"]);return Zt(e.stdout)}var td=1.2,ed=0.75,nd=0.5,C$=/[\p{Variation_Selector}\p{Me}]/gu,A$=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function rd(t){return t.normalize("NFC").toLowerCase().replace(C$,"").match(A$)??[]}function ks(t,e){let n=[...new Set(rd(t))].sort(N),r=e.map(O$),s=r.reduce((a,c)=>a+c.length,0),o=r.length===0?0:s/r.length,i=new Map(n.map((a)=>[a,R$(a,r)]));return r.map((a)=>({id:a.id,score:I$(a,n,i,o)})).sort((a,c)=>c.score-a.score||N(a.id,c.id))}function O$(t){let e=rd(t.text),n=new Map;for(let r of e)n.set(r,(n.get(r)??0)+1);return{frequencies:n,id:t.id,length:e.length}}function R$(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+nd)/(n+nd))}function I$(t,e,n,r){let s=r===0?1:t.length/r,o=td*(1-ed+ed*s);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(td+1)/(c+o)},0)}function et(t){return Buffer.byteLength(t,"utf8")}function Ti(t){return Math.ceil(et(t)/4)}import{readFileSync as Q$}from"fs";import{join as pd}from"path";import{copyFileSync as K$,mkdirSync as U$,readlinkSync as B$,rmSync as Ci,symlinkSync as W$}from"fs";import{dirname as V$,join as ws}from"path";import{existsSync as _$,mkdtempSync as P$,readFileSync as N$,realpathSync as D$,rmSync as sd}from"fs";import{tmpdir as j$}from"os";import{join as vi}from"path";var Gn=0,od=128,L$="ari-base-",M$="gitdir",G$=".git",H$=["-c","core.hooksPath=/dev/null"];async function ad(t,e,n){let r=D$(P$(vi(j$(),L$))),s={admin:null,directory:r},o=ge(()=>id(t,s));try{return await F$(t,e,s),await n(r)}finally{id(t,s),o()}}async function F$(t,e,n){let{directory:r}=n,s=await A(t,[...H$,"worktree","add","--detach",r,e],{allowedExitCodes:[Gn,od],env:{GIT_INDEX_FILE:void 0}});if(s.exitCode!==Gn)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${Xo(s.stderr)}`);let o=await A(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[Gn,od],env:Ur}),i=o.stdout.trim();if(o.exitCode===Gn&&cd(i,r))n.admin=i}function id(t,e){let{admin:n,directory:r}=e,s=Bun.spawnSync(["git","worktree","remove","--force",r],{cwd:t,env:{...process.env,GIT_INDEX_FILE:void 0},stderr:"ignore",stdin:"ignore",stdout:"ignore"});if(sd(r,{force:!0,recursive:!0}),s.exitCode===Gn||n===null)return;if(cd(n,r))sd(n,{force:!0,recursive:!0})}function cd(t,e){let n=vi(t,M$);return _$(n)&&N$(n,"utf8").trim()===vi(e,G$)}var J$="@base",q$=12;async function ld(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return z("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,q$),r=yt(t.changedFiles).filter((p)=>K(p,t.config.testGlobs)),s=await ad(t.root,t.base,(p)=>Y$(t,e,r,p)),o=await wt(e,"pass",t.root),i=[...s.setup,...s.checks,...o],c=s.setup.some((p)=>!p.ok)?[`regression checks did not run on ${n} because its setup failed`]:[],l=[...Ae(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${Z(l.length,"problem","problems")} against ${n}`;return z("regression",u,d,l,i)}async function Y$(t,e,n,r){for(let i of n)z$(t.root,r,i);let s=await wt(X$(t.config),"pass",r);if(s.some((i)=>!i.ok))return{checks:[],setup:s};let o=e.map((i)=>({...i,name:`${i.name}${J$}`}));return{checks:await wt(o,"fail",r),setup:s}}function X$(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function z$(t,e,n){let r=ws(t,n),s=ws(e,n),o=ze(t,n)?null:he(r);if(o===null){Z$(e,n);return}if(!o.isFile()&&!o.isSymbolicLink())return;if(ud(e,n),Ci(s,{force:!0,recursive:!0}),o.isFile())K$(r,s);else W$(B$(r),s)}function Z$(t,e){let n=ws(t,e);if(ze(t,e)||he(n)?.isDirectory()!==!1)return;Ci(n,{force:!0})}function ud(t,e){let n=V$(e);if(n===".")return;ud(t,n);let r=ws(t,n),s=he(r);if(s?.isDirectory())return;if(s!==null)Ci(r,{force:!0});U$(r)}var tb="{id}",eb=[".ari/tasks/**",".ari/knowledge/**"];async function Oi(t){let e=ae(t.task,t.pack),r={...t,changedFiles:()=>Ct(t.root,gd(t.task)),stage:e},s=[],o=[];for(let[i,a]of e.gates.entries()){let c=await nb(a,r);if(s.push(c),c.ok&&ub(a)&&i<e.gates.length-1)o.push({index:i,result:await db(a.kind,c,r)})}for(let i of o)s[i.index]=await i.result();return s}function ae(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new g(`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${e.name}" has ${e.stages.length}`,`Restore the stages of pack "${e.name}", or amend the task's pack`)}async function Hn(t,e,n){let r=await zt(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([s])=>!cn(s)&&K(s,n.scope)))}async function Ri(t,e,n){let s=e.gates.flatMap((o)=>o.kind==="artifact"?[md(o.path,n)]:[]).flatMap((o)=>{let i=pd(t,o);return qo(i)?.isFile()?[[o,$t(Q$(i))]]:[]});return{artifactHashes:Object.fromEntries(s),treeHash:await Qe(t,eb)}}function Fn(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(N).flatMap((r)=>{let s=t[r],o=e[r];if(s===o)return[];if(s===void 0)return[`added ${r}`];return o===void 0?[`deleted ${r}`]:[`changed ${r}`]})}async function nb(t,e){switch(t.kind){case"criteria":return rb(e.task.contract);case"checks":return sb(t.select,t.expect,e);case"invariants":return ob(e);case"scope":return ib(e);case"locked":return ab(e);case"tests-unchanged":return cb(e);case"regression":return ld({base:gd(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return lb(t.path,t.minBytes,e);case"approval":return Ii("approval",e);case"review":return pb(e);case"command":return mb(t.run,e)}}function rb(t){let e=ii(t),n=e.length===0?`${t.criteria.length} ${Z(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${Z(e.length,"problem","problems")}`;return z("criteria",e.length===0,n,e)}async function sb(t,e,n){let r=sn(n.task.contract,t);if(r.length===0)return z("checks",!1,`no check matches the selection "${t}"`);let s=await wt(r,e,n.root),o=Ae(s),i=e==="pass"?"passed":"failed as expected",a=`${s.length-o.length} of ${s.length} ${Z(s.length,"check","checks")} ${i}`;return z("checks",o.length===0,a,o,s)}async function ob(t){let e=t.task.contract.invariants.map((o,i)=>({name:`invariants[${i}]`,run:o,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await wt(e,"pass",t.root),r=Ae(n),s=`${n.length-r.length} of ${n.length} ${Z(n.length,"invariant","invariants")} passed`;return z("invariants",r.length===0,s,r,n)}async function ib(t){let e=yt(await t.changedFiles()),n=e.filter((s)=>!K(s,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${Z(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${Z(e.length,"file","files")} outside the scope`;return z("scope",n.length===0,r,n)}async function ab(t){let e=await zt(t.root,t.task.contract.lock),n=Fn(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,s=n.length===0?`${r} locked ${Z(r,"file","files")} unchanged`:`${n.length} locked ${Z(n.length,"file","files")} changed`;return z("locked",n.length===0,s,n)}async function cb(t){let e=await Hn(t.root,t.config,t.task.contract),n=Fn(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,s=n.length===0?`${r} test ${Z(r,"file","files")} unchanged since the stage started`:`${n.length} test ${Z(n.length,"file","files")} changed since the stage started`;return z("tests-unchanged",n.length===0,s,n)}function lb(t,e,n){let r=md(t,n.task.contract.id),s=qo(pd(n.root,r));if(!s?.isFile())return z("artifact",!1,`${r} does not exist`);let o=s.size>=e,i=o?`${r} has ${s.size} bytes`:`${r} has ${s.size} bytes; it needs at least ${e}`;return z("artifact",o,i)}function md(t,e){return t.replaceAll(tb,e)}function ub(t){return t.kind==="approval"||t.kind==="review"}async function db(t,e,n){if(t==="approval"||n.config.review.command===null)return()=>Ii(t,n);let r=await Ai(n);return async()=>{if(fd(r,await Ai(n)))return e;return z(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function Ai(t){return Ri(t.root,t.stage,t.task.contract.id)}function fd(t,e){return t.treeHash===e.treeHash&&Fn(t.artifactHashes,e.artifactHashes).length===0}async function Ii(t,e){let n=e.stage.name,r=`a human runs 'ari approve ${e.task.contract.id}'`,s=e.task.record.approvals.filter((c)=>c.stage===n);if(s.length===0)return z(t,!1,`stage ${n} has no approval; ${r}`);let o=await Ai(e),i=s.filter((c)=>fd(c,o));if(i.length>0)return z(t,!0,`stage ${n} approved by ${dd(i)}`);let a=`the working tree changed after ${dd(s)} approved stage ${n}`;return z(t,!1,`${a}; ${r} again`)}function dd(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function pb(t){let e=t.config.review.command;if(e===null)return Ii("review",t);let n={name:"review",run:e,timeoutSeconds:t.config.checkTimeoutSeconds},r=await wt([n],"pass",t.root),s=Ae(r),o=s.length===0?"the review command passed":"the review command failed";return z("review",s.length===0,o,s,r)}async function mb(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r=await wt([n],"pass",e.root),s=Ae(r),o=s.length===0?`${t} passed`:`${t} failed`;return z("command",s.length===0,o,s,r)}function gd(t){if(t.record.base!==null)return t.record.base;throw Error(`Task "${t.contract.id}" has no base commit; gates run only after 'ari start'`)}import{closeSync as fb,existsSync as gb,fstatSync as hb,openSync as yb,readSync as kb}from"fs";import{join as wb}from"path";var $b="journal",bb=".jsonl",hd=65536,xb=1000,$s=10;function bs(t,e,n){let r=[];if(n===0)return r;for(let s of Eb(kd(t,e))){let o=wd(s,e);if(o!==null)r.push(o);if(r.length===n)break}return r.reverse()}function*yd(t,e){let n=[];for(let r of Sb(kd(t,e))){let s=wd(r,e);if(s===null)continue;if(n.push(s),n.length<xb)continue;yield n,n=[]}if(n.length>0)yield n}function kd(t,e){return wb(t,$b,`${un(e)}${bb}`)}function wd(t,e){try{let n=ds(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof O)return null;throw n}}function*Sb(t){let e=[];for(let n of $d(t,!1)){let r=0;for(let s=n.indexOf($s);s!==-1;s=n.indexOf($s,r))yield Buffer.concat([...e,n.subarray(r,s)]),e=[],r=s+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*Eb(t){let e=[];for(let n of $d(t,!0)){let r=n.length;for(let s=n.lastIndexOf($s);s!==-1;s=s===0?-1:n.lastIndexOf($s,s-1))yield Buffer.concat([n.subarray(s+1,r),...e]),e=[],r=s;e.unshift(n.subarray(0,r))}yield Buffer.concat(e)}function*$d(t,e){if(!gb(t))return;let n=yb(t,"r");try{let{size:r}=hb(n);for(let s=0;s<r;s+=hd){let o=Math.min(hd,r-s),i=Buffer.alloc(o),a=kb(n,i,0,o,e?r-s-o:s);yield i.subarray(0,a)}}finally{fb(n)}}import{randomUUID as Rb}from"crypto";import{mkdirSync as Ib,readFileSync as _b,renameSync as Pb,rmSync as Nb,writeFileSync as Db}from"fs";import{basename as jb,dirname as bd,join as xd}from"path";var Tb=/\p{M}+/gu,vb=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,Cb=/[^a-z0-9]+/,Ab={\u{e6}:"ae",\u{f0}:"d",\u{111}:"d",\u{127}:"h",\u{131}:"i",\u{142}:"l",\u{f8}:"o",\u{153}:"oe",\u{df}:"ss",\u{fe}:"th"};function Kn(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(Tb,"").replace(vb,(s)=>Ab[s]??"").split(Cb).filter((s)=>s.length>0).slice(0,e).join("-");return Ob(r)}function Ob(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function Un(t,e){if(t.length===0)throw Error("uniqueId needs a non-empty base");let n=new Set(e);if(!n.has(t))return t;let r=2;while(n.has(`${t}-${r}`))r++;return`${t}-${r}`}var Lb=["constraint","decision"],Mb=6,Gb=10,Hb="knowledge",Fb=".md",Kb=4,Ub="\x00",Bb=",",Wb={"[":"]","{":"}"},Vb="\\",Jb=()=>new Date().toISOString();function _i(t,e,n){let r=Qt(t.text,`${e}.text`).trim(),s=et(r);if(s>n)throw new O(`${e}.text is ${s} bytes, but a knowledge entry holds at most ${n}`);return{kind:rt(Pe,t.kind,`${e}.kind`),scope:zr(t.scope,`${e}.scope`),text:r}}function Sd(t){return Pe.includes(t)}function qb(t,e){return{created:e.created,id:e.id,kind:t.kind,scope:[...t.scope],sources:[...e.sources],status:"active",supersededBy:null,supersedes:[...e.supersedes],text:t.text}}function Yb(t,e){let n=Kn(t.text,Mb),r=Un(n.length>0?n:t.kind,e);return e.add(r),r}function xs(t,e,n,r){for(;;){let s=qb(e,{...n,id:Yb(e,r)});try{return fs(t,s),s}catch(o){if(!oe(t).includes(s.id))throw o}}}function Ge(t,e){return{...t,status:"archived",supersededBy:e}}function He(t){return Lb.includes(t.kind)}function Ss(t){return t.slice(0,Gb)}function Es(t,e){let n=Rd(t,e.id),r=xd(bd(n),`.${jb(n)}.${process.pid}.${Rb()}.tmp`);Ib(bd(n),{recursive:!0});try{Db(r,ss(e)),Pb(r,n)}catch(s){throw Nb(r,{force:!0}),s}}function Xb(t){let e=new Map;for(let n of t){if(n.record.status!=="done")continue;for(let r of n.record.knowledgeUsed)e.set(r,(e.get(r)??0)+1)}return e}async function Ts(t){let e=await A(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return yt([...new Set(e.stdout.split(Ub).filter((n)=>n.length>0))])}function vs(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((s)=>e.some((o)=>s===o||K(s,[o])||K(o,[s])))||n.some((s)=>K(s,t)&&K(s,e))}function Ed(t){let e=[],n=[],r="";for(let s=0;s<t.length;s++){let o=t[s]??"";if(o===Vb){r+=t.slice(s,s+2),s++;continue}let i=Wb[o];if(i!==void 0)n.push(i);else if(o===n.at(-1))n.pop();if(o===Bb&&n.length===0){e.push(r.trim()),r="";continue}r+=o}return e.push(r.trim()),e.filter((s)=>s.length>0)}function zb(t,e,n={}){let r=Y(t),s=st("note","Shorten the text or fix the --kind and --scope values",()=>_i(e,"note",r.knowledge.maxEntryBytes)),i={created:Ss((n.clock??Jb)()),sources:[...n.sources??[]],supersedes:[]};return xs(t,s,i,new Set(oe(t)))}async function Td(t,e,n={}){Y(t);let r=it(await tt(t))?.task,s=r!==void 0&&Mt(t).includes(r)?[r]:[];return zb(t,e,{...n,sources:s})}function Pi(t,e={}){return Y(t),{entries:ie(t).filter((r)=>e.all===!0||r.status==="active")}}function vd(t,e,n={}){let{entries:r}=Pi(t,n),s=new Map(r.map((a)=>[a.id,a]));return{matches:ks(e,r.map((a)=>({id:a.id,text:a.text}))).flatMap(({id:a,score:c})=>{let l=s.get(a);return l===void 0||c<=0?[]:[{entry:l,score:Zb(c)}]}),query:e}}function Cd(t,e,n){return{entry:Od(t,e),uses:Xb(n).get(e)??0}}function Ad(t,e,n={}){let r=Od(t,e);if(r.status==="archived")throw new g(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(He(r)&&n.force!==!0)throw new g(`Knowledge entry "${e}" is a ${r.kind}; ${r.kind} entries are archived only on purpose`,`Run 'ari knowledge archive ${e} --force' if it no longer holds`);let s=Ge(r,null);return Es(t,s),s}function Od(t,e){if(Y(t),oe(t).includes(e))return rs(e,_b(Rd(t,e),"utf8"));throw new g(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function Rd(t,e){return xd(t,W,Hb,`${e}${Fb}`)}function Zb(t){let e=10**Kb;return Math.round(t*e)/e}var Qb=4,Rt=`
|
|
74
|
+
|
|
75
|
+
`,jd=`
|
|
76
|
+
`,tx=3,ex=/`+/g,nx=/^ {0,3}(?:```|~~~)/,rx=/\n+$/,sx=/\n/g,Ld=`
|
|
77
|
+
`,Li="none",Id={constraint:0,decision:1},Mi={contract:{title:"Contract",unit:"contract"},failure:{title:"Last failed attempt",unit:"failed attempt"},journal:{title:"Journal tail",unit:"journal event"},knowledge:{title:"Knowledge",unit:"knowledge entry"},notes:{title:"Task notes",unit:"task note"},rules:{title:"Constraints and decisions",unit:"constraint or decision entry"},task:{title:"Task",unit:"task header"}},ox=["failure","rules","notes","knowledge","journal"],ix=/y$/,ax=()=>new Date().toISOString();async function dn(t,e={}){let n=Y(t),r=await tt(t),s=e.id??cx(r),o=e.budget??n.context.budget,{task:i}=Q(t,s,n),a=ie(t).filter((f)=>f.status==="active"),c=(await Ts(t)).filter((f)=>K(f,i.contract.scope)),l=dx(t,i),u=px(i),d=[...mx(i.record.lastFailure),...fx(i,a,c),...gx(i.record.notes),...hx(i,a,c),...yx(bs(r,s,n.context.journalTail))],p=lx(s,o,l,u,d);if(i.record.status!=="done"){let f=(e.clock??ax)(),m={[an]:p.knowledge,tokens:p.estimatedTokens};Le(r,{at:f,detail:m,task:s,type:"context"})}return p}function cx(t){let e=it(t);if(e!==null)return e.task;throw new g("No task is active in this worktree","Pass a task id: ari context <id>")}function lx(t,e,n,r,s){let o=e*Qb,i=[n,Cs(r.fields,r.body)],a=_d(s,et(i.join(Rt)),Number.POSITIVE_INFINITY),c=et(Pd(i,a.sections,null))<=o,l=et(`${Rt}${Dd(e,Nd(s))}`),u=c?i:[n,ux(t,n,r,o-l)],d=u.join(Rt),p=c?a:_d(s,et(d)+l,o),f=Nd(p.omitted),m=Pd(u,p.sections,f.length===0?null:Dd(e,f)),h=[Ni("task",u[0]??"",1),Ni("contract",u[1]??"",1),...p.sections.map((y)=>Ni(y.name,Md(y),y.items.length))];return{budget:e,estimatedTokens:Ti(m),knowledge:p.sections.flatMap((y)=>y.knowledge),omitted:f,sections:h,sha256:$t(m),task:t,text:m}}function ux(t,e,{body:n,fields:r},s){let o=Cs(r,n);if(et([e,o].join(Rt))<=s)return o;let i=`_The contract body is shortened to fit the budget; read ${pt(t)}._`,a=s-et([e,Cs(r,i)].join(Rt))-Rt.length,c=[];for(let d of n.split(`
|
|
78
|
+
`)){if(a-=et(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>nx.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Cs(r,[u.join(`
|
|
79
|
+
`).trim(),i].filter((d)=>d.length>0).join(Rt))}function Cs(t,e){return e.length===0?t:`${t}${Rt}${e}`}function _d(t,e,n){let r=[],s=[],o=e;for(let i of t){let a=r.at(-1),c=a?.name===i.section,l=c?jd:`${Rt}${Gi(i.section)}${Rt}`,u=et(l)+et(i.text);if(o+u>n){s.push(i);continue}o+=u;let d=c&&a?a:{items:[],knowledge:[],name:i.section};if(d!==a)r.push(d);if(d.items.push(i.text),i.knowledgeId!==null)d.knowledge.push(i.knowledgeId)}return{omitted:s,sections:r}}function Pd(t,e,n){return[...[...t,...e.map(Md)],...n===null?[]:[n]].join(Rt)}function Md(t){return`${Gi(t.name)}${Rt}${t.items.join(jd)}`}function Gi(t){return`## ${Mi[t].title}`}function Ni(t,e,n){return{estimatedTokens:Ti(e),items:n,name:t,text:e,title:Mi[t].title}}function Nd(t){return ox.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function Dd(t,e){let n=e.map(({count:r,section:s})=>{let{unit:o}=Mi[s];return`${r} ${r===1?o:`${o.replace(ix,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function dx(t,e){let{contract:n,record:r}=e,s=De(n.pack,$e(t)),o=ae(e,s);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${s.name}`,`- Stage: ${o.name} (${r.stage+1} of ${s.stages.length})`,`- Instruction: ${be(on(o,n.id))}`,...r.question===null?[]:[`- Question: ${be(r.question)}`]].join(`
|
|
80
|
+
`)}function px(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Li:i.checks.join(", ");return`- ${i.id}: ${be(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${As(i.run)}`),s=e.invariants.map((i)=>`- ${As(i)}`),o=[Gi("contract"),"",`Scope: ${ji(e.scope)}`,`Lock: ${ji(e.lock)}`,...Di("Criteria:",n),...Di("Checks:",r),...Di("Invariants:",s)];return{body:e.body.trim(),fields:o.join(`
|
|
81
|
+
`)}}function Di(t,e){return e.length===0?[`${t} ${Li}`]:[t,...e]}function mx(t){if(t===null)return[];let e=t.gates.filter((r)=>!r.ok).flatMap((r)=>[`- ${r.gate}: ${be(r.summary)}`,...r.details.map((s)=>` - ${be(s)}`),...r.checks.filter((s)=>!s.ok&&s.outputTail.length>0).map((s)=>` ${s.name} output:${Ld}${be(kx(s.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...e].join(`
|
|
82
|
+
`)}]}function fx(t,e,n){return Gd(t,e,n).sort((r,s)=>(Id[r.kind]??0)-(Id[s.kind]??0)).map((r)=>Hd("rules",r))}function Gd(t,e,n){return e.filter((r)=>He(r)&&vs(r.scope,t.contract.scope,n))}function gx(t){return t.map((e,n)=>({index:n,note:e})).sort((e,n)=>N(n.note.at,e.note.at)||n.index-e.index).map(({note:e})=>({knowledgeId:null,section:"notes",text:`- ${e.at}: ${be(e.text)}`}))}function hx(t,e,n){let r=new Set(Gd(t,e,n).map((l)=>l.id)),s=e.filter((l)=>!r.has(l.id)),o=new Map(s.map((l)=>[l.id,l])),{contract:i}=t,a=[i.title,i.body,...i.criteria.map((l)=>l.text)].join(`
|
|
83
|
+
`);return ks(a,s.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=o.get(l);return u===void 0?[]:[Hd("knowledge",u)]})}function Hd(t,e){let n=e.scope.length===0?"":` (scope: ${ji(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${As(e.id)}${n}: ${be(e.text)}`}}function yx(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse(ot(e.detail)))}`}))}function ji(t){return t.length===0?Li:t.map(As).join(", ")}function As(t){let e="`".repeat(Fd(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function kx(t){let e="`".repeat(Math.max(tx,Fd(t)+1));return`${e}
|
|
84
|
+
${t.replace(rx,"")}
|
|
85
|
+
${e}`}function Fd(t){return Math.max(0,...[...t.matchAll(ex)].map((e)=>e[0].length))}function be(t){return t.replace(sx,Ld)}import{existsSync as wx,readFileSync as $x}from"fs";function Kd(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-Eo(t,e)/n}var bx=["fact","pattern","gotcha"],xx=3,Sx=["merges","promotions","archive"],Ex=["replace","entry"],Tx=["task","notes","entry"],vx=["kind","scope","text"],Os="Fix the proposal file, then run 'ari sleep --apply <file>' again",Cx=1,Ax=()=>new Date().toISOString();async function pn(t){let e=Y(t),n=await tt(t),{tasks:r}=Gt(t,e),s=[],o=r.map((u)=>{let{id:d}=u.contract;if(u.record.status!=="done"||bs(n,d,1).length===0)return u;let p=0,f=Ot(t,n,d,(m)=>{let h=m;for(let y of yd(n,d))h=Rx(h,y),p+=y.length;return h});return gs(n,d),s.push({events:p,task:d}),{contract:u.contract,record:f}}),i=new Map(ie(t).map((u)=>[u.id,u])),a=[...Ix(i,e),..._x(i,o,e),...Px(i,o,e)];for(let{id:u}of a){let d=i.get(u);if(d!==void 0)Es(t,d)}let c=Bn(i),l=await Ts(t);return{activeBytes:Wd(c),archived:a,candidates:{clusters:Dx(c,e),decisions:Lx(c,l),notes:jx(o)},maxBytes:e.knowledge.maxBytes,pruned:s}}function Ox(t,e){if(!wx(t))throw new g(`The proposal file ${t} does not exist`,Os);let n;try{n=JSON.parse($x(t,"utf8"))}catch(r){let s=r instanceof Error?r.message:String(r);throw new g(`The proposal file ${t} is not valid JSON (${s})`,Os)}return st("sleep proposal",Os,()=>Gx(n,e.knowledge.maxEntryBytes))}async function Bd(t,e,n={}){let r=Y(t),s=await tt(t),o=Ox(e,r),i=new Map(ie(t).map((m)=>[m.id,m])),{tasks:a}=Gt(t,r),c=new Map(a.map((m)=>[m.contract.id,m.record])),l=Hx(o,i,c,n.force===!0);if(l.length>0){let m=l.map((h)=>` - ${h}`).join(`
|
|
86
|
+
`);throw new g(`The sleep proposal has ${l.length} problem(s):
|
|
87
|
+
${m}`,Os)}let u=Ss((n.clock??Ax)()),d=new Set(oe(t)),p=[],f=[];for(let m of o.merges){let h=m.replace.map((b)=>i.get(b)).filter((b)=>b!==void 0),y=[...new Set(h.flatMap((b)=>b.sources))].sort(N),{id:x}=xs(t,m.entry,{created:u,sources:y,supersedes:[...m.replace]},d);p.push(...h.map((b)=>Ge(b,x))),f.push({id:x,kind:m.entry.kind,origin:"merge"})}for(let m of o.promotions){let h={created:u,sources:[m.task],supersedes:[]},{id:y}=xs(t,m.entry,h,d);f.push({id:y,kind:m.entry.kind,origin:"promotion"})}for(let m of o.archive){let h=i.get(m);if(h!==void 0)p.push(Ge(h,null))}for(let m of p)Es(t,m);for(let{notes:m,task:h}of o.promotions)Ot(t,s,h,(y)=>Eu(y,m));return{archived:p.map((m)=>({id:m.id,supersededBy:m.supersededBy})),created:f,promoted:o.promotions.map((m)=>({notes:[...m.notes],task:m.task}))}}function Rx(t,e){let n=e.flatMap((r)=>{let s=r.detail[an];return r.type==="context"&&Array.isArray(s)?s:[]});return cs(Su(t,n),e)}function Bn(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>N(e.id,n.id))}function Wd(t){return t.reduce((e,n)=>e+et(n.text),0)}function Vd(t,e){return N(t.created,e.created)||N(t.id,e.id)}function Ix(t,e){let n=[],r=[];for(let s of Bn(t).filter((o)=>!He(o)).sort(Vd)){let o=n.find((i)=>i.kind===s.kind&&Yd(i.text,s.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(o===void 0){n.push(s);continue}t.set(s.id,Ge(s,o.id)),r.push({id:s.id,reason:"duplicate",supersededBy:o.id})}return r}function _x(t,e,n){let r=qd(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let s=new Set(r.flatMap((i)=>Jd(i,t))),o=r.map((i)=>Ss(i.record.history[0]?.at??"")).sort(N)[0]??"";return Bn(t).flatMap((i)=>{if(!bx.includes(i.kind)||s.has(i.id))return[];if(N(i.created,o)>=0)return[];return t.set(i.id,Ge(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function Px(t,e,n){let r=new Map;for(let a of qd(e).flatMap((c)=>Jd(c,t)))r.set(a,(r.get(a)??0)+1);let s=Bn(t).filter((a)=>!He(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||Vd(a,c)),o=[],i=Wd(Bn(t));for(let a of s){if(i<=n.knowledge.maxBytes)break;t.set(a.id,Ge(a,null)),i-=et(a.text),o.push({id:a.id,reason:"budget",supersededBy:null})}return o}function Jd(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>Nx(n,e)))]}function Nx(t,e){let n=new Set([t]),r=t;for(;;){let s=e.get(r)?.supersededBy??null;if(s===null||n.has(s)||!e.has(s))return r;n.add(s),r=s}}function qd(t){let e=(n)=>n.record.history.findLast((r)=>r.type==="done")?.at??n.record.history.at(-1)?.at??"";return t.filter((n)=>n.record.status==="done").sort((n,r)=>N(e(r),e(n))||N(n.contract.id,r.contract.id))}function Yd(t,e,n){let r=ai(t),s=ai(e),o=Math.max(r.length,s.length);if(o>0&&Math.min(r.length,s.length)/o<n)return 0;return Kd(r,s)}function Dx(t,e){let n=new Map(t.map((i)=>[i.id,i.id])),r=new Map,s=(i)=>{let a=n.get(i)??i;return a===i?i:s(a)};t.forEach((i,a)=>{for(let c of t.slice(a+1)){let l=Yd(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[s(i.id),s(c.id)].sort(N);n.set(d,u),r.set(u,Math.max(r.get(u)??0,r.get(d)??0,l))}});let o=new Map;for(let i of t){let a=s(i.id);o.set(a,[...o.get(a)??[],i.id])}return[...o.entries()].filter(([,i])=>i.length>1).map(([i,a])=>({ids:a,similarity:Mx(r.get(i)??0)})).sort((i,a)=>N(i.ids[0]??"",a.ids[0]??""))}function jx(t){return t.filter((e)=>e.record.status==="done").flatMap((e)=>e.record.notes.flatMap((n,r)=>n.promoted?[]:[{at:n.at,note:r,task:e.contract.id,text:n.text}]))}function Lx(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,s)=>n.slice(s+1).filter((o)=>vs(r.scope,o.scope,e)).map((o)=>({ids:[r.id,o.id]})))}function Mx(t){let e=10**xx;return Math.round(t*e)/e}function Gx(t,e){let n=I(t,"proposal",Sx);return{archive:J(n.archive,[],(r)=>U(r,"archive",E)),merges:J(n.merges,[],(r)=>U(r,"merges",(s,o)=>{let i=I(s,o,Ex);return{entry:Ud(i.entry,`${o}.entry`,e),replace:ht(i.replace,`${o}.replace`,(a,c)=>U(a,c,E))}})),promotions:J(n.promotions,[],(r)=>U(r,"promotions",(s,o)=>{let i=I(s,o,Tx);return{entry:Ud(i.entry,`${o}.entry`,e),notes:ht(i.notes,`${o}.notes`,(a,c)=>U(a,c,At)),task:ht(i.task,`${o}.task`,E)}}))}}function Ud(t,e,n){let r=ht(t,e,(s,o)=>I(s,o,vx));return _i({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}function Hx(t,e,n,r){let s=[],o=new Map,i=(c,l)=>{let u=e.get(c),d=o.get(c);if(u===void 0)s.push(`${l} names the unknown entry "${c}"`);else if(u.status!=="active")s.push(`${l} names the archived entry "${c}"`);else if(He(u)&&!r)s.push(`${l} retires the ${u.kind} "${c}"; pass --force to retire ${u.kind} entries`);if(d!==void 0)s.push(`${l} names "${c}", which ${d} already retires`);o.set(c,l)};t.merges.forEach((c,l)=>{if(c.replace.length<Cx)s.push(`merges[${l}].replace is empty`);c.replace.forEach((u,d)=>{i(u,`merges[${l}].replace[${d}]`)})}),t.archive.forEach((c,l)=>{i(c,`archive[${l}]`)});let a=new Map;return t.promotions.forEach((c,l)=>{let u=`promotions[${l}]`,d=n.get(c.task);if(d===void 0){s.push(`${u}.task names the unknown or unreadable task "${c.task}"`);return}if(c.notes.length===0)s.push(`${u}.notes is empty`);let p=a.get(c.task)??new Set;for(let f of c.notes){let m=d.notes[f];if(m===void 0)s.push(`${u}.notes names note ${f}, but "${c.task}" has none`);else if(m.promoted)s.push(`${u}.notes names note ${f}, which is already promoted`);if(p.has(f))s.push(`${u}.notes names note ${f} of "${c.task}" twice`);p.add(f)}a.set(c.task,p)}),s}function Rs(t,e){let n=new Set,r=(s,o)=>{for(let i of e(s)){if(i===t)return[...o,t];if(n.has(i))continue;n.add(i);let a=r(i,[...o,i]);if(a)return a}return null};return r(t,[t])}function Is(t){return`depends forms a cycle: ${t.join(" -> ")}`}var Fx=["ari check","ari done"],Kx=["ari next"],Ux='ari new "<title>"',Xd=["active","blocked"];function Hi(t){let e=[...t.tasks].sort((u,d)=>N(u.contract.id,d.contract.id)),n=t.active?e.find((u)=>u.contract.id===t.active?.task):void 0;if(n?.record.status==="active")return Bx(n,t.packs);if(n?.record.status==="blocked")return Wx(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),o=r.filter((u)=>Xd.includes(u.record.status)).find((u)=>Ki(u,t.packs)===null);if(o)return Vx(o,t.packs);let i=Xx(r,t),a=Zx(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return qx(a,t.packs);let c=zx(e,r,t,i);if(c)return Jx(c);let l=e.find((u)=>u.record.status==="draft");if(l)return Yx(l);return{action:"new",commands:[Ux],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function Bx(t,e){let n=Fi(t,e);return{action:"continue",commands:[...Fx],instruction:on(n,t.contract.id),stage:n.name,task:t.contract.id}}function Wx(t,e){let n=t.record.question??"the task was blocked without a recorded question";return{action:"resolve",commands:[`ari resolve ${t.contract.id} --answer "<answer>"`],instruction:`A human must answer: ${n}`,stage:Fi(t,e).name,task:t.contract.id}}function Vx(t,e){return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Task "${t.contract.title}" is ${t.record.status}, but no worktree holds it; adopt it here.`,stage:Fi(t,e).name,task:t.contract.id}}function Jx(t){return{action:"fix",commands:[...Kx],instruction:t.instruction,stage:null,task:t.id}}function qx(t,e){let n=e.find((r)=>r.name===t.contract.pack)?.stages[0];return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Start "${t.contract.title}".`,stage:n?.name??null,task:t.contract.id}}function Yx(t){return{action:"ready",commands:[`ari ready ${t.contract.id}`],instruction:`Complete the contract of "${t.contract.title}", then mark it ready.`,stage:null,task:t.contract.id}}function Fi(t,e){let n=Ki(t,e);if(n!==null)throw new g(n.message,n.hint);let r=e.find((s)=>s.name===t.contract.pack)?.stages[t.record.stage];if(r)return r;throw Error(`Task "${t.contract.id}" has no stage ${t.record.stage}`)}function Ki(t,e){let n=e.find((r)=>r.name===t.contract.pack);if(!n)return{hint:"Fix the contract's pack",message:`Unknown pack "${t.contract.pack}" in task "${t.contract.id}"`};if(t.record.stage<n.stages.length)return null;return{hint:`Restore the stages of pack "${n.name}" in .ari/packs/${n.name}.yaml`,message:`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${n.name}" has ${n.stages.length}`}}function Xx(t,{packs:e,uncoveredLocks:n}){let s=t.filter((o)=>o.record.status==="ready").map((o)=>{let i=n.get(o.contract.id),a=i===void 0?[]:[`lock glob ${JSON.stringify(i)} matches no file that git tracks or would track`];return[o.contract.id,[...rn(o.contract,e),...a]]});return new Map(s.filter(([,o])=>o.length>0))}function zx(t,e,{invalid:n,packs:r},s){let o=new Map(t.map((p)=>[p.contract.id,p])),i=new Set(n.map((p)=>p.id)),a=(p)=>o.get(p)?.contract.depends??[],c=e.filter((p)=>p.record.status==="ready").flatMap((p)=>{let f=p.contract.id,m=p.contract.depends.find((y)=>!o.has(y)&&!i.has(y));if(m!==void 0)return[{id:f,instruction:`depends names the unknown task "${m}". Fix the depends of .ari/tasks/${f}.md`}];let h=Rs(f,a);return h?[{id:f,instruction:`${Is(h)}. Remove one of these dependencies`}]:[]}),l=[...s].map(([p,f])=>({id:p,instruction:`The contract can no longer start: ${f.join("; ")}. Fix .ari/tasks/${p}.md`})),u=e.filter((p)=>Xd.includes(p.record.status)).flatMap((p)=>{let f=Ki(p,r);return f===null?[]:[{id:p.contract.id,instruction:`${f.message}. ${f.hint}`}]});return[...n.map((p)=>({id:p.id,instruction:`${p.problem}. ${p.hint}`})),...u,...l,...c].sort((p,f)=>N(p.id,f.id))[0]}function Zx(t,e){let n=new Map(t.map((i)=>[i.contract.id,i])),r=new Map,s=(i,a)=>{let c=r.get(i);if(c!==void 0)return c;let l=n.get(i);if(!l||a.has(i))return 0;let u=new Set([...a,i]),d=Math.max(-1,...l.contract.depends.map((p)=>s(p,u)))+1;return r.set(i,d),d};for(let i of t)s(i.contract.id,new Set);let o=(i)=>i.contract.depends.every((a)=>n.get(a)?.record.status==="done");return e.filter((i)=>i.record.status==="ready"&&o(i)).sort((i,a)=>(r.get(i.contract.id)??0)-(r.get(a.contract.id)??0)||N(i.contract.id,a.contract.id))[0]}import{realpathSync as Qx}from"fs";import{resolve as tS}from"path";var eS="ENOENT";async function Ui(t){let e=zd(t),n=new Map;for(let r of await Jl(t)){if(zd(r)===e)continue;let s=nS(await tt(r));if(s!==null&&!n.has(s.task))n.set(s.task,r)}return n}function nS(t){try{return it(t)}catch(e){if(e instanceof g)return null;throw e}}function zd(t){try{return Qx(t)}catch(e){if(e.code===eS)return tS(t);throw e}}var rS=8,sS=6,oS=10,Zd=`
|
|
88
|
+
scope: []
|
|
89
|
+
`,iS="decision",Bi=10,tp={active:(t)=>`Finish it with 'ari done', or block it with 'ari block ${t} --reason <text>'`,blocked:(t)=>`A human answers it with 'ari resolve ${t} --answer <text>'`},aS=()=>new Date().toISOString();async function ep(t,e,n={}){let r=await St(t),s=e.trim(),o=Kn(s,rS);if(o.length===0)throw new g(`The title "${e}" has no letters or digits to build a task id from`,'Run ari new "<title>"');let i=De(n.pack??r.config.pack,r.projectPacks).name,a=[...n.scope??[]],c=a.find((p)=>Oe(p)!==null);if(c!==void 0)throw new g(`Scope glob ${JSON.stringify(c)} ${Oe(c)}`,"Pass globs relative to the root");let l=Un(o,Uu(t)),u=cS(au(s,i),a),d=li(l,Wt(n)());return Ku(t,r.state,d,u),{contractPath:pt(l),id:l,task:{contract:ns(l,u,r.config),record:d}}}async function np(t,e,n={}){let r=await St(t),{task:s}=Q(t,e,r.config),o=Wt(n)();ui(s.record,o);let i=[...rn(s.contract,r.packs),...gS(s.contract,t),...Ji(r,s.contract)];Wi(e,i,`Fix ${pt(e)}, then run 'ari ready ${e}'`);let a=Ot(t,r.state,e,(c)=>ui(c,o));return{contract:s.contract,record:a}}async function mn(t,e,n={}){let r=await St(t),{contractText:s,task:o}=Q(t,e,r.config),{contract:i}=o,a=Wt(n)();if(yS(r,e),await dS(r,e),Vi(o.record.status))return uS(r,o,a);let c=await Vr(t),l=await zt(t,i.lock),u=await Hn(t,r.config,i),d={contractHash:ee(s),gatesHash:Ns(r,i),lockHashes:l,stageTestHashes:u},p=(h)=>yu(h,c,d,a);p(o.record),Wi(e,rn(i,r.packs),`Fix ${pt(e)}, then start it again`),hS(r,i),await pS(t,e),dp(i,l);let f=Ot(t,r.state,e,p);bi(r.state,{since:a,task:e});let m={contract:i,record:f};return{...Ds(m,xe(r,i)),task:m}}async function rp(t,e={}){let n=await St(t),{contractText:r,task:s}=mp(n),o=xe(n,s.contract),i=ae(s,o),a=await Oi({config:n.config,pack:o,root:t,task:s}),c=a.every((d)=>d.ok);Le(n.state,gp("check",s,i,a,Wt(e)()));let l=ee(r)!==s.record.contractHash,u=Ns(n,s.contract)!==s.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:s}}async function sp(t,e={}){let n=await St(t),r=mp(n),{task:s}=r,{contract:o}=s;fp(n,r);let i=xe(n,o),a=ae(s,i),c=await Qe(t,[je]),l=await Oi({config:n.config,pack:i,root:t,task:s}),u=Wt(e)();Le(n.state,gp("done",s,a,l,u));let d=o.budget.attempts,p={budget:d,gates:l,stage:a.name},f=Vu(n.state,o.id),m=(T)=>Ot(t,n.state,o.id,(D)=>(wS(s.record,D),T({...D,knowledgeUsed:$S(D.knowledgeUsed,f)})));if(!l.every((T)=>T.ok)){let T=m((S)=>wu(S,{at:u,gates:l,stage:a.name,treeHash:c},d)),D=T.status==="blocked"?"blocked":"failed";return{...p,attempts:T.attempts,next:null,outcome:D,task:{contract:o,record:T}}}let h=await Hn(t,n.config,o),y={at:u,gates:l,stage:a.name,testHashes:h,treeHash:c},x=m((T)=>{let D=ku(T,y,i.stages.length,h);return D.status==="done"?cs(D,f):D}),b=x.status==="done",H={contract:o,record:x};if(b)return Wu(n.state),gs(n.state,o.id),{...p,attempts:x.attempts,next:null,outcome:"done",task:H};let M=Ds(H,i);return{...p,attempts:x.attempts,next:M,outcome:"advanced",task:H}}async function op(t,e,n,r={}){let s=await St(t),{contractText:o,task:i}=Q(t,e,s.config),{contract:a,record:c}=i,l=Vi(c.status);if(r.onto!==void 0&&!l)throw new g(`Task "${e}" is ${c.status}; only an active or blocked task has a base to move`,`Run 'ari amend ${e} --reason <text>' without --onto`);let u=await zt(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let x=[...rn(a,s.packs),...Ji(s,a)];Wi(e,x,`Fix ${pt(e)}, then run 'ari amend ${e}' again`)}if(l)mS(i,xe(s,a));let p=d?ae(i,xe(s,a)).name:null;if(l)dp(a,u);let f=l?await Hn(t,s.config,a):{...c.stageTestHashes},h={base:r.onto===void 0?null:await Vl(t,"HEAD",await Ze(t,r.onto)),contractHash:ee(o),gatesHash:Ns(s,a),lockHashes:u,reason:n,stage:p,stageTestHashes:f},y=Wt(r)();return di(c,h,y),{contract:a,record:Ot(t,s.state,e,(x)=>di(x,h,y))}}async function ip(t,e,n,r={}){let s=await St(t),{task:o}=Q(t,e,s.config),i=Wt(r)(),a=Ot(t,s.state,e,(c)=>$u(c,n,i));return{contract:o.contract,record:a}}async function ap(t,e,n,r={}){let s=await St(t),{task:o}=Q(t,e,s.config),i=Wt(r)();pi(o.record,n,i);let a=n.trim(),c=s.config.knowledge.maxEntryBytes,l=et(a);if(l>c)throw new g(`The answer is ${l} bytes, but a knowledge entry holds at most ${c}`,"Shorten the answer, or raise knowledge.maxEntryBytes in .ari/config.json");let u=Kn(a,sS),d=Un(u.length>0?u:iS,oe(t));fs(t,{created:i.slice(0,oS),id:d,kind:"decision",scope:[...o.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=Ot(t,s.state,e,(f)=>pi(f,n,i));return{knowledgeId:d,task:{contract:o.contract,record:p}}}async function cp(t,e,n,r={}){let s=await St(t),o=Q(t,e,s.config),{contract:i,record:a}=o.task,c=xe(s,i);if(a.status==="active")fp(s,o);let l=ae(o.task,c),u=await Ri(t,l,e),d=Wt(r)(),p=Ot(t,s.state,e,(f)=>(kS(a,f),bu(f,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function lp(t,e,n={}){let r=await St(t),s=n.task??pp(r),{task:o}=Q(t,s,r.config),i=Wt(n)(),a=Ot(t,r.state,s,(c)=>xu(c,e,i));return{contract:o.contract,record:a}}async function _s(t){let e=await St(t),n=it(e.state),r=n===null?null:lS(e,n.task);if(r!==null&&Vi(r.record.status))return Hi({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:s,tasks:o}=Gt(t,e.config),i=new Set((await Ui(t)).keys()),a=await fS(t,o);return Hi({active:n,claimed:i,invalid:s,packs:e.packs,tasks:o,uncoveredLocks:a})}async function Ps(t,e={}){let n=await St(t),r=Gt(t,n.config),{statuses:s}=e;if(s===void 0)return r;return{invalid:r.invalid,tasks:r.tasks.filter((o)=>s.includes(o.record.status))}}async function Fe(t,e){let n=await St(t),{task:r}=Q(t,e,n.config),o=r.record.status==="active"||r.record.status==="blocked"?Ds(r,xe(n,r.contract)):null;return{active:it(n.state)?.task===e,instruction:o?.instruction??null,stage:o?.stage??null,task:r}}async function St(t){let e=Y(t),n=$e(t);return{config:e,packs:Ne(n),projectPacks:n,root:t,state:await tt(t)}}function Wt(t){return t.clock??aS}function Ns(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:as(n,t.config)}function xe(t,e){return De(e.pack,t.projectPacks)}function Ds(t,e){let n=ae(t,e);return{instruction:on(n,t.contract.id),stage:n.name}}function cS(t,e){if(e.length===0)return t;if(!t.includes(Zd))throw Error("The contract template has no empty scope line");return t.replace(Zd,()=>`
|
|
90
|
+
scope: ${nn(e)}
|
|
91
|
+
`)}function Wi(t,e,n){if(e.length===0)return;let r=e.map((s)=>` - ${s}`).join(`
|
|
92
|
+
`);throw new g(`The contract of "${t}" has ${e.length} problem(s):
|
|
93
|
+
${r}`,n)}function Vi(t){return t==="active"||t==="blocked"}function lS(t,e){return Mt(t.root).includes(e)?Q(t.root,e,t.config).task:null}function uS(t,e,n){let r=e.contract.id;if(it(t.state)?.task!==r)bi(t.state,{since:n,task:r});return{...Ds(e,xe(t,e.contract)),task:e}}async function dS(t,e){let n=(await Ui(t.root)).get(e);if(n===void 0)return;throw new g(`Task "${e}" is already held by the worktree at ${n}`,"Continue it there, or run 'ari next' here for other work")}async function pS(t,e){let n=yt(await Ct(t,"HEAD"));if(n.length===0)return;let r=n.length-Bi,s=r>0?` and ${r} more`:"",o=(await qr(t)).filter((a)=>n.includes(a)),i=o.length===0?"":`; git hides ${o.slice(0,Bi).join(", ")} until you run 'git update-index --no-skip-worktree <path>' or 'git update-index --no-assume-unchanged <path>', so keep local settings in an ignored file instead`;throw new g(`Task "${e}" cannot start with uncommitted changes outside .ari: ${n.slice(0,Bi).join(", ")}${s}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function mS(t,e){let{evidence:n,id:r}=t.record,s=n.findIndex((i,a)=>i.stage!==e.stages[a]?.name),o=n[s];if(o===void 0)return;throw new g(`Task "${r}" passed stage "${o.stage}", which pack "${e.name}" does not have as stage ${s+1}`,"Keep the pack that the passed stages belong to, or create a follow-up with 'ari new'")}async function fS(t,e){let n=e.filter((o)=>o.record.status==="ready"&&o.contract.lock.length>0),r=n.flatMap((o)=>o.contract.lock),s=Object.keys(await zt(t,r));return new Map(n.flatMap((o)=>{let i=up(o.contract,s);return i===void 0?[]:[[o.contract.id,i]]}))}function up(t,e){return t.lock.find((n)=>!e.some((r)=>K(r,[n])))}function dp(t,e){let n=up(t,Object.keys(e));if(n===void 0)return;throw new g(`Lock glob ${JSON.stringify(n)} of task "${t.id}" matches no file that git tracks or would track`,`Fix the lock list in ${pt(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function Ji(t,e){let{tasks:n}=Gt(t.root,t.config),r=new Map(n.map((o)=>[o.contract.id,o.contract.depends]));r.set(e.id,e.depends.filter((o)=>o!==e.id));let s=Rs(e.id,(o)=>r.get(o)??[]);return s===null?[]:[Is(s)]}function gS(t,e){let n=new Set(Mt(e));return t.depends.filter((r)=>r.trim().length>0&&r!==t.id&&!n.has(r)).map((r)=>`depends names the unknown task "${r}"`)}function hS(t,e){let n=new Set(Mt(t.root)),r=e.depends.filter((o)=>!n.has(o)||Q(t.root,o,t.config).task.record.status!=="done");if(r.length===0)return;let s=Ji(t,e).map((o)=>`; ${o}`);throw new g(`Task "${e.id}" depends on unfinished tasks: ${r.join(", ")}${s.join("")}`,"Finish those tasks first; 'ari next' shows the order")}function yS(t,e){let n=it(t.state);if(n===null||n.task===e||!Mt(t.root).includes(n.task))return;let{status:r}=Q(t.root,n.task,t.config).task.record;if(r!=="active"&&r!=="blocked")return;throw new g(`Task "${n.task}" is already ${r} in this worktree; one task runs per worktree`,tp[r](n.task))}function pp(t){let e=it(t.state);if(e!==null)return e.task;throw new g("No task is active in this worktree","Run 'ari next' to see what to do")}function mp(t){let e=pp(t),n=Q(t.root,e,t.config),{question:r,status:s}=n.task.record;if(s==="active")return n;if(s==="blocked")throw new g(`Task "${e}" is blocked: ${r??"no question was recorded"}`,tp.blocked(e));throw new g(`Task "${e}" is ${s}, not active`,"Run 'ari next' to see what to do")}function fp(t,{contractText:e,task:n}){let{contract:r}=n;if(ee(e)!==n.record.contractHash)throw new g(`The contract of "${r.id}" changed after it was frozen`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`);if(Ns(t,r)!==n.record.gatesHash)throw new g(`The gates of "${r.id}" changed after they were frozen: its pack, or the test globs, regression setup or review command of .ari/config.json`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`)}function kS(t,e){if(t.stage===e.stage)return;throw new g(`Task "${e.id}" moved to another stage while its approval was recorded`,`Review the current stage, then run 'ari approve ${e.id}' again`)}function wS(t,e){if(ot(Qd(t))===ot(Qd(e)))return;throw new g(`Task "${e.id}" changed while its gates ran, so their result no longer applies`,"Run 'ari done' again; another ari command changed its status, stage, approvals, contract or frozen hashes")}function Qd(t){let{approvals:e,attempts:n,base:r,contractHash:s,gatesHash:o,lockHashes:i,stage:a,stageTestHashes:c,status:l}=t,u=t.evidence.length;return{approvals:e,attempts:n,base:r,contractHash:s,gatesHash:o,lockHashes:i,stage:a,stageTestHashes:c,stages:u,status:l}}function $S(t,e){let n=e.flatMap((r)=>{let s=r.detail[an];return r.type==="context"&&Array.isArray(s)?s:[]});return[...new Set([...t,...n])].sort(N)}function gp(t,e,n,r,s){let o=r.filter((i)=>!i.ok).map((i)=>i.gate);return{at:s,detail:{failing:o,ok:o.length===0,stage:n.name},task:e.contract.id,type:t}}var js="{prompt}",bS=2,xS=20,SS=`
|
|
94
|
+
|
|
95
|
+
`,ES=1,TS=5000,vS=["advanced","done","failed"];async function qi(t,e={}){let n=await sp(t,e),r=n.outcome==="done"?await pn(t):null;return{...n,sleep:r}}async function hp(t,e){let n=OS(t,e.agent),r=await RS(t,e),s=[],o=null;for(;;){let i=await _S(t,r,o),a=(await Fe(t,r)).task.record.history.length,c=await DS(e.agent,n,i,t,e.output??"inherit"),l=await CS(t,r,a)??await qi(t,{clock:e.clock}),u=l.gates.filter((d)=>!d.ok).map((d)=>d.gate);if(s.push({agentExitCode:c,failing:u,outcome:l.outcome,stage:l.stage}),l.outcome==="done"||l.outcome==="blocked")return{agent:e.agent,outcome:l.outcome,task:r,turns:s};o=l.outcome==="failed"?l:null}}async function CS(t,e,n){let r=await Fe(t,e),{contract:s,record:o}=r.task,i=o.history.slice(n).findLast((c)=>vS.includes(c.type)),a=AS(o.status,i?.type);if(a===null)return null;return{attempts:o.attempts,budget:s.budget.attempts,gates:i?.type==="failed"?o.lastFailure?.gates??[]:[],outcome:a,stage:i?.stage??r.stage??""}}function AS(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}function OS(t,e){let n=Y(t).agents[e];if(n===void 0)throw new g(`No agent "${e}" is configured`,`Add "agents": { "${e}": { "command": ["<binary>", "<non-interactive flag>", "{prompt}"] } } to .ari/config.json`);if(n.command.some((r)=>r.includes(js)))return n;throw new g(`The command of agent "${e}" has no ${js} argument`,`Put ${js} where the agent takes its prompt in agents.${e}.command`)}async function RS(t,e){if(e.task===void 0)return IS(t,e.clock);let n=await Fe(t,e.task),{question:r,status:s}=n.task.record,o=n.task.contract.id;switch(s){case"ready":return(await mn(t,o,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await mn(t,o,{clock:e.clock});return o;case"blocked":throw new g(`Task "${o}" is blocked: ${r??"no question was recorded"}`,yp(o));case"draft":throw new g(`Task "${o}" is a draft`,`Complete its contract, then run 'ari ready ${o}'`);case"done":throw new g(`Task "${o}" is already done`,"Run 'ari next' to see what to do")}}async function IS(t,e){let n=await _s(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await mn(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new g(`Task "${n.task}" is blocked`,yp(n.task));throw new g(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function yp(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function _S(t,e,n){let r=await Fe(t,e),s=(await dn(t,{id:e})).text,o=`Current stage: ${r.stage??"none"}. ${r.instruction??""}`.trim(),i=[`Work only inside the scope of task "${e}". Do not edit files under .ari/ other than the task contract.`,"When the stage's work is complete, stop. Ariadne then runs 'ari done' and sends you any failures."].join(`
|
|
96
|
+
`),a=n===null?[]:[PS(n)];return[s,o,...a,i].join(SS)}function PS(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>NS(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
|
|
97
|
+
`)}function NS(t){let e=t.details.slice(0,xS).map((r)=>` - ${r}`),n=t.checks.filter((r)=>!r.ok).map((r)=>` ${r.name} output:
|
|
98
|
+
${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}async function DS(t,e,n,r,s){let o=e.command.map((l)=>l.replaceAll(js,()=>n)),i;try{i=Bun.spawn(o,{cwd:r,detached:!0,stderr:"inherit",stdin:"ignore",stdout:s==="inherit"?"inherit":bS})}catch(l){throw new g(`Agent "${t}" could not start: ${o[0]??""}`,`Fix agents.${t}.command in .ari/config.json`,ES,{cause:l})}let a=ge(()=>jS(i)),c=await i.exited;if(vl())await new Promise(()=>{return});return a(),c}async function jS(t){Rn(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(TS)]),Rn(t.pid,"SIGKILL")}var LS=" ";async function _(){return Bl(process.cwd())}function Wn(t){if(t===void 0)return[];return t.split(",").map((e)=>e.trim()).filter((e)=>e.length>0)}function Se(t,e,n){if(t!==void 0&&t.trim().length>0)return t;throw new v(`${e} is required`,`Run ${n}`)}function Ls(t){return t.flatMap((e)=>MS(e)).join(`
|
|
99
|
+
`)}function Yi(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}function MS(t){let e=`${t.ok?"pass":"FAIL"} ${t.gate}: ${t.summary}`;if(t.ok)return[e];let n=t.details.map((s)=>` - ${s}`),r=t.checks.filter((s)=>!s.ok&&s.outputTail.length>0).flatMap((s)=>[` ${s.name} (${s.command}) output:`,...s.outputTail.trimEnd().split(`
|
|
100
|
+
`).map((o)=>`${LS}${o}`)]);return[e,...n,...r]}var Xi=1,kp=R({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await _s(await _()),GS)}}),wp=R({description:"Evaluate the active task's current stage without recording an attempt",examples:["ari check"],json:!0,name:"check",run:async(t)=>{let e=await rp(await _()),n={contractChanged:e.contractChanged,gates:e.gates,gatesChanged:e.gatesChanged,ok:e.ok,stage:e.stage,task:e.task.contract.id};return t.output.result(n,(r)=>{let s=r.ok?`Stage ${r.stage} passes`:`Stage ${r.stage} fails`,i=[...r.contractChanged?["contract"]:[],...r.gatesChanged?["gates (its pack, test globs, regression setup or review command)"]:[]].map((a)=>`The ${a} changed since it was frozen; run 'ari amend ${r.task} --reason <text>' before 'ari done'`);return[Ls(r.gates),`${s} for "${r.task}"`,...i].join(`
|
|
101
|
+
`)}),e.ok?void 0:Xi}}),$p=R({description:"Evaluate the current stage's gates, record evidence and advance",examples:["ari done","ari done --json"],json:!0,name:"done",run:async(t)=>{let e=await qi(await _()),n={attempts:e.attempts,budget:e.budget,gates:e.gates,next:e.next,outcome:e.outcome,sleep:e.sleep,stage:e.stage,task:e.task.contract.id};return t.output.result(n,HS),e.outcome==="done"||e.outcome==="advanced"?void 0:Xi}}),bp=R({args:L({staged:{default:!1,description:"Check only staged files (the pre-commit hook)",type:"boolean"}}),description:"Check that changed files lie inside the active task's scope",examples:["ari scope","ari scope --staged"],json:!0,name:"scope",run:async(t)=>{let e=await Qu(await _(),{staged:t.args.staged});return t.output.result(e,FS),e.ok?void 0:Xi}});function GS(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
|
|
102
|
+
`)}function HS(t){switch(t.outcome){case"done":return`Task "${t.task}" is done`;case"advanced":return`Stage ${t.stage} passed. Next stage ${t.next?.stage??""}: ${t.next?.instruction??""}`;case"failed":return[Ls(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
|
|
103
|
+
`);case"blocked":return[Ls(t.gates.filter((e)=>!e.ok)),`Task "${t.task}" is blocked: attempt budget exhausted; a human answers with 'ari resolve ${t.task} --answer <text>'`].join(`
|
|
104
|
+
`)}}function FS(t){if(t.task===null)return t.ok?"No active task; scope passes":`Scope fails: ${t.reason??""}`;if(t.ok){let e=Z(t.checked.length,"changed file lies","changed files lie");return`${t.checked.length} ${e} inside the scope of "${t.task}"`}return[`${t.reason??""}:`,...t.outside.map((e)=>` ${e}`)].join(`
|
|
105
|
+
`)}import{resolve as BS}from"path";var KS=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,US=/\r?\n/;function Vn(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function mt(t,e){let n=Vn(t,e);return typeof n==="string"?n:null}function Ms(t,e){return mt(t,"cwd")??e}function xp(t){return t.split(US).flatMap((e)=>KS.exec(e.trim())?.[1]?.trim()??[])}function Jn(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var zi=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],ce=new Set(["before-edit","before-shell"]);function Sp(t){return zi.includes(t)}var WS=30,VS=120,JS=new Set(["stop","pre-compact"]),qS=1000,YS="apply_patch",Ep="run_shell_command";function V(t,e,n=null){let r=JS.has(t)?VS:WS;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var Tp=[V("stop","Stop"),V("pre-compact","PreCompact","manual|auto"),V("session-start","SessionStart","startup|resume|clear|compact|fork")];function Qi(t){return{decision:"block",reason:t}}function Zi(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function vp(t,e,n){let r=Vn(e,"tool_input"),s=mt(r,"file_path")??mt(r,"notebook_path"),o=mt(r,"command"),i=mt(e,"tool_name"),a=i===Ep?mt(r,"dir_path"):null;return Jn(t,BS(Ms(e,n),a??""),{command:o,paths:s===null?[]:[s],tool:i})}function XS(t,e,n){let r=mt(e,"tool_name"),s=mt(Vn(e,"tool_input"),"command"),o=r===YS?{paths:xp(s??"")}:{command:s};return Jn(t,Ms(e,n),{...o,tool:r})}function zS(t,e,n){let r=mt(e,"cwd")??mt(Vn(e,"workspace_roots"),"0")??n,s=mt(e,"file_path");return Jn(t,r,{command:mt(e,"command"),paths:t==="after-tool"&&s!==null?[s]:[]})}function ZS(t,e,n){return Jn(t,Ms(e,n),{command:mt(QS(e),"command"),tool:mt(e,"toolName")})}function QS({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function ta({answers:t},e,n){let r=tE(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function tE(t,e,n){switch(n.kind){case"allow":return t.allow?.(e)??"";case"context":return t.context(n.text);case"ask":return(t.ask??t.deny)(n.reason);case"block":return t.block(n.reason);case"deny":return t.deny(n.reason)}}var eE={answers:{ask:Zi("ask"),block:Qi,context:(t)=>t,deny:Zi("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...ce.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:vp,registrations:[V("before-edit","PreToolUse","Edit|Write|NotebookEdit"),V("before-shell","PreToolUse","Bash|PowerShell|Monitor"),V("after-tool","PostToolUse","Edit|Write|NotebookEdit|Bash|PowerShell|Monitor"),...Tp],support:"verified"},nE={answers:{allow:(t)=>t==="stop"?{}:"",block:Qi,context:(t)=>t,deny:Zi("deny")},file:".codex/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,statusMessage:`ari ${e}`,timeout:n,type:"command"}),label:"Codex CLI",layout:"grouped",name:"codex",parse:XS,registrations:[V("before-edit","PreToolUse","^apply_patch$"),V("before-shell","PreToolUse","^Bash$"),V("after-tool","PostToolUse","^(Bash|apply_patch)$"),...Tp],support:"verified"},rE={answers:{block:(t)=>({decision:"deny",reason:t}),context:(t)=>({hookSpecificOutput:{additionalContext:t}}),deny:(t)=>({decision:"deny",reason:t})},file:".gemini/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,name:`ari-${e}`,timeout:n*qS,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:vp,registrations:[V("before-edit","BeforeTool","write_file|replace"),V("before-shell","BeforeTool",Ep),V("after-tool","AfterTool","write_file|replace|run_shell_command"),V("stop","AfterAgent","*"),V("pre-compact","PreCompress","*"),V("session-start","SessionStart","*")],support:"verified"},sE={answers:{allow:(t)=>ce.has(t)?{permission:"allow"}:{},block:(t)=>({followup_message:t}),context:(t)=>({additional_context:t}),deny:(t)=>({agent_message:t,permission:"deny",user_message:t})},file:".cursor/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...ce.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:zS,registrations:[V("before-shell","beforeShellExecution"),V("after-tool","afterFileEdit"),V("stop","stop"),V("pre-compact","preCompact"),V("session-start","sessionStart")],support:"partial"},oE={answers:{allow:(t)=>ce.has(t)?{permissionDecision:"allow"}:"",block:Qi,context:(t)=>({additionalContext:t}),deny:(t)=>({permissionDecision:"deny",permissionDecisionReason:t})},file:".github/hooks/ari.json",handler:(t,{matcher:e,timeoutSeconds:n})=>({bash:t,...e===null?{}:{matcher:e},powershell:t,timeoutSec:n,type:"command"}),label:"GitHub Copilot CLI",layout:"flat",name:"copilot",parse:ZS,registrations:[V("before-shell","preToolUse","bash|powershell"),V("stop","agentStop"),V("pre-compact","preCompact"),V("session-start","sessionStart")],support:"partial"},Gs=[eE,nE,rE,sE,oE];import{existsSync as Zn,readFileSync as Fp,rmSync as HE,statSync as FE}from"fs";import{join as Qn,relative as Kp}from"path";import{randomUUID as OE}from"crypto";import{chmodSync as RE,existsSync as ia,mkdirSync as IE,readFileSync as Mp,renameSync as _E,rmSync as PE,statSync as NE,writeFileSync as DE}from"fs";import{basename as jE,dirname as Lp,join as aa}from"path";import{isDeepStrictEqual as Ap}from"util";var iE=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,aE=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,cE=/[^\r\n]/g,lE=/(?:^|\n)([\t ]*)[^\n]*$/,uE=/^[\t ]*\r?\n/,dE=/^[\t ]+(?=\S)/m,pE=" ",qn=",";function ea(t){return t.replace(aE,(e)=>e.startsWith('"')?e:e.replace(cE," "))}function Op(t,e){let n=dE.exec(t)?.[0]??pE,r=t.includes(`\r
|
|
106
|
+
`)?`\r
|
|
107
|
+
`:`
|
|
108
|
+
`,s=(i,a)=>{let c=t.slice(i.start,i.end);if(Ap(i.value,a))return c;let l=r+(lE.exec(t.slice(0,i.start))?.[1]??""),u=(S,w)=>JSON.stringify(S,null,n).replaceAll(`
|
|
109
|
+
`,w);if(!Cp(i.value)||!Cp(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=mE(i,a),p=[],f="",m=i.start+1,h=(S)=>{let w=t.slice(m,S);return f+(f.length===0||uE.test(w)?"":r)+w};for(let S of i.entries){let w=h(S.start),j=d.get(S);if(f="",j!==void 0){let ct=s(S.node,a[j]);p.push(w+t.slice(S.start,S.node.start)+ct+t.slice(S.node.end,S.end))}else if(w.trim().length>0)f=w.trimEnd();m=t[S.end]===qn?S.end+1:S.end}let y=new Set(d.values()),x=l+n,b=Object.keys(a).filter((S)=>!y.has(S)).map((S)=>{let w=Array.isArray(a)?"":`${JSON.stringify(S)}: `;return x+w+u(a[S],x)}),H=h(i.end-1),M=H.trimEnd(),T=b.length===0?H.slice(M.length):l,D=p.length>0&&b.length>0?qn:"";return c[0]+p.join(qn)+D+M+b.join(qn)+T+c.at(-1)},o=fE(ea(t));return t.slice(0,o.start)+s(o,JSON.parse(JSON.stringify(e)))+t.slice(o.end)}function mE({entries:t},e){let n=Array.isArray(e)&&e.length<t.length,r=new Map;for(let s of t){let o=n?String(r.size):s.key;if((!n||Ap(s.node.value,e[o]))&&Object.hasOwn(e,o))r.set(s,o)}return r}function Cp(t){return typeof t==="object"&&t!==null}function fE(t){let e=[...t.matchAll(iE)],n=0,r=()=>{let o=e[n];if(o===void 0)throw Error("Unexpected end of JSON");return n+=1,o},s=()=>{let o=r(),i=o[0];if(i!=="{"&&i!=="[")return{end:o.index+i.length,entries:[],start:o.index,value:JSON.parse(i)};let a=i==="{"?"}":"]",c=[];while(e[n]!==void 0&&e[n]?.[0]!==a){let u=e[n]?.index??0,d=i==="{"?JSON.parse(r()[0]):String(c.length);if(i==="{")r();let p=s(),f=e[n]?.[0]===qn?r().index:p.end;c.push({end:f,key:d,node:p,start:u})}let l=r().index+1;return{end:l,entries:c,start:o.index,value:JSON.parse(t.slice(o.index,l))}};return s()}import{existsSync as Rp,readlinkSync as gE,realpathSync as hE,statSync as yE}from"fs";import{basename as kE,dirname as Yn,isAbsolute as wE,join as Hs,relative as $E,resolve as Ip,sep as bE}from"path";var _p=".git",xE="..",Fs=0,SE=1,Pp=128,EE=40,TE=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function Np(){let t=new Map,e=new Map,n=new Map,r=[],s=(c)=>na(t,c,()=>vE(c)),o=(c)=>na(e,c.root,async()=>{let l=await AE(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of Dp(c).filter((p)=>Rp(Hs(p,_p)))){let p=await s(d);if(p===null)continue;if(u!==null&&await CE(u,p))break;if(u=p,Rp(Hs(d,W)))l.push(await o(p))}return l},a=(c)=>{let l=jp(at(c));return na(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function at(t,e=EE){let n=sa(()=>hE(t));if(n!==null)return n;let r=Yn(t);if(r===t)return t;let s=Hs(at(r,e),kE(t)),o=e>0?ra(s):null;return o===null?s:at(Ip(Yn(s),o),e-1)}function ra(t){return sa(()=>gE(t))}function Ks(t){return sa(()=>yE(t).isDirectory())??!1}function Vt(t,e){let n=$E(t,e),r=n.split(bE);return r[0]===xE||wE(n)?null:r.join("/")}function sa(t){try{return t()}catch{return null}}function na(t,e,n){let r=t.get(e);if(r!==void 0)return r;let s=n();return t.set(e,s),s}function Dp(t){let e=Yn(t);return e===t?[t]:[t,...Dp(e)]}function jp(t){return Ks(t)||Yn(t)===t?t:jp(Yn(t))}async function vE(t){let e=await A(t,TE,{allowedExitCodes:[Fs,Pp]});if(e.exitCode!==Fs)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[Hs(t,_p)],root:t};let[n="",r="",s=""]=e.stdout.split(`
|
|
110
|
+
`);if(at(n)!==t)return null;let o=[r,Ip(t,s)].map((i)=>at(i));return{fault:null,gitDirectories:[...new Set(o)],root:t}}async function CE(t,e){if(t.fault===null&&t.gitDirectories.at(-1)===e.gitDirectories.at(-1))return!0;if(e.fault!==null)return!1;return(await A(e.root,["check-ignore","-q","--",t.root],{allowedExitCodes:[Fs,SE,Pp]})).exitCode===Fs}async function AE({fault:t,gitDirectories:e,root:n}){if(t!==null)return{fault:t,gitDirectories:e,root:n,workspace:null};try{return{fault:null,gitDirectories:e,root:n,workspace:await ys(n)}}catch(r){if(!(r instanceof g))throw r;return{fault:oa(r),gitDirectories:e,root:n,workspace:null}}}function oa({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var LE=2;function fn(t,e){let n=le(t,e);return n===null?null:ME(e,n)}function le(t,e){let n=aa(t,e);return ia(n)?Mp(n,"utf8"):null}function ME(t,e){let n;try{n=JSON.parse(ea(e))}catch(r){let s=r instanceof Error?r.message:String(r);throw new g(`${t} is not valid JSON (${s})`,`Fix ${t}, then run the command again`)}if(ue(n))return n;throw new g(`${t} does not hold a JSON object`,`Fix ${t}, then run the command again`)}function Us(t,e,n){if(!ia(t))return n;try{return e(JSON.parse(Mp(t,"utf8")))}catch{return n}}function Xn(t,e,n){let r=le(t,e);return zn(t,e,r===null?`${JSON.stringify(n,null,LE)}
|
|
111
|
+
`:Op(r,n))}function zn(t,e,n){let r=aa(t,e),s=le(t,e);if(s===n)return"unchanged";return Ke(r,n,GE(r)),s===null?"created":"updated"}function Ke(t,e,n){let r=at(t);IE(Lp(r),{recursive:!0});let s=aa(Lp(r),`.${jE(r)}.${process.pid}.${OE()}.tmp`);try{if(DE(s,e),n!==void 0)RE(s,n);_E(s,r)}finally{PE(s,{force:!0})}}function GE(t){return ia(t)?NE(t).mode:void 0}function ue(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Up="# ari:managed",KE=493,UE=64,BE=1,Gp=0,gn=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],WE=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),Hp=".husky",VE=/\.ya?ml$/,Bp=gn.map((t)=>t.name);async function Wp(t){let e=await Re(t,"hooks");return gn.every(({name:n})=>{let r=Qn(e,n);return ca(r)&&qp(r)})}async function Vp(t){let e=await qE(t);if(e!==null)throw new g(`This repository manages git hooks with ${e.name}; ari will not write hooks beside it`,e.hint);let n=await Re(t,"hooks"),r=gn.map((i)=>({hook:i,path:Qn(n,i.name),script:JE(i)})),s=r.filter(({path:i})=>Zn(i)&&!ca(i));if(s.length>0){let i=s.map(({hook:a})=>a.name).join(", ");throw new g(`Unmanaged git hooks already exist: ${i}`,Bs(""))}return{agent:"git",files:r.map(({hook:i,path:a,script:c})=>{let l=Kp(t,a),u=Zn(a);if(u&&Fp(a,"utf8")===c&&qp(a))return{action:"unchanged",hook:i.name,path:l};return Ke(a,c,KE),{action:u?"updated":"created",hook:i.name,path:l}})}}async function Jp(t){let e=await Re(t,"hooks");return{agent:"git",files:gn.map(({name:r})=>{let s=Qn(e,r),o=ca(s);if(o)HE(s);return{action:o?"removed":"unchanged",hook:r,path:Kp(t,s)}})}}function ca(t){return Zn(t)&&Fp(t,"utf8").includes(Up)}function qp(t){return(FE(t).mode&UE)!==0}function JE(t){return["#!/bin/sh",Up,"if ! command -v ari >/dev/null 2>&1; then",` echo "ari is not on PATH; install @r5n/ariadne or remove .git/hooks/${t.name}" >&2`," exit 1","fi",`exec ${t.command}`,""].join(`
|
|
112
|
+
`)}async function qE(t){let e=await A(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Gp,BE]}),n=e.stdout.trim();if(e.exitCode===Gp&&n.length>0)return{hint:Bs(`${n}/`),name:`core.hooksPath (${n})`};let r=WE.find((s)=>Zn(Qn(t,s)));if(r!==void 0)return{hint:YE(r),name:`lefthook (${r})`};if(Zn(Qn(t,Hp)))return{hint:Bs(`${Hp}/`),name:"husky"};return null}function Bs(t){return`Add the lines yourself: ${gn.map((e)=>`${t}${e.name}: ${e.command}`).join("; ")}`}function YE(t){if(!VE.test(t))return Bs("lefthook ");let e=gn.map((n)=>`${n.name}:
|
|
113
|
+
commands:
|
|
114
|
+
ari-${n.name}:
|
|
115
|
+
run: ${n.command}`).join(`
|
|
116
|
+
`);return`Add to ${t}:
|
|
117
|
+
${e}`}import{realpathSync as ZE,rmSync as QE}from"fs";import{join as tT}from"path";import{join as Yp}from"path";var Xp="hooks.json",XE=384,zE=ul(Kr({installed:Xt(),original:Xt().or(Fr())}));function la(t,e){return zp(t)[e]??null}function ua(t,e,n){let{[e]:r,...s}=zp(t);if(n===null&&r===void 0)return;let o=n===null?s:{...s,[e]:n};Ke(Yp(t,Xp),`${JSON.stringify(o)}
|
|
118
|
+
`,XE)}function zp(t){return Us(Yp(t,Xp),zE,{})}var eT="ari hook",nT=1;function da(t,e){return`${eT} ${t} ${e}`}function tm(t,e,n){let{file:r,name:s,registrations:o}=e,i=le(t,r),a=fn(t,r)??{},c=la(n,r),l=nm(a,e)?void 0:i,u=c?.installed===i?c?.original:l,d=Xn(t,r,rm(a,e,o)),p=le(t,r)??"";return ua(n,r,u===void 0?null:{installed:p,original:u}),{action:d,agent:s,events:tr(e),file:r}}function em(t,e,n){let{file:r,name:s}=e;return{action:pa(t,e)?rT(t,e,n):"unchanged",agent:s,file:r}}function rT(t,e,n){let{file:r}=e,s=la(n,r);if(ua(n,r,null),s===null||s.installed!==le(t,r)){let o=fn(t,r)??{};return Xn(t,r,rm(o,e,[]))}if(s.original!==null)return zn(t,r,s.original);return QE(ZE(tT(t,r))),"removed"}function pa(t,e){let n=fn(t,e.file);return n!==null&&nm(n,e)}function tr(t){return[...new Set(t.registrations.map((e)=>e.event))]}function nm({hooks:t},e){if(!ue(t))return!1;return Object.values(t).flat().some((n)=>sm(n,e).length>0)}function rm({hooks:t={},...e},n,r){if(!ue(t))throw Zp(n,'"hooks" value that is not an object');let o=[...new Set([...Object.keys(t),...r.map(({agentEvent:a})=>a)])].flatMap((a)=>{let c=t[a]??[];if(!Array.isArray(c))throw Zp(n,`hooks.${a} that is not a list`);let l=sT(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??nT}:{};return{...e,...i,...o.length===0?{}:{hooks:Object.fromEntries(o)}}}function Zp({file:t},e){return new g(`${t} has a ${e}`,`Fix ${t}`)}function sT(t,e,n){let r=new Set(n);return[...t.flatMap((o)=>{let i=sm(o,e),a=[...r].filter(({event:c})=>i.includes(da(e.name,c)));for(let c of a)r.delete(c);return[...oT(o,e),...a.map((c)=>Qp(e,c))]}),...[...r].map((o)=>Qp(e,o))]}function Qp(t,e){let n=t.handler(da(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function oT(t,e){let n=om(t,e),r=n.filter((s)=>im(s,e).length===0);if(r.length===n.length)return[t];return r.length>0&&ue(t)?[{...t,hooks:r}]:[]}function sm(t,e){return om(t,e).flatMap((n)=>im(n,e))}function om(t,{layout:e}){if(e==="flat")return[t];return ue(t)&&Array.isArray(t.hooks)?t.hooks:[]}function im(t,{name:e}){let n=ue(t)?Object.values(t):[],r=da(e,"");return n.filter((s)=>typeof s==="string"&&s.startsWith(r))}import{join as Rv,resolve as Em}from"path";import{resolve as bm}from"path";var am=new RegExp([/\\\n/,/\\(?<escaped>[\s\S])/,/(?<![^ \t\r\n;&|()])#[^\n]*/,/'(?<single>[^']*)'?/,/"(?<double>(?:[^"\\$]+|\\[\s\S]|\$\(cat <<-?[ \t]*["']?(?<mark>\w+)[^\n]*\n[\s\S]*?\n[ \t]*\k<mark>\n\s*\)|\$)*)"?/,/\(\((?<arithmetic>(?:[^()\n]|\([^()\n]*\))*)\)\)/,/<<(?!<)(?<tabs>-?)[ \t]*(?<delimiter>(?:'[^'\n]*'|"[^"\n]*"|\\.|[^ \t\r\n'"\\`;&|()<>])+)/,/(?:(?<![^ \t\r\n;&|()<>])\d+)?[<>]&[ \t]*(?:\d+-?|-)(?![^ \t\r\n;&|()<>])/,/(?<output>(?:&|(?<![^ \t\r\n;&|()<>])\d+)?>(?!\()[>|&]?)/,/(?<input><<<|(?:(?<![^ \t\r\n;&|()<>])\d+)?<(?!\()>?)/,/(?<separator>&&|\|\||\|&|;;|[<>]?\(|[;&|)\n`])/,/(?<blank>[ \t\r]+)/,/(?<plain>[^ \t\r\n'"\\`;&|()<>#]+|[\s\S])/].map(({source:t})=>t).join("|"),"y"),iT=/[ \t\r\n]/,aT=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,cT=/\\[\s\S]/g,lT=/\\([$`"\\\n])/g,uT=/[$`]/,dT=/[$*?[]|\{./;var pT=/['"\\]/g,mT=/^\t+/;var fT=/[(`]/,gT=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function ma(t){let e=[],n=[],r=cm(""),s="words",o=null,i=0,a=(u,d)=>{o=(o??"")+u,r.literal&&=d},c=(u="words")=>{if(o!==null)r[s].push(o);o=null,s=u},l=(u)=>{if(c(),r.literal&&=!fT.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=cm(u)};while(i<t.length){am.lastIndex=i;let u=am.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:f,double:m,escaped:h,input:y,output:x,plain:b,separator:H,single:M,tabs:T}=u.groups??{};if(i+=u[0].length,h!==void 0)a(h,!0);else if(M!==void 0)a(M,!0);else if(m!==void 0)a(yT(m),hT(m));else if(d!==void 0)a(d,!1);else if(b!==void 0)a(b,!dT.test(b)&&(o!==null||!b.startsWith("~")));else if(p!==void 0&&o!==null)c();else if(x!==void 0)c("outputs");else if(y!==void 0)c("inputs");else if(f!==void 0)c(),n.push({delimiter:f.replace(pT,""),tabs:T!==""});else if(H!==void 0){if(H===`
|
|
119
|
+
`)for(let D of n.splice(0)){let{body:S,end:w}=kT(t,i,D);r.inputs.push(S),i=w}l(H)}}return l(""),e}function fa(t){return ma(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>iT.test(n)).flatMap(fa)])}function Ws(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n]??"";if(!r.startsWith("-"))return{args:t.slice(n+1),directories:e,subcommand:r};if(gT.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Ue(t){return t.slice(t.lastIndexOf("/")+1)}function cm(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function hT(t){return!uT.test(t.replace(aT,"").replace(cT,""))}function yT(t){return t.replace(lT,(e,n)=>n===`
|
|
120
|
+
`?"":n)}function kT(t,e,{delimiter:n,tabs:r}){for(let s=e;s<t.length;){let o=t.indexOf(`
|
|
121
|
+
`,s),i=o===-1?t.length:o,a=t.slice(s,i);if((r?a.replace(mT,""):a)===n)return{body:t.slice(e,s),end:i};s=i+1}return{body:t.slice(e),end:t.length}}import{basename as wT,isAbsolute as $T,join as bT,resolve as Js}from"path";var xT=/^[A-Za-z_]\w*\+?=/,ST=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),ET=new Map([["mkdir",["created","m mode"]],["rm",["removed",""]],["rmdir",["removed",""]],["tee",["written",""]],["touch",["written","A d r t date reference"]],["truncate",["written","r s reference size"]]]),TT=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),vT=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),CT=new Set(["cd","popd","pushd"]),lm=new Set(["","&&",";",`
|
|
122
|
+
`]),AT="S suffix",OT=/^(?:-[a-z0-9E]*i|--in-place)/,RT=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,IT="e f l expression file line-length",_T=/^-[a-zA-Z0-9]*[eE]/,PT="e E",NT=/^-\w+$/,DT=/^\.\w+$/,jT=/^(?:-[a-zA-Z]*t$|--target-directory)/,LT=/^(?:--staged|-[A-Za-z]*S)/,MT=/^(?:--worktree|-[A-Za-z]*W)/,um="of=",ha="--",ga=".";function pm(t,e){let n=e,r=e,s=!0,o=t.map((i,a)=>{let c=HT(i,n),[l="",u="-",...d]=qs(i);if(!CT.has(l))return s=!1,c;return s&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,s&&=lm.has(i.before)&&lm.has(t[a+1]?.before??""),r=s?Js(r,u):r,n=s?r:null,c});return{directory:r,steps:o}}function qs({words:t}){let e=t.findIndex((n)=>!xT.test(n)&&!ST.has(n));return e===-1?[]:[Ue(t[e]??""),...t.slice(e+1)]}function Ys(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(ha),s=[],o=r===-1?t:t.slice(0,r);for(let i=0;i<o.length;i+=1){let a=o[i]??"";if(!a.startsWith("-"))s.push(a);else if(n.has(GT(a)))i+=1}return[...s,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function GT(t){if(t.startsWith("--"))return t.slice(2);return NT.test(t)?t.slice(-1):""}function HT(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=qs(t),s=n==="git"?Ws(r):null,o=e===null?null:Js(e,...s?.directories??[]),i=s===null?mm(n,r,e):FT(s.subcommand,s.args,o),a=[...Vs(e,"file",t.outputs),...Vs(o,"file",i?.written),...Vs(o,"directory",i?.created),...Vs(o,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function Vs(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!$T(r))return null;let s=Js(t??r,r),o=e!=="removed"&&Ks(s);if(o&&e==="directory")return[];return{kind:o?"directory":e,path:s}})}function mm(t,e,n){let[r,s]=ET.get(t)??[];if(r!==void 0)return{[r]:Ys(e,s)};switch(t){case"dd":return{written:e.filter((o)=>o.startsWith(um)).map((o)=>o.slice(um.length))};case"cp":case"ln":case"mv":return KT(t,e,n);case"sed":return{written:dm(e,IT,RT)??[]};case"perl":{let o=dm(e,PT,_T);return o===null?null:{written:o}}default:return TT.has(t)?{}:null}}function FT(t,e,n){switch(t){case"checkout":return e.includes(ha)?{removed:e.slice(e.indexOf(ha)+1)}:null;case"restore":return e.some((s)=>LT.test(s))&&!e.some((s)=>MT.test(s))?{}:{removed:Ys(e,"s source pathspec-from-file")};case"rm":case"mv":return mm(t,e,n);default:return vT.has(t)?{}:null}}function KT(t,e,n){if(e.some((a)=>jT.test(a)))return null;let r=Ys(e,AT),[s=ga,o]=r.length<2?[ga,r]:[r.at(-1),r.slice(0,-1)],i=s.endsWith("/")||Ks(Js(n??ga,s));return{removed:t==="mv"?o:[],written:i?o.map((a)=>bT(s,wT(a))):[s]}}function dm(t,e,n){if(!t.some((o)=>OT.test(o)))return null;let r=Ys(t,e),s=r.length>1&&DT.test(r[0]??"")?r.slice(1):r;return t.some((o)=>n.test(o))?s:s.slice(1)}import{basename as fm,dirname as UT,join as gm}from"path";var BT=[`${W}/tasks/*.md`,`${W}/designs/**`],WT="x",VT=/\*\*.*/,JT=".git",qT=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],YT="; pass the paths to change instead of their directory",XT="\x00",Xs=0,zT=1,hm=128;async function ym(t,e){let n=at(e),r=await t.governing(n),s=$m(t.opened(),n);if(s!==null)return s;return r.flatMap((i)=>{let a=Vt(i.root,n);return a===null||a.length===0?[]:er(i,a)??[]})[0]??null}async function km(t,e){let n=[],r=new Map;for(let{kind:s,path:o}of e){let a=s==="removed"&&ra(o)!==null?gm(at(UT(o)),fm(o)):at(o),c=await t.governing(a),l=$m(t.opened(),a);if(l!==null)n.push(l);let u=s==="removed"?t.opened().filter(({root:d})=>Vt(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:Vt(d.root,a)??"",kind:s}])}}for(let[s,o]of r)n.push(...await ZT(s,o));return n}async function ZT(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await nv(t,n),s=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=er(t,u);return d===null?[]:`${d}${u===a?"":YT}`}).slice(0,1)),o=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?er(t,a):QT(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:wm(t,a)!==null,name:u,reason:l}]}),i=await rv(t.root,o.filter(({guarded:a})=>!a).map(({name:a})=>a));return[...s,...o.filter(({name:a})=>!i.has(a)).map(({reason:a})=>a)]}function wm(t,e){if(cn(e)&&!K(e,BT))return`${e} is written only by ari; use ari commands instead of editing it`;let n=t.workspace?.task??null;if(n===null)return null;return Object.hasOwn(n.record.lockHashes,e)||K(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function er(t,e,n=K){let r=wm(t,e);if(r!==null||cn(e))return r;let s=t.fault??t.workspace?.drift??null;if(s!==null)return`ari cannot check ${e}: ${s}`;let o=t.workspace?.task??null;if(o===null||n(e,o.contract.scope))return null;let{id:i,scope:a}=o.contract;return`${e} is outside the scope of task "${i}" (${a.join(", ")}); change the scope with a contract edit and 'ari amend ${i} --reason <text>', or ask a human`}function QT(t,e){return er(t,`${e}/${WT}`)===null?null:er(t,e,tv)}function tv(t,e){let n=t.split("/").length,r=e.map((s)=>s.replace(VT,"**").split("/").slice(0,n).join("/"));return K(t,r)}function $m(t,e){return t.some(({gitDirectories:r,root:s})=>Vt(gm(s,JT),e)===""||r.some((o)=>ev(o,e)))?`${fm(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function ev(t,e){let n=Vt(t,e);return n!==null&&qT.some((r)=>r.test(n))}async function nv({root:t,workspace:e},n){let r=await A(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((o)=>o.length===0?".":o)],{allowedExitCodes:[Xs,hm]}),s=r.exitCode===Xs?Zt(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),W,...s]}async function rv(t,e){if(e.length===0)return new Set;let n=await A(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[Xs,zT,hm],stdin:[...new Set(e)].join(XT)});return new Set(n.exitCode===Xs?Zt(n.stdout):[])}var sv="'ari approve' records a human approval; ask a person to run it, and pass text that contains these words in a file, as in 'git commit -F <file>'",ov="'git commit --no-verify' skips ari's pre-commit scope check; commit without --no-verify, -n or core.hooksPath, and fix what the check reports",iv="run it as a plain command with literal paths, or ask a person to run it",av=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,cv="approve",lv="git",uv="commit",dv="config",pv=/^core\.hookspath$/i,mv=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,fv=/^(?:--)?unset/,gv=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,hv=/(?<![\w-])\.ari(?![\w.-])/,ya=/[\s'"`;&|()<>=,]+/,yv=[[/^(?:cp|dd|eval|ln|mkdir|mv|rm|rmdir|tee|touch|truncate|xargs)$/,null],[/^find$/,/^-(?:delete|exec(?:dir)?|ok(?:dir)?)$/],[/^git$/,/^(?:checkout|restore)$/],[/^sed$/,/^(?:-[a-zA-Z]*i|--in-place)/]],kv=/^(?:ba|da|fi|k|z)?sh$/,wv=/^-[a-z]*c$/,$v=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,bv=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function xm(t,e,n){let{directory:r,steps:s}=pm(ma(e),n),o=[...new Set([...await t.governing(n),...await t.governing(r)])],i=xv(fa(e));if(i!==null&&(o.length>0||await Sv(t,e,n)))return{kind:"deny",reason:i};let a=await km(t,s.flatMap(({targets:d})=>d));if(a.length>0)return{kind:"deny",reason:[...new Set(a)].join("; ")};let c=s.filter(({resolved:d})=>!d).flatMap((d)=>Cv(d)??[])[0],l=o.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:Ov(l,e,[n,r]);if(u===null)return{kind:"allow"};return{kind:"ask",reason:`the command mentions ${u}, which ari protects, and ari does not resolve what its '${c}' writes; ${iv}`}}function xv(t){if(t.some(Ev))return sv;return t.some(Tv)?ov:null}async function Sv(t,e,n){for(let r of new Set(e.split(ya)))if((await t.governing(bm(n,r))).length>0)return!0;return!1}function Ev({words:t}){return t.some((e,n)=>av.test(e)&&t.slice(n+1).find((r)=>!r.startsWith("-"))===cv)}function Tv({words:t}){if(t.some((e)=>mv.test(e)))return!0;return t.some((e,n)=>{let r=Ue(e)===lv?Ws(t.slice(n+1)):null;if(r?.subcommand===dv)return vv(r.args);return r?.subcommand===uv&&r.args.some((s)=>gv.test(s))})}function vv(t){let e=t.findIndex((n)=>pv.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>fv.test(n)))}function Cv({command:t}){let[e]=qs(t),n=t.words.flatMap((s)=>s.split(ya)).filter((s)=>s.length>0);return n.map(Ue).find((s,o)=>Av(s,e,n,o+1))??(!t.literal&&t.outputs.length>0?">":null)}function Av(t,e,n,r){let s=yv.find(([c])=>c.test(t))?.[1];if(s===null)return!0;if(s!==void 0)return n.slice(r).some((c)=>s.test(c));let o=kv.test(t);if(!o&&!$v.test(t))return!1;let i=n.slice(r),a=i.findIndex((c)=>!c.startsWith("-"));if(a===-1&&t===e)return!0;return o?i.some((c)=>wv.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>bv.test(c))}function Ov(t,e,n){if(t.length>0&&hv.test(e))return W;let r=new Set(e.split(ya));for(let{root:s,workspace:o}of t){let i=Object.keys(o?.task?.record.lockHashes??{}),a=new Set(i.map(Ue));for(let c of[...r].filter((l)=>a.has(Ue(l)))){let u=[s,...n].map((d)=>Vt(s,at(bm(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var Iv="stop.json",_v=500,Pv=20000,It={kind:"allow"},Nv={decision:{kind:"ask",reason:"ari could not check this in time; write a simpler command, or ask a person to run it"},expired:!0,warning:"ari hook ran out of time"},Dv=Kr({task:Xt(),tree:Xt()});async function Tm(t){let e=Np();if(ce.has(t.event))return jv(Lv(e,t));let n=await e.at(t.cwd);if(n===null)return zs(It);if(n.workspace===null)return Sm(t,n.fault??"");try{return zs(await Gv(t,n.workspace))}catch(r){if(!(r instanceof g))throw r;return Sm(t,oa(r))}}function Sm({event:t},e){return{...zs(It),warning:`ari hook skipped ${t}: ${e}`}}async function jv(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,Pv,Nv);try{return await Promise.race([e.promise,t.then(zs)])}finally{clearTimeout(n)}}function zs(t){return{decision:t,expired:!1,warning:null}}async function Lv(t,e){let{command:n,cwd:r,event:s,paths:o}=e,i=await t.at(r);if(s==="before-shell"&&n!==null)return xm(t,n,r);if(s==="before-edit"&&o.length>0)return Mv(t,e);if(i===null)return It;return{kind:"ask",reason:`ari found no ${s==="before-edit"?"path":"command"} in the hook payload`}}async function Mv(t,e){let n=[];for(let r of e.paths){let s=await ym(t,Em(e.cwd,r));if(s!==null)n.push(s)}return n.length===0?It:{kind:"deny",reason:n.join("; ")}}async function Gv(t,e){switch(t.event){case"before-edit":case"before-shell":return It;case"after-tool":return Zs(e,Hv(t,e)),It;case"stop":return Fv(e);case"pre-compact":return Zs(e,{detail:{},type:"compact"}),await pn(e.root),It;case"session-start":return Kv(e)}}function Hv(t,e){let n=at(e.root),r=t.paths.flatMap((s)=>Vt(n,at(Em(t.cwd,s)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,_v)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function Fv(t){let{task:e}=t;if(e===null||e.record.status!=="active")return It;let n=e.contract.id,r=await Qe(t.root,[je]);if(e.record.evidence.at(-1)?.treeHash===r)return It;let s=Rv(t.state,Iv),o=Us(s,Dv,null);if(o?.task===n&&o.tree===r)return It;return Ke(s,`${JSON.stringify({task:n,tree:r})}
|
|
123
|
+
`),Zs(t,{detail:{blocked:!0},type:"stop"}),{kind:"block",reason:`Task "${n}" has changes that no gate has passed yet. Run 'ari check', fix what it reports, then 'ari done'. If you are stuck, run 'ari block ${n} --reason <question>' for a human.`}}async function Kv(t){if(t.task===null)return It;Zs(t,{detail:{},type:"session"});let{text:e}=await dn(t.root,{id:t.task.contract.id});return e.trim().length===0?It:{kind:"context",text:e}}function Zs(t,e){if(t.task===null)return;Le(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var hn="git",Uv={amp:"Amp",opencode:"OpenCode"},Bv=".git/hooks";function ka(){return[...Gs.map((t)=>t.name),hn]}function Qs(t){let e=Gs.find((r)=>r.name===t);if(e!==void 0)return e;if(t===hn)throw new v("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=Uv[t];if(n!==void 0)throw new g(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new v(`Unknown agent "${t}"`,`Choose one of: ${ka().join(", ")}`)}function vm(t){if(t!==hn)Qs(t)}async function to(t,e){if(e===hn)return Vp(t);return tm(t,Qs(e),await tt(t))}async function Cm(t,e){if(e===hn)return Jp(t);return em(t,Qs(e),await tt(t))}async function Am(t){return[...Gs.map((n)=>({agent:n.name,events:tr(n),file:n.file,installed:pa(t,n),label:n.label,support:n.support})),{agent:hn,events:[...Bp],file:Bv,installed:await Wp(t),label:"git",support:"git"}]}async function Om(t,e,n,r){let s=Qs(t),o=Wv(s,e);try{let{decision:i,expired:a,warning:c}=await Tm(s.parse(o,Vv(n),r));return{expired:a,stdout:ta(s,o,i),warning:c}}catch(i){if(!ce.has(o))throw i;let a=`ari could not check this ${o} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:ta(s,o,{kind:"deny",reason:a}),warning:a}}}function Wv(t,e){if(!Sp(e))throw new v(`Unknown hook event "${e}"`,`Choose one of: ${zi.join(", ")}`);if(tr(t).includes(e))return e;throw new v(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${tr(t).join(", ")}`)}function Vv(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(ue(e))return e;throw new g("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}function Rm(t,e,n){let r=`ari hooks ${t} --agent`;return R({args:L({agent:{description:`Agent: ${ka().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(s)=>{let o=Se(s.args.agent,"--agent",`${r} <name>`);s.output.result(await n(await _(),o),Yv)}})}var Jv=R({description:"List the agents ari has hook adapters for and whether they are installed here",examples:["ari hooks list --json"],json:!0,name:"list",run:async(t)=>{let e=await Am(await _());t.output.result({agents:e},({agents:n})=>n.map(Xv).join(`
|
|
124
|
+
`))}}),Im=R({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[Rm("install","Install ari hooks into an agent's project settings or into git",to),Rm("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",Cm),Jv]}),_m=R({description:"Answer an agent hook: reads the agent's JSON payload on stdin and prints its decision",examples:["ari hook claude before-edit < payload.json"],name:"hook",positionals:nt({agent:{description:"Agent name",required:!0},event:{description:"before-edit, before-shell, after-tool, stop, pre-compact or session-start",required:!0}}),run:async(t)=>{let e=process.stdin.isTTY?"":await Bun.stdin.text(),n=await Om(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
|
|
125
|
+
`);if(n.stdout.length>0)process.stdout.write(`${n.stdout}
|
|
126
|
+
`);if(n.expired)await qv()}});async function qv(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function Yv(t){if("files"in t)return t.files.map((n)=>`git ${n.hook}: ${n.action} (${n.path})`).join(`
|
|
127
|
+
`);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function Xv(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}import{existsSync as zv}from"fs";import{join as Zv}from"path";var nr="AGENTS.md",wa="<!-- ari:begin -->",eo="<!-- ari:end -->",Qv=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,tC=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,eC=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,Pm=`${W}/config.json`,nC="git",Nm=`\r
|
|
128
|
+
`,$a=`
|
|
129
|
+
`,rC=[wa,"## Ariadne","","This repository tracks work as Ariadne (`ari`) tasks. Work in this loop:","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`.","3. Run `ari check` to evaluate the current stage's gates.","4. Run `ari done`; it records evidence and advances. Fix what it reports and run it again.","",'Record learnings with `ari note "<text>"` and reload context with `ari context`. If you are stuck, ask a human with `ari block <id> --reason "<question>"`.',"Edit task contracts (`.ari/tasks/*.md`) and designs, never other files under `.ari/`: ari writes them. `ari --help --json` describes every command.",eo];function sC(t){let e=oC(le(t,nr)??"");return{action:zn(t,nr,e),path:nr}}async function Dm(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[nC]:[]],r=[...new Set(n)];for(let d of r)vm(d);let s=zv(Zv(t,W))?$e(t):[],o=e.pack===void 0?null:De(e.pack,s).name,a=Fu(t)?"created":"unchanged",c=o===null?a:cC(t,o,a),l=sC(t),u=[];for(let d of r)u.push(await to(t,d));return{agentsMd:l,config:c,hooks:u,pack:Y(t).pack,root:t}}function oC(t){let e=t.includes(Nm)?Nm:$a,n=rC.join(e),r=iC(t),[s,o]=r;if(s===void 0){let i=t.length===0?"":t.endsWith(e)?e:`${e}${e}`;return`${t}${i}${n}${e}`}if(r.length!==2||s.marker!==wa||o?.marker!==eo)throw new g(`${nr} has a damaged ari block: expect one ${wa} followed by one ${eo}`,`Remove the ari markers and the lines between them from ${nr}, then run 'ari init' again`);return`${t.slice(0,s.start)}${n}${t.slice(o.start+eo.length)}`}function iC(t){let e=[],n=null,r=0;for(let s of t.split($a)){let o=tC.exec(s)?.[1];if(n===null&&o!==void 0)n={mark:o,markers:e.length};else if(n!==null&&aC(s,n.mark))e.length=n.markers,n=null;let i=Qv.exec(s)?.[1];if(i!==void 0)e.push({marker:i,start:r+s.indexOf(i)});r+=s.length+$a.length}return e}function aC(t,e){return eC.exec(t)?.[1]?.startsWith(e)===!0}function cC(t,e,n){if(Y(t).pack===e)return n;return Xn(t,Pm,{...fn(t,Pm),pack:e}),n==="created"?"created":"updated"}var jm=R({args:L({agents:{description:"Install agent hooks, comma-separated (claude,codex,gemini,cursor,copilot,git)",type:"string"},gitHooks:{default:!1,description:"Install the pre-commit and pre-push git hooks",type:"boolean"},pack:{description:"Default methodology pack for new tasks",type:"string"}}),description:"Create .ari/ and the AGENTS.md block, and optionally install hooks",examples:["ari init","ari init --pack tdd --agents claude,codex --git-hooks"],json:!0,name:"init",run:async(t)=>{let e=await _(),n=await Dm(e,{agents:Wn(t.args.agents),gitHooks:t.args.gitHooks,pack:t.args.pack});t.output.result(n,lC)}});function lC(t){let e=t.hooks.flatMap((n)=>("files"in n)?n.files.map((r)=>`git ${r.hook}: ${r.action} (${r.path})`):[`${n.agent} hooks: ${n.action} (${n.file})`]);return[`.ari/config.json: ${t.config} (pack ${t.pack})`,`${t.agentsMd.path}: ${t.agentsMd.action}`,...e,'Next: ari new "<title>"'].join(`
|
|
130
|
+
`)}var yn=nt({id:{description:"Task id",required:!0}}),Lm=R({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:yn,run:async(t)=>{let e=await np(await _(),t.positionals.id),n={id:e.contract.id,status:e.record.status};t.output.result(n,({id:r})=>`Task "${r}" is ready; run 'ari start ${r}'`)}}),Mm=R({description:"Start a ready task in this worktree, or adopt one that no worktree holds",examples:["ari start add-profile-inheritance"],json:!0,name:"start",positionals:yn,run:async(t)=>{let e=await mn(await _(),t.positionals.id),{record:n}=e.task,r={base:n.base,id:n.id,instruction:e.instruction,stage:e.stage};t.output.result(r,({id:s,instruction:o,stage:i})=>`Task "${s}" is active at stage ${i}
|
|
131
|
+
${o}
|
|
132
|
+
Then: ari check, ari done`)}}),Gm=R({args:L({onto:{description:"Move the base to the merge base of HEAD and this ref",type:"string"},reason:{description:"Why the contract or locked files changed",type:"string"}}),description:"Accept a changed contract: re-freeze its hashes and withdraw the stage's approvals",examples:['ari amend add-profile-inheritance --reason "Widen scope to the loader"'],json:!0,name:"amend",positionals:yn,run:async(t)=>{let e=Se(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await op(await _(),t.positionals.id,e,{onto:t.args.onto}),r={base:n.record.base,id:n.contract.id,reason:e,status:n.record.status};t.output.result(r,({id:s})=>`Task "${s}" amended`)}}),Hm=R({args:L({reason:{description:"The question for a human",type:"string"}}),description:"Block the active task with a question for a human",examples:['ari block add-profile-inheritance --reason "Should child profiles inherit secrets?"'],json:!0,name:"block",positionals:yn,run:async(t)=>{let e=Se(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await ip(await _(),t.positionals.id,e),r={id:n.contract.id,question:n.record.question,status:n.record.status};t.output.result(r,({id:s})=>`Task "${s}" is blocked; a human answers with 'ari resolve ${s} --answer <text>'`)}}),Fm=R({args:L({answer:{description:"The answer to the task's question",type:"string"}}),description:"Answer a blocked task's question, record it as a decision and resume the task",examples:['ari resolve add-profile-inheritance --answer "No; secrets stay per profile"'],json:!0,name:"resolve",positionals:yn,run:async(t)=>{let e=Se(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await ap(await _(),t.positionals.id,e),{contract:r,record:s}=n.task,o={id:r.id,knowledgeId:n.knowledgeId,status:s.status};t.output.result(o,({id:i,knowledgeId:a})=>`Task "${i}" is active again; decision ${a} recorded`)}}),Km=R({description:"Record a human approval for the task's current stage (as git user.name)",examples:["ari approve add-profile-inheritance"],json:!0,name:"approve",positionals:yn,run:async(t)=>{let e=await _(),n=await Wl(e);if(n===null)throw new g("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await cp(e,t.positionals.id,n),s=r.record.approvals.at(-1),o={by:n,id:r.contract.id,stage:s?.stage??null};t.output.result(o,({id:i,stage:a})=>`Approved stage ${a??"unknown"} of "${i}" as ${n}`)}});var uC=1,Um=R({args:L({agent:{description:"Agent name from config.agents",type:"string"},task:{description:"Task id (defaults to the active task, then the next startable one)",type:"string"}}),description:"Drive a task headlessly with an agent until it is done, blocked or out of attempts",examples:["ari run --agent claude","ari run --agent codex --task add-profile-inheritance --json"],json:!0,name:"run",run:async(t)=>{let e=Se(t.args.agent,"--agent","ari run --agent <name>"),n=await hp(await _(),{agent:e,output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(n,dC),n.outcome==="done"?void 0:uC}});function dC(t){return[...t.turns.map((n,r)=>`turn ${r+1}: stage ${n.stage}, agent exit ${n.agentExitCode}, ${n.outcome}${n.failing.length===0?"":` (${n.failing.join(", ")})`}`),`Task "${t.task}" is ${t.outcome}`].join(`
|
|
133
|
+
`)}var ba=["draft","ready","active","blocked","done"],Bm=R({args:L({pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{description:"Scope globs, comma-separated",type:"string"}}),description:"Create a task contract from a title",examples:['ari new "Add profile inheritance" --pack tdd --scope "src/profiles/**"'],json:!0,name:"new",positionals:nt({title:{description:"Task title",required:!0}}),run:async(t)=>{let e=await ep(await _(),t.positionals.title,{pack:t.args.pack,scope:Wn(t.args.scope)}),n={contractPath:e.contractPath,...Yi(e.task)};t.output.result(n,({contractPath:r,id:s})=>`Created task "${s}" at ${r}
|
|
134
|
+
Complete its scope, criteria and checks, then run 'ari ready ${s}'`)}}),Wm=R({args:L({status:{description:`Only these statuses, comma-separated (${ba.join(",")})`,type:"string"}}),description:"List tasks and any unreadable contracts or records",examples:["ari list","ari list --status ready,active --json"],json:!0,name:"list",run:async(t)=>{let e=pC(t.args.status),n=await Ps(await _(),e.length===0?{}:{statuses:e});t.output.result({invalid:n.invalid,tasks:n.tasks.map(Yi)},mC)}}),Vm=R({description:"Show a task's contract, record and current stage",examples:["ari show add-profile-inheritance --json"],json:!0,name:"show",positionals:nt({id:{description:"Task id",required:!0}}),run:async(t)=>{let e=await Fe(await _(),t.positionals.id);t.output.result(e,fC)}});function pC(t){return Wn(t).map((e)=>{let n=ba.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown status "${e}"`,`Choose from ${ba.join(", ")}`)})}function mC(t){if(t.tasks.length===0&&t.invalid.length===0)return'No tasks yet. Run ari new "<title>"';let e=t.tasks.map((r)=>`${r.id} ${r.status} ${r.pack} ${r.title}`),n=t.invalid.map((r)=>`${r.id} unreadable ${r.problem}`);return[...e,...n].join(`
|
|
135
|
+
`)}function fC(t){let{contract:e,record:n}=t.task,r=t.stage===null?[]:[`Stage: ${t.stage}${t.active?" (active here)":""}`],s=t.instruction===null?[]:[`Instruction: ${t.instruction}`],o=n.question===null?[]:[`Question: ${n.question}`];return[`${e.id}: ${e.title}`,`Status: ${n.status} Pack: ${e.pack} Attempts: ${n.attempts}/${e.budget.attempts}`,...r,...s,...o,`Scope: ${e.scope.join(", ")||"none"}`,...e.criteria.map((i)=>`${i.id}: ${i.text} [${i.checks.join(", ")}]`),...e.checks.map((i)=>`check ${i.name} (expect ${i.expect}): ${i.run}`)].join(`
|
|
136
|
+
`)}var Jm=R({name:"context",description:"Print the context pack of a task within a token budget",args:L({budget:{description:"Token budget (default: context.budget from .ari/config.json)",type:"number"}}),positionals:nt({id:{description:"Task id (default: the active task of this worktree)"}}),json:!0,examples:["ari context","ari context add-profile-inheritance --budget 2000","ari context --json"],run:async(t)=>{let{budget:e}=t.args;if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw new v(`--budget must be a positive whole number of tokens, got ${e}`,"Pass --budget 6000");let n=await dn(await _(),{budget:e,id:t.positionals.id});t.output.result(n,({text:r})=>r)}});var gC=" ",hC=R({name:"list",description:"List project knowledge entries",args:L({all:{default:!1,description:"Include archived entries",type:"boolean"}}),json:!0,examples:["ari knowledge list","ari knowledge list --all --json"],run:async(t)=>{let e=Pi(await _(),{all:t.args.all});t.output.result(e,$C)}}),yC=R({name:"search",description:"Rank knowledge entries against a query with BM25",args:L({all:{default:!1,description:"Include archived entries",type:"boolean"}}),positionals:nt({query:{description:"Words to search for",required:!0,variadic:!0}}),json:!0,examples:["ari knowledge search profile resolution"],run:async(t)=>{let e=t.positionals.query.join(gC),n=vd(await _(),e,{all:t.args.all});t.output.result(n,bC)}}),kC=R({name:"show",description:"Show one knowledge entry and how many done tasks used it",positionals:nt({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),{tasks:n}=await Ps(e);t.output.result(Cd(e,t.positionals.id,n),xC)}}),wC=R({name:"archive",description:"Archive a knowledge entry",args:L({force:{default:!1,description:"Allow archiving a constraint or decision",type:"boolean"}}),positionals:nt({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),n=Ad(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),qm=R({name:"knowledge",description:"List, search, show and archive project knowledge",subcommands:[hC,yC,kC,wC]});function Ym(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
|
|
137
|
+
`)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function $C(t){return t.entries.length===0?"No knowledge entries":t.entries.map(Ym).join(`
|
|
138
|
+
`)}function bC(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${Ym(e.entry)}`).join(`
|
|
139
|
+
`)}function xC(t){let{entry:e}=t,n=(r)=>r.length===0?"none":r.join(", ");return[`${e.id} (${e.kind}, ${e.status})`,`Scope: ${n(e.scope)}`,`Sources: ${n(e.sources)}`,`Created: ${e.created}`,`Used by done tasks: ${t.uses}`,...e.supersedes.length===0?[]:[`Supersedes: ${n(e.supersedes)}`],...e.supersededBy===null?[]:[`Superseded by: ${e.supersededBy}`],"",e.text].join(`
|
|
140
|
+
`)}var SC="fact",EC=" ",zm=R({name:"note",description:"Add a note to the active task, or a project knowledge entry with --global",args:L({global:{default:!1,description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:`Entry kind with --global: ${Pe.join(", ")} (default: fact)`,type:"string"},scope:{description:"Comma-separated globs the entry applies to, with --global (default: everywhere)",type:"string"}}),positionals:nt({text:{description:"The note text",required:!0,variadic:!0}}),json:!0,examples:['ari note "The fixture needs a real git repository"','ari note --global --kind constraint --scope "packages/atlas/src/**" "Profile resolution stays synchronous"'],run:async(t)=>{let e=t.positionals.text.join(EC),{global:n,kind:r,scope:s}=t.args;if(!n&&(r!==void 0||s!==void 0))throw new v("--kind and --scope apply only to knowledge entries","Add --global, or drop them");let o=r??SC;if(!Sd(o))throw new v(`--kind must be one of ${Pe.join(", ")}, got "${o}"`,"Pass --kind fact");let i=await _();if(n){let p={kind:o,scope:Ed(s??""),text:e},f=await Td(i,p);t.output.result({entry:f,target:"knowledge"},Xm);return}let a=await lp(i,e),c=a.record.notes.length-1,l=a.record.notes[c],d={at:l?.at??"",index:c,target:"task",task:a.contract.id,text:l?.text??e};t.output.result(d,Xm)}});function Xm(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var xa="HEAD~1",TC={fail:"fail",pass:"pass",regression:"pass"};async function Zm(t,e={}){let n=Y(t),r=e.since??xa,s=await Ze(t,r),o=yt(await Ct(t,s)),{tasks:i}=Gt(t,n),a=i.filter((u)=>u.record.status==="done"&&o.some((d)=>K(d,u.contract.scope))),c=ie(t),l=[];for(let u of a){let d=await CC(t,u),p=c.filter((f)=>f.sources.includes(u.contract.id)).map((f)=>f.id);l.push({checks:d,knowledge:p,ok:d.every((f)=>f.ok),task:u.contract.id})}return{changed:o.length,commit:s,regressed:l.filter((u)=>!u.ok).map((u)=>u.task),since:r,tasks:l}}function vC(t){return{command:t.command,exitCode:t.exitCode,expect:t.expect,name:t.name,ok:t.ok,outputTail:t.outputTail,timedOut:t.timedOut}}async function CC(t,e){let n=[];for(let r of e.contract.checks){let[s]=await wt([OC(r)],AC(e,r),t);if(s!==void 0)n.push(vC(s))}return n}function AC(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??TC[e.expect]}function OC(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var RC=1,Qm=R({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:L({since:{default:xa,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await Zm(await _(),{since:t.args.since});return t.output.result(e,IC),e.regressed.length===0?void 0:RC}});function IC(t){let e=`Replayed ${t.tasks.length} done tasks against ${t.since} (${t.changed} changed files)`,n=t.tasks.flatMap((r)=>{if(r.ok)return[`ok ${r.task}`];let s=r.checks.filter((i)=>!i.ok),o=r.knowledge.length===0?[]:[` cited by: ${r.knowledge.join(", ")}`];return[`REGRESSED ${r.task}`,...s.flatMap((i)=>[` ${i.name} should ${i.expect}: ${i.command}`,_C(i.outputTail)]),...o]});return[e,...n].join(`
|
|
141
|
+
`)}function _C(t){return t.trimEnd().split(`
|
|
142
|
+
`).map((e)=>` ${e}`).join(`
|
|
143
|
+
`)}import{resolve as PC}from"path";var rr="none",tf=R({name:"sleep",description:"Consolidate memory: prune journals, archive duplicates, decay and enforce the budget",args:L({apply:{description:"Apply a validated JSON proposal of merges, promotions and archives",type:"string"},force:{default:!1,description:"With --apply, allow retiring constraint and decision entries",type:"boolean"}}),json:!0,examples:["ari sleep","ari sleep --json","ari sleep --apply proposal.json"],run:async(t)=>{let e=await _(),{apply:n,force:r}=t.args;if(n===void 0){if(r)throw new v("--force applies only with --apply","Run 'ari sleep --apply <file> --force'");t.output.result(await pn(e),NC);return}t.output.result(await Bd(e,PC(process.cwd(),n),{force:r}),DC)}});function NC(t){let e=t.archived.map((o)=>` ${o.id} (${o.reason}${o.supersededBy===null?"":` of ${o.supersededBy}`})`),{clusters:n,decisions:r,notes:s}=t.candidates;return[`Pruned journals: ${t.pruned.length===0?rr:t.pruned.map((o)=>o.task).join(", ")}`,`Archived entries: ${e.length===0?rr:""}`.trimEnd(),...e,`Active knowledge: ${t.activeBytes} of ${t.maxBytes} bytes`,`Candidates: ${n.length} merge clusters, ${s.length} unpromoted notes, ${r.length} overlapping decision pairs`,...n.map((o)=>` merge? ${o.ids.join(", ")} (similarity ${o.similarity})`),...s.map((o)=>` promote? ${o.task} note ${o.note}: ${o.text.split(`
|
|
144
|
+
`)[0]??""}`),...r.map((o)=>` reconcile? ${o.ids.join(" and ")}`)].join(`
|
|
145
|
+
`)}function DC(t){return[`Created: ${t.created.length===0?rr:t.created.map((e)=>e.id).join(", ")}`,`Archived: ${t.archived.length===0?rr:t.archived.map((e)=>e.id).join(", ")}`,`Promoted notes: ${t.promoted.length===0?rr:t.promoted.map((e)=>`${e.task} ${e.notes.join(", ")}`).join("; ")}`].join(`
|
|
146
|
+
`)}import{existsSync as kf}from"fs";import{basename as rA,extname as sA,join as wf}from"path";import{readFileSync as jC}from"fs";import{join as LC}from"path";var nf=["checks","invariants","scope","locked"];function rf(t,e,{exact:n,pack:r}){if(r===null)return[`the pack "${e.contract.pack}" is not a built-in or project pack`];let s=e.record.status==="done",o=s?[...BC(t,e),...HC(e)]:[],i=e.record.evidence.flatMap(UC);if(!n)return[...o,...MC(e,r),...i];let a=s?WC(e,r):[];return[...o,...FC(e,r),...i,...a]}function sf(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return nf.flatMap((r)=>{let s=no(t,r),o=s.at(-1);return o===void 0?[]:[{...o,checks:of(s)}]})}function MC(t,e){let n=e.stages.flatMap((u)=>u.gates),s=nf.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>no(t,u).length===0).map((u)=>`the record holds no ${u} evidence, but pack "${e.name}" runs that gate`),o=new Set(n.flatMap((u)=>GC(t.contract,u))),i=of(no(t,"checks")),a=[...o].filter((u)=>!i.some((d)=>d.name===u.name&&d.command===u.run)).map((u)=>`the record holds no evidence that ${u.name} (${JSON.stringify(u.run)}) passed`),c=no(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||Ea(c,t.contract.invariants)?[]:[`the invariants evidence ran ${JSON.stringify(c)}, but the contract asks for ${JSON.stringify(t.contract.invariants)}`];return[...s,...a,...l]}function GC(t,e){return e.kind==="checks"&&e.expect==="pass"?sn(t,e.select):[]}function no(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function of(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[Sa(n),n])).values()]}function HC(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function FC(t,e){let{record:n}=t,r=n.status==="done"?e.stages.length:n.stage,s=n.evidence.length;return[...s===r?[]:[`the record holds evidence for ${s} ${Z(s,"stage","stages")}, but pack "${e.name}" expects ${r} at this point`],...n.evidence.flatMap((i,a)=>KC(i,e,a))]}function KC(t,e,n){let r=e.stages[n];if(r===void 0)return[];if(t.stage!==r.name)return[`evidence ${n+1} is for stage "${t.stage}", but stage ${n+1} of pack "${e.name}" is "${r.name}"`];let s=t.gates.map((i)=>i.gate),o=r.gates.map((i)=>i.kind);if(Ea(s,o))return[];return[`the evidence of stage "${r.name}" records the gates [${s.join(", ")}], but the pack runs [${o.join(", ")}]`]}function UC(t){return t.gates.filter((e)=>!e.ok||e.checks.some((n)=>!n.ok)).map((e)=>`the evidence of stage "${t.stage}" records a failing ${e.gate} gate`)}function BC(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=jC(LC(t,pt(e.contract.id)),"utf8");if(ee(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function WC(t,e){let n=t.record.evidence.length-1,r=t.record.evidence[n],s=e.stages[n];if(r===void 0||s===void 0||r.stage!==s.name)return[];return r.gates.flatMap((o,i)=>VC(t.contract,s,o,i))}function VC(t,e,n,r){let s=e.gates[r];if(s===void 0||s.kind!==n.gate)return[];let o=JC(t,s);if(o===null)return[];let i=n.checks.map(qC);if(Ea(i.map(Sa),o.map(Sa)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${ef(i)}, but the contract asks for ${ef(o)}`]}function JC(t,e){switch(e.kind){case"checks":return sn(t,e.select).map((n)=>({command:n.run,expect:e.expect,name:n.name}));case"invariants":return t.invariants.map((n,r)=>({command:n,expect:"pass",name:`invariants[${r}]`}));default:return null}}function qC(t){return{command:t.command,expect:t.expect,name:t.name}}function Sa(t){return JSON.stringify([t.name,t.command,t.expect])}function ef(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function Ea(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Ee=0,va=1,YC=128,XC=`
|
|
147
|
+
`;async function af(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=se(e.id),s=await A(t,["log","--reverse","--format=%H","HEAD","--",r]),o=null;for(let i of s.stdout.split(XC).filter((a)=>a.length>0)){let a=mf(await sr(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)o??=i;if(zC(a,n))return{finished:i,started:o??i}}return null}async function cf(t,e,n){return mf(await sr(t,e,se(n)))?.status??null}async function sr(t,e,n){let r=await A(t,["show",`${e}:${n}`],{allowedExitCodes:[Ee,YC]});return r.exitCode===Ee?r.stdout:null}async function lf(t,e){return await pf(t,e)!==null}async function uf(t,e){return pf(t,`${e}^`)}async function or(t,e,n){return(await A(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[Ee,va]})).exitCode===Ee}async function Ca(t,e,n){let r=await A(t,["merge-base",e,n],{allowedExitCodes:[Ee,va]});return r.exitCode===Ee?r.stdout.trim():null}async function Aa(t,e,n){return Number((await A(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function df(t){return(await A(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function pf(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await A(t,n,{allowedExitCodes:[Ee,va]});return r.exitCode===Ee?r.stdout.trim():null}function mf(t){let e=ZC(t);if(!Ta(e))return null;let n=Array.isArray(e.evidence)?e.evidence.at(-1):null,r=Array.isArray(e.history)?e.history[0]:null;return{base:e.base??null,created:Ta(r)?r.at:null,evidence:Ta(n)?n:null,status:e.status}}function zC(t,{at:e,stage:n,treeHash:r}){let s=t.evidence;return s!==null&&s.at===e&&s.stage===n&&s.treeHash===r}function ZC(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function Ta(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Oa({packs:t},e){return{exact:!0,pack:Ra(t,e.contract.pack)}}async function ff(t,e,n,r){let{gatesHash:s}=e.record,o=r===null?null:await QC(t,r,e.contract.pack),i=[n,o].find((a)=>a!==null&&tA(a,e)===s);if(i)return Oa(i,e);return{exact:!1,pack:Ra((o??n).packs,e.contract.pack)}}async function QC(t,e,n){let r=$i(n),s=await sr(t,e,r),o=await sr(t,e,jn);try{return{config:Pn(o===null?{}:JSON.parse(o)),packs:Ne(s===null?[]:[is(s,r)])}}catch(i){if(i instanceof g||i instanceof SyntaxError)return null;throw i}}function tA({config:t,packs:e},n){let r=Ra(e,n.contract.pack);return r===null?null:as(r,t)}function Ra(t,e){return t.find((n)=>n.name===e)??null}async function hf(t){let{commits:e,record:n,root:r,target:s}=t,{base:o}=n;if(o===null)return yf("the record has no base commit");let i=await lf(r,o);if(e===null){if(!i)return Ia(o);return ro(await Ct(r,await gf(r,o,s,"HEAD")))}let{finished:a}=e,c=i&&await or(r,o,a),l=s===null?null:await Ca(r,s,a);if(l===null||l===a)return nA(t,e,c?o:null);let u=c?await gf(r,o,s,a):await eA(r,l,t.otherFinishes,a);return ro(await Jr(r,u,a))}async function gf(t,e,n,r){let s=n===null?null:await Ca(t,n,r);return s!==null&&await or(t,e,s)?s:e}async function eA(t,e,n,r){let s={commit:e,distance:await Aa(t,e,r)};for(let o of n){if(o===r||!await or(t,e,o)||!await or(t,o,r))continue;let i=await Aa(t,o,r);if(i<s.distance)s={commit:o,distance:i}}return s.commit}async function nA(t,e,n){let{record:r,root:s}=t,{finished:o,started:i}=e;if(n===null&&await df(s))return Ia(r.base);let a=await uf(s,i),c=a===null?null:await Jr(s,a,o);if(n===null)return c===null?Ia(r.base):ro(c);let l=await Jr(s,n,o);return ro(c===null?l:l.filter((u)=>c.includes(u)))}function ro(t){return{files:t,problem:null}}function yf(t){return{files:[],problem:t}}function Ia(t){return yf(`the base commit ${t} is not in this clone; fetch the full history`)}var oA="\x00",_a="HEAD",ja="done",Pa=[je,Pu],iA="invalid";async function $f(t,e){let n=Y(t);await Vr(t);let r=Gt(t,n),s=Ne($e(t)),o=e.kind==="base"?await Ze(t,e.ref):null,i=new Map(r.tasks.map((p)=>[p.contract.id,p])),a=new Map(r.invalid.map((p)=>[p.id,p])),c=await aA(t,e,o,i),l=new Map;for(let p of c){let f=i.get(p);if(f!==void 0)l.set(p,await af(t,f.record))}let u={commits:l,config:n,mode:e.kind,packs:s,root:t,target:o},d=[];for(let p of c){let f=i.get(p);if(f!==void 0){d.push(await uA(u,f));continue}let m=a.get(p)?.problem??lA(t,p);if(m===null)continue;d.push({gates:[],ok:!1,problems:[m],stage:null,status:iA,task:p})}return{failed:d.filter((p)=>!p.ok).map((p)=>p.task),mode:e.kind,ref:e.kind==="base"?e.ref:null,tasks:d}}async function aA(t,e,n,r){let s=n??_a,o=async(i)=>(r.get(i)?.record.status??await cA(t,i,s))===ja;switch(e.kind){case"all":return Da(Mn(t),o);case"base":{let i=["diff","--name-only","--no-renames","-z",s,_a,"--",...Pa],a=(await A(t,i)).stdout.split(oA),c=new Set(Na(a,je));return Da(Na(a,...Pa),async(l)=>c.has(l)||o(l))}case"local":{let i=it(await tt(t))?.task,a=await Da(Na(await Ct(t,_a),...Pa),o);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function cA(t,e,n){if(!kf(wf(t,se(e))))return cf(t,n,e);try{return Me(t,e).status}catch(r){if(r instanceof g)return ja;throw r}}function lA(t,e){let n=se(e);return kf(wf(t,n))?`${n} has a record but no contract`:null}function Na(t,...e){let n=t.filter((r)=>K(r,e)).map((r)=>rA(r,sA(r)));return[...new Set(n)].filter(wi).sort(N)}async function Da(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function uA(t,e){let{record:n}=e,r=n.evidence.at(-1),s={status:n.status,task:e.contract.id};if(r===void 0){let u=n.status===ja?["the task is done but has no stage evidence"]:[];return{...s,gates:[],ok:u.length===0,problems:u,stage:null}}let{root:o}=t,i=t.mode==="all"?await ff(o,e,t,bf(t,e)?.finished??null):Oa(t,e),a=rf(o,e,i),c=[];for(let u of sf(e,i)){let d=await dA(t,e,u);if(d===null)continue;let p=d.current===u.ok&&d.details.length===0;c.push({current:d.current,details:d.details,gate:u.gate,ok:p,recorded:u.ok})}let l=a.length===0&&c.every((u)=>u.ok);return{...s,gates:c,ok:l,problems:a,stage:r.stage}}function bf(t,e){return t.commits.get(e.contract.id)??null}async function dA(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=pA(e,n.checks);return r.length===0?null:mA(t,e,r)}case"locked":return gA(t,e);case"scope":return hA(t,e);default:return null}}function pA(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function mA(t,e,n){let r=[],s=!0;for(let o of n){let i={name:o.name,run:o.command,timeoutSeconds:fA(t,e,o.name)},[a]=await wt([i],o.expect,t.root);if(a===void 0)continue;if(s&&=a.ok,a.ok===o.ok)continue;r.push(a.ok?`${o.name} now meets its expectation (${o.expect})`:Vo(a))}return{current:s,details:r}}function fA(t,e,n){return e.contract.checks.find((s)=>s.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function gA(t,e){let n=await zt(t.root,e.contract.lock),r=Fn(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function hA(t,e){let{commits:n,root:r,target:s}=t,o=[...n].flatMap(([c,l])=>l===null||c===e.contract.id?[]:[l.finished]),i=await hf({commits:bf(t,e),otherFinishes:o,record:e.record,root:r,target:s});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=yt(i.files).filter((c)=>!K(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var yA=1,Sf=R({name:"verify",description:"Re-evaluate the reproducible gates of done tasks against their evidence",args:L({all:{default:!1,description:"Verify every done task",type:"boolean"},base:{description:"Verify tasks whose record changed between this reference and HEAD (CI mode)",type:"string"}}),json:!0,examples:["ari verify","ari verify --base origin/develop","ari verify --all --json"],run:async(t)=>{let{all:e,base:n}=t.args;if(e&&n!==void 0)throw new v("--all and --base exclude each other","Pass one of them");let r=n!==void 0?{kind:"base",ref:n}:e?{kind:"all"}:{kind:"local"},s=await $f(await _(),r);return t.output.result(s,kA),s.failed.length===0?void 0:yA}});function kA(t){if(t.tasks.length===0)return"No task to verify";return t.tasks.flatMap((e)=>{let n=e.stage===null?"":` (${e.stage})`,r=e.gates.filter((i)=>!i.ok).flatMap((i)=>[` ${i.gate}: recorded ${xf(i.recorded)}, now ${xf(i.current)}`,...i.details.map((a)=>` ${a}`)]),s=e.problems.map((i)=>` ${i}`),o=e.ok&&e.gates.length===0?" (no evidence to reproduce yet)":"";return[`${e.ok?"ok":"FAILED"} ${e.task}${n}${o}`,...s,...r]}).join(`
|
|
148
|
+
`)}function xf(t){return t?"passed":"failed"}var Ef=[Jm,zm,qm,tf,Qm,Sf];var bA=".ari",xA="cli-state.json",SA=_o({bin:"ari",commands:[jm,Bm,Wm,Vm,Lm,Mm,kp,wp,$p,Gm,Hm,Fm,Km,bp,...Ef,Im,_m,Um],config:new Ho($A(wA(),bA,xA),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:bl});SA.main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
|
+
"author": "@ice-chillios",
|
|
3
|
+
"bin": {
|
|
4
|
+
"ari": "dist/cli.js",
|
|
5
|
+
"ariadne": "dist/cli.js"
|
|
6
|
+
},
|
|
7
|
+
"description": "Ariadne CLI - Task contracts, CLI-evaluated gates and tiered memory for coding agents",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"LICENSE"
|
|
11
|
+
],
|
|
12
|
+
"keywords": [
|
|
13
|
+
"cli",
|
|
14
|
+
"agents",
|
|
15
|
+
"ai",
|
|
16
|
+
"contracts",
|
|
17
|
+
"gates",
|
|
18
|
+
"tdd",
|
|
19
|
+
"workflow",
|
|
20
|
+
"memory"
|
|
21
|
+
],
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
|
+
"main": "dist/cli.js",
|
|
2
24
|
"name": "@r5n/ariadne",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org/"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/r5n-labs/clis.git"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "rm -rf dist && bun build.ts",
|
|
35
|
+
"clean": "rm -rf dist node_modules",
|
|
36
|
+
"dev": "bun --bun src/cli.ts",
|
|
37
|
+
"package:dryRun": "bun ../../tools/scripts/publish-package.ts . --dry-run",
|
|
38
|
+
"package:prepare": "NODE_ENV=production bun run build && bun ../../tools/scripts/prepare-publish.ts .",
|
|
39
|
+
"package:publish": "bun ../../tools/scripts/publish-package.ts ."
|
|
40
|
+
},
|
|
41
|
+
"type": "module",
|
|
42
|
+
"version": "0.2.0"
|
|
43
|
+
}
|