@geonosis/verify 1.0.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ # `@geonosis/verify`
2
+
3
+ One gate runner. Tiers of shell steps, run serially, recorded as a JSON gate report a hook can read.
4
+
5
+ A repo's gate is already a list of commands — it lives in a `verify` script, a CI job, and an
6
+ engineer's muscle memory, and the three drift. This runs the list from one place and writes down
7
+ what happened, so the Stop hook, CI and the ledger are all reading the same run rather than each
8
+ re-deciding what "green" meant.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pnpm add -D @geonosis/verify # bun add -d, npm i -D
14
+ ```
15
+
16
+ ## `--prove` is the first thing to run after installing
17
+
18
+ ```bash
19
+ geonosis-verify --prove
20
+ ```
21
+
22
+ It writes a temp config with one passing step and one that exits 3, runs the real binary over it in
23
+ a throwaway directory, and checks that the failure reached the report, that the right step is named
24
+ with the right exit code, and that the process exited 1:
25
+
26
+ ```
27
+ PROVEN — a planted "exit 3" step reached the report and exited 1
28
+ ```
29
+
30
+ A runner that reports green is worth nothing until it has been watched going red on purpose. It
31
+ touches nothing in the repo it is run from, so it is safe at any time.
32
+
33
+ ## Config
34
+
35
+ `geonosis.json` in the directory you run it from:
36
+
37
+ ```jsonc
38
+ {
39
+ "verify": {
40
+ "fast": ["pnpm typecheck", "pnpm lint", "pnpm test:unit", "pnpm ratchet --tier fast"],
41
+ "full": ["fast", "pnpm build", "pnpm test:integration", "pnpm format:check"]
42
+ }
43
+ }
44
+ ```
45
+
46
+ A step whose text is another tier's NAME is that tier, inlined in place, however deep it goes. A
47
+ cycle is refused by the path it went round rather than discovered as a stack overflow.
48
+
49
+ **There is no default tier and there never will be one.** A default that happened to match one
50
+ repo's script names would run the wrong commands everywhere else and still report green. No
51
+ `geonosis.json`, no `verify` object, or an unknown tier is refused by name.
52
+
53
+ ## Running it
54
+
55
+ ```bash
56
+ geonosis-verify fast
57
+ geonosis-verify full --report .geonosis/full.json
58
+ geonosis-verify full --exclusive --exclusive-timeout 900
59
+ ```
60
+
61
+ ```
62
+ ok fast/1 pnpm typecheck (2140 ms)
63
+ FAIL fast/2 pnpm lint (1830 ms)
64
+ skip fast/3 pnpm test:unit (0 ms)
65
+ verify FAIL — fast — /repo/.geonosis/gate-report.json
66
+ ```
67
+
68
+ | Exit | What it means |
69
+ | --- | --- |
70
+ | `0` | every step passed AND the report was written |
71
+ | `1` | a step failed |
72
+ | `2` | refused — no config, no `verify`, an unknown tier, an option we do not implement — **or the report could not be written** |
73
+
74
+ The last one is the one worth arguing about: a gate that cannot record has not passed. Exit 0 on a
75
+ green run whose report never landed would hand the caller a pass they cannot go back and read.
76
+
77
+ ## The report
78
+
79
+ `.geonosis/gate-report.json`, unless `--report` says otherwise:
80
+
81
+ ```jsonc
82
+ {
83
+ "tier": "full",
84
+ "startedAt": "2026-08-30T10:00:00.000Z",
85
+ "finishedAt": "2026-08-30T10:00:04.500Z",
86
+ "ok": false,
87
+ "steps": [
88
+ { "id": "fast/1", "command": "pnpm typecheck", "ok": true, "exitCode": 0, "ms": 2140, "tail": "…" },
89
+ { "id": "fast/2", "command": "pnpm lint", "ok": false, "exitCode": 1, "ms": 1830, "tail": "…" },
90
+ { "id": "full/1", "command": "pnpm build", "ok": false, "exitCode": -1, "ms": 0, "tail": "", "skipped": true }
91
+ ]
92
+ }
93
+ ```
94
+
95
+ - **`id` is `<tier>/<n>`, numbered within the tier that DECLARED the step** — not within the run. An
96
+ inlined step keeps its own tier, so `fast/2` is the same command whether the operator ran `fast`
97
+ or ran `full`. Numbering per run would renumber every fast step the moment `full` grew one in
98
+ front of it, and an id that moves is an id nothing can compare against yesterday's report.
99
+ - **The run stops at the first red, and the rest are still written down**, as `skipped` with
100
+ `exitCode: -1`. A report that silently lost the tail of the tier reads as a shorter, greener tier.
101
+ - **`tail` is the last 40 lines of stdout and stderr, interleaved**, with the colour codes taken
102
+ out. The shell folds the two streams, so they stay in the order they were written; concatenating
103
+ two captured buffers would not.
104
+ - Each step runs in a **subshell**. `<step> 2>&1` binds the redirect to the last command of the step
105
+ only, so `echo boom >&2; exit 3` would lose "boom" entirely — and a gate whose report is missing
106
+ the error line is a gate nobody can act on.
107
+
108
+ ## `stats` — the first-try pass rate
109
+
110
+ Not a gate; the KPI a law diet is judged by. The Stop hook records every turn-end it gated in
111
+ `.geonosis/stop-turns.json`, one bucket per day, and this reads it back:
112
+
113
+ ```bash
114
+ geonosis-verify stats
115
+ geonosis-verify stats --since 2026-09-07 # that window, and everything before it
116
+ geonosis-verify stats --json
117
+ ```
118
+
119
+ ```
120
+ first-try pass rate — the share of turn-ends whose fast tier was green
121
+ before 61 turns · 18 blocked · 70.5 % first try
122
+ 2026-09-07+ 58 turns · 6 blocked · 89.7 % first try
123
+ ```
124
+
125
+ A turn whose fast tier was green on the first run is a turn where the code was written the way the
126
+ gates accept without being told twice. A blocked turn is a correction loop. `--since` gives the two
127
+ windows a before/after needs, from one command and one instrument — the procedure is
128
+ [`docs/law-diet.md`](../../docs/law-diet.md).
129
+
130
+ Three refusals, all of them the same refusal: **an empty record is not a perfect score.** A repo
131
+ where the hook has never run says "no turns recorded" and gives no rate; a record that will not parse
132
+ is an error, not zero turns; and a turn the hook never gated (`stop_hook_active`, where the gate does
133
+ not run at all) is not counted, because there was no first try to have.
134
+
135
+ The sibling `stop-blocks.json` cannot answer this and is not asked to. It is the block cap's working
136
+ memory, and a green turn deletes its own row from it.
137
+
138
+ ## `--exclusive`
139
+
140
+ Takes the machine-wide lock `@geonosis/ratchet` owns, through that package's published entry, so a
141
+ verify and a ratchet on one laptop serialise against each other rather than each against itself.
142
+ Three sessions each starting a full gate is how a 25-minute run becomes two hours and produces
143
+ failures that are about the load and not the code.
144
+
145
+ The lock is taken only AFTER every refusal has been decided: a run that waits half an hour for the
146
+ machine and then finds the tier was misspelled has held it against two other sessions for nothing.
147
+ `--exclusive-timeout <seconds>` bounds the wait (default 1800) and says who it is waiting for.
148
+
149
+ ## Programmatic use
150
+
151
+ ```ts
152
+ import { loadVerifyConfig, resolveTier, runSteps, shellRun, writeReport } from '@geonosis/verify'
153
+
154
+ const steps = resolveTier(loadVerifyConfig(cwd), 'fast')
155
+ const report = runSteps({ run: shellRun(cwd), steps, tier: 'fast' })
156
+ writeReport(cwd, '.geonosis/gate-report.json', report)
157
+ ```
158
+
159
+ ## What this cannot see about itself
160
+
161
+ - **It does not know whether your steps measure anything.** `verify` reports what your commands
162
+ exited with; whether `pnpm lint` was pointed at the right directory is between you and the
163
+ ratchet's `--prove`.
164
+ - **`.geonosis/` is runner-owned.** The `geonosis` Claude Code plugin refuses agent writes there
165
+ (D-007) — the scored agent never writes the scoreboard. Nothing in this package enforces that.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // Committed, so `pnpm install` can link the bin on a fresh clone — before `pnpm build` has
3
+ // produced dist/. A bin that only exists after a build is a bin that is missing when you need it.
4
+ import '../dist/cli.js'
@@ -0,0 +1,249 @@
1
+ // src/config.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { resolve } from "path";
4
+ var CONFIG_FILE = "geonosis.json";
5
+ var loadVerifyConfig = (cwd) => {
6
+ const path = resolve(cwd, CONFIG_FILE);
7
+ if (!existsSync(path)) {
8
+ throw new Error(`no ${CONFIG_FILE} in ${cwd} \u2014 verify has no tiers to run`);
9
+ }
10
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
11
+ const verify = parsed.verify;
12
+ if (typeof verify !== "object" || verify === null || Array.isArray(verify)) {
13
+ throw new Error(`${CONFIG_FILE} has no "verify" object \u2014 verify has no tiers to run`);
14
+ }
15
+ const tiers = {};
16
+ for (const [tier, steps] of Object.entries(verify)) {
17
+ if (!Array.isArray(steps) || steps.some((one) => typeof one !== "string")) {
18
+ throw new Error(`${CONFIG_FILE}: tier "${tier}" must be a list of shell commands`);
19
+ }
20
+ tiers[tier] = steps;
21
+ }
22
+ return { tiers };
23
+ };
24
+ var known = (config) => Object.keys(config.tiers).toSorted().join(", ");
25
+ var resolveTier = (config, tier, path = []) => {
26
+ if (path.includes(tier)) {
27
+ throw new Error(
28
+ `${CONFIG_FILE}: tier "${tier}" inlines itself \u2014 ${[...path, tier].join(" -> ")}`
29
+ );
30
+ }
31
+ const steps = config.tiers[tier];
32
+ if (steps === void 0) {
33
+ throw new Error(
34
+ `${CONFIG_FILE}: no "${tier}" tier under "verify" \u2014 known tiers: ${known(config)}`
35
+ );
36
+ }
37
+ return steps.flatMap(
38
+ (step) => step in config.tiers ? resolveTier(config, step, [...path, tier]) : [{ command: step, tier }]
39
+ );
40
+ };
41
+
42
+ // src/prove.ts
43
+ import { spawnSync } from "child_process";
44
+ import { mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
45
+ import { tmpdir } from "os";
46
+ import { join } from "path";
47
+ var RED_STEP = "exit 3";
48
+ var GREEN_STEP = "echo the-step-that-passes";
49
+ var check = (claim, held, saw) => held ? [] : [` ${claim} \u2014 saw ${saw}`];
50
+ var prove = ({ entry, execPath }) => {
51
+ const root = mkdtempSync(join(tmpdir(), "geonosis-verify-prove-"));
52
+ try {
53
+ writeFileSync(
54
+ join(root, "geonosis.json"),
55
+ JSON.stringify({ verify: { fast: [GREEN_STEP, RED_STEP] } }, null, 2)
56
+ );
57
+ const done = spawnSync(execPath, [entry, "fast", "--report", "report.json"], {
58
+ cwd: root,
59
+ encoding: "utf8"
60
+ });
61
+ const code = done.status ?? -1;
62
+ let report;
63
+ try {
64
+ report = JSON.parse(readFileSync2(join(root, "report.json"), "utf8"));
65
+ } catch {
66
+ return {
67
+ message: `NOT PROVEN \u2014 the planted run wrote no readable report (exit ${code})`,
68
+ ok: false
69
+ };
70
+ }
71
+ const red = report.steps[1];
72
+ const green = report.steps[0];
73
+ const failures = [
74
+ ...check("a failed step exits 1", code === 1, `exit ${code}`),
75
+ ...check("the report is red", report.ok === false, `ok ${String(report.ok)}`),
76
+ ...check(
77
+ "the passing step passed",
78
+ green?.ok === true,
79
+ `${green?.command} ok ${String(green?.ok)}`
80
+ ),
81
+ ...check("the failing step is named", red?.command === RED_STEP, String(red?.command)),
82
+ ...check("the failing step kept its code", red?.exitCode === 3, String(red?.exitCode))
83
+ ];
84
+ if (failures.length > 0) return { message: `NOT PROVEN
85
+ ${failures.join("\n")}`, ok: false };
86
+ return {
87
+ message: `PROVEN \u2014 a planted "${RED_STEP}" step reached the report and exited 1`,
88
+ ok: true
89
+ };
90
+ } finally {
91
+ rmSync(root, { force: true, recursive: true });
92
+ }
93
+ };
94
+
95
+ // src/report.ts
96
+ import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
97
+ import { dirname, resolve as resolve2 } from "path";
98
+ var DEFAULT_REPORT = ".geonosis/gate-report.json";
99
+ var TAIL_LINES = 40;
100
+ var NEVER_RAN = -1;
101
+ var ANSI = /\[[0-9;]*m/g;
102
+ var lastLines = (output, limit = TAIL_LINES) => output.replaceAll(ANSI, "").replace(/\n+$/, "").split("\n").slice(-limit).join("\n");
103
+ var writeReport = (cwd, path, report) => {
104
+ const full = resolve2(cwd, path);
105
+ mkdirSync(dirname(full), { recursive: true });
106
+ writeFileSync2(full, `${JSON.stringify(report, null, 2)}
107
+ `);
108
+ return full;
109
+ };
110
+
111
+ // src/run.ts
112
+ import { spawnSync as spawnSync2 } from "child_process";
113
+ var shellRun = (cwd) => (command) => {
114
+ const done = spawnSync2(`(
115
+ ${command}
116
+ ) 2>&1`, { cwd, encoding: "utf8", shell: true });
117
+ return { exitCode: done.status ?? NEVER_RAN, output: done.stdout ?? "" };
118
+ };
119
+ var numbering = () => {
120
+ const seen = /* @__PURE__ */ new Map();
121
+ return (tier) => {
122
+ const next = (seen.get(tier) ?? 0) + 1;
123
+ seen.set(tier, next);
124
+ return `${tier}/${next}`;
125
+ };
126
+ };
127
+ var skipped = (id, command) => ({
128
+ command,
129
+ exitCode: NEVER_RAN,
130
+ id,
131
+ ms: 0,
132
+ ok: false,
133
+ skipped: true,
134
+ tail: ""
135
+ });
136
+ var runSteps = ({
137
+ run,
138
+ steps: planned,
139
+ tier
140
+ }) => {
141
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
142
+ const idOf = numbering();
143
+ const steps = [];
144
+ let stopped = false;
145
+ for (const { command, tier: from } of planned) {
146
+ const id = idOf(from);
147
+ if (stopped) {
148
+ steps.push(skipped(id, command));
149
+ continue;
150
+ }
151
+ const at = Date.now();
152
+ const { exitCode, output } = run(command);
153
+ const ok = exitCode === 0;
154
+ steps.push({ command, exitCode, id, ms: Date.now() - at, ok, tail: lastLines(output) });
155
+ stopped = !ok;
156
+ }
157
+ return {
158
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
159
+ ok: steps.every((one) => one.ok),
160
+ startedAt,
161
+ steps,
162
+ tier
163
+ };
164
+ };
165
+
166
+ // src/stats.ts
167
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
168
+ import { dirname as dirname2, resolve as resolve3 } from "path";
169
+ var TURNS_FILE = ".geonosis/stop-turns.json";
170
+ var isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
171
+ var readDays = (root) => {
172
+ const at = resolve3(root, TURNS_FILE);
173
+ if (!existsSync2(at)) return {};
174
+ let parsed;
175
+ try {
176
+ parsed = JSON.parse(readFileSync3(at, "utf8"));
177
+ } catch (error) {
178
+ throw new Error(`${TURNS_FILE} is not JSON: ${error.message}`, { cause: error });
179
+ }
180
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
181
+ throw new Error(`${TURNS_FILE} must hold an object of days`);
182
+ }
183
+ const days = {};
184
+ for (const [day, value] of Object.entries(parsed)) {
185
+ const row = value;
186
+ if (!isCount(row.blocked) || !isCount(row.turns)) {
187
+ throw new Error(`${TURNS_FILE}: ${day} has no readable turn and block counts`);
188
+ }
189
+ days[day] = { blocked: row.blocked, turns: row.turns };
190
+ }
191
+ return days;
192
+ };
193
+ var windowOf = (days) => {
194
+ const turns = days.reduce((total, [, one]) => total + one.turns, 0);
195
+ const blocked = days.reduce((total, [, one]) => total + one.blocked, 0);
196
+ return { blocked, passRate: turns === 0 ? void 0 : (turns - blocked) / turns, turns };
197
+ };
198
+ var readStats = (root, since) => {
199
+ const days = Object.entries(readDays(root));
200
+ if (since === void 0) return windowOf(days);
201
+ return {
202
+ ...windowOf(days.filter(([day]) => day >= since)),
203
+ before: windowOf(days.filter(([day]) => day < since)),
204
+ since
205
+ };
206
+ };
207
+ var percent = (rate) => rate === void 0 ? "no turns recorded" : `${(rate * 100).toFixed(1)} %`;
208
+ var line = (label, window) => ` ${label.padEnd(10)} ${String(window.turns).padStart(6)} turns \xB7 ${String(window.blocked).padStart(6)} blocked \xB7 ${percent(window.passRate)} first try`;
209
+ var formatStats = (stats) => {
210
+ if (stats.turns === 0 && stats.before === void 0) {
211
+ return `first-try pass rate: no turns recorded \u2014 the Stop hook has not written ${TURNS_FILE} here yet`;
212
+ }
213
+ return [
214
+ "first-try pass rate \u2014 the share of turn-ends whose fast tier was green",
215
+ ...stats.before === void 0 ? [] : [line("before", stats.before)],
216
+ line(stats.since === void 0 ? "all" : `${stats.since}+`, stats)
217
+ ].join("\n");
218
+ };
219
+ var recordTurn = ({
220
+ blocked,
221
+ day,
222
+ root
223
+ }) => {
224
+ const days = readDays(root);
225
+ const seen = days[day] ?? { blocked: 0, turns: 0 };
226
+ days[day] = { blocked: seen.blocked + (blocked ? 1 : 0), turns: seen.turns + 1 };
227
+ const at = resolve3(root, TURNS_FILE);
228
+ mkdirSync2(dirname2(at), { recursive: true });
229
+ writeFileSync3(at, `${JSON.stringify(days, null, 2)}
230
+ `);
231
+ };
232
+
233
+ export {
234
+ CONFIG_FILE,
235
+ loadVerifyConfig,
236
+ resolveTier,
237
+ prove,
238
+ DEFAULT_REPORT,
239
+ TAIL_LINES,
240
+ NEVER_RAN,
241
+ lastLines,
242
+ writeReport,
243
+ shellRun,
244
+ runSteps,
245
+ TURNS_FILE,
246
+ readStats,
247
+ formatStats,
248
+ recordTurn
249
+ };
package/dist/cli.js ADDED
@@ -0,0 +1,129 @@
1
+ import {
2
+ DEFAULT_REPORT,
3
+ formatStats,
4
+ loadVerifyConfig,
5
+ prove,
6
+ readStats,
7
+ resolveTier,
8
+ runSteps,
9
+ shellRun,
10
+ writeReport
11
+ } from "./chunk-4HXX3SXM.js";
12
+
13
+ // src/cli.ts
14
+ import { acquireExclusive } from "@geonosis/ratchet";
15
+ var REFUSED = 2;
16
+ var USAGE = "usage: geonosis-verify <tier> [--report <path>] [--exclusive] [--exclusive-timeout <seconds>] | --prove | stats [--since <YYYY-MM-DD>] [--json]";
17
+ var refuse = (message) => {
18
+ process.stderr.write(`geonosis-verify: ${message}
19
+ `);
20
+ process.exit(REFUSED);
21
+ };
22
+ var args = process.argv.slice(2);
23
+ if (args.includes("--prove")) {
24
+ const proof = prove({ entry: process.argv[1] ?? "", execPath: process.execPath });
25
+ process.stdout.write(`${proof.message}
26
+ `);
27
+ process.exit(proof.ok ? 0 : REFUSED);
28
+ }
29
+ if (args[0] === "stats") {
30
+ const rest = args.slice(1);
31
+ let since;
32
+ for (let at = 0; at < rest.length; at += 1) {
33
+ const arg = rest[at] ?? "";
34
+ if (arg === "--since") {
35
+ const next = rest[at + 1];
36
+ if (next === void 0 || next.startsWith("--")) refuse("--since needs a YYYY-MM-DD date");
37
+ since = next;
38
+ at += 1;
39
+ } else if (arg !== "--json") {
40
+ refuse(`unknown option "${arg}" \u2014 ${USAGE}`);
41
+ }
42
+ }
43
+ try {
44
+ const stats = readStats(process.cwd(), since);
45
+ process.stdout.write(
46
+ rest.includes("--json") ? `${JSON.stringify(stats, void 0, 2)}
47
+ ` : `${formatStats(stats)}
48
+ `
49
+ );
50
+ } catch (error) {
51
+ refuse(error.message);
52
+ }
53
+ process.exit(0);
54
+ }
55
+ var tier = "";
56
+ var reportPath = DEFAULT_REPORT;
57
+ var exclusive = false;
58
+ var timeoutSeconds;
59
+ var valueAfter = (at, flag) => {
60
+ const next = args[at + 1];
61
+ if (next === void 0 || next.startsWith("--")) refuse(`${flag} needs a value`);
62
+ return next ?? "";
63
+ };
64
+ for (let at = 0; at < args.length; at += 1) {
65
+ const arg = args[at] ?? "";
66
+ if (arg === "--report") {
67
+ reportPath = valueAfter(at, "--report");
68
+ at += 1;
69
+ } else if (arg === "--exclusive") {
70
+ exclusive = true;
71
+ } else if (arg === "--exclusive-timeout") {
72
+ const seconds = Number(valueAfter(at, "--exclusive-timeout"));
73
+ if (!(seconds > 0)) refuse("--exclusive-timeout needs a number of seconds");
74
+ timeoutSeconds = seconds;
75
+ at += 1;
76
+ } else if (arg.startsWith("-")) {
77
+ refuse(`unknown option "${arg}" \u2014 ${USAGE}`);
78
+ } else if (tier === "") {
79
+ tier = arg;
80
+ } else {
81
+ refuse(`one tier at a time \u2014 got "${tier}" and "${arg}"`);
82
+ }
83
+ }
84
+ if (tier === "") refuse(`name a tier \u2014 ${USAGE}`);
85
+ var cwd = process.cwd();
86
+ var steps = [];
87
+ try {
88
+ steps = resolveTier(loadVerifyConfig(cwd), tier);
89
+ } catch (error) {
90
+ refuse(error.message);
91
+ }
92
+ var release = () => void 0;
93
+ if (exclusive) {
94
+ try {
95
+ release = await acquireExclusive(timeoutSeconds === void 0 ? {} : { timeoutSeconds });
96
+ } catch (error) {
97
+ refuse(error.message);
98
+ }
99
+ }
100
+ var giveBack = () => {
101
+ release();
102
+ process.exit(130);
103
+ };
104
+ process.on("SIGINT", giveBack);
105
+ process.on("SIGTERM", giveBack);
106
+ var code = REFUSED;
107
+ try {
108
+ const report = runSteps({ run: shellRun(cwd), steps, tier });
109
+ for (const step of report.steps) {
110
+ const verdict = step.skipped ? "skip" : step.ok ? "ok " : "FAIL";
111
+ process.stdout.write(` ${verdict} ${step.id} ${step.command} (${step.ms} ms)
112
+ `);
113
+ }
114
+ try {
115
+ const at = writeReport(cwd, reportPath, report);
116
+ process.stdout.write(`${report.ok ? "verify PASS" : "verify FAIL"} \u2014 ${tier} \u2014 ${at}
117
+ `);
118
+ code = report.ok ? 0 : 1;
119
+ } catch (error) {
120
+ process.stderr.write(
121
+ `geonosis-verify: could not write ${reportPath}: ${error.message}
122
+ `
123
+ );
124
+ code = REFUSED;
125
+ }
126
+ } finally {
127
+ release();
128
+ }
129
+ process.exit(code);
package/dist/index.js ADDED
@@ -0,0 +1,34 @@
1
+ import {
2
+ CONFIG_FILE,
3
+ DEFAULT_REPORT,
4
+ NEVER_RAN,
5
+ TAIL_LINES,
6
+ TURNS_FILE,
7
+ formatStats,
8
+ lastLines,
9
+ loadVerifyConfig,
10
+ prove,
11
+ readStats,
12
+ recordTurn,
13
+ resolveTier,
14
+ runSteps,
15
+ shellRun,
16
+ writeReport
17
+ } from "./chunk-4HXX3SXM.js";
18
+ export {
19
+ CONFIG_FILE,
20
+ DEFAULT_REPORT,
21
+ NEVER_RAN,
22
+ TAIL_LINES,
23
+ TURNS_FILE,
24
+ formatStats,
25
+ lastLines,
26
+ loadVerifyConfig,
27
+ prove,
28
+ readStats,
29
+ recordTurn,
30
+ resolveTier,
31
+ runSteps,
32
+ shellRun,
33
+ writeReport
34
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@geonosis/verify",
3
+ "version": "1.0.0",
4
+ "description": "One gate runner — tiers of shell steps, run serially, recorded as a JSON gate report.",
5
+ "keywords": [
6
+ "gate",
7
+ "ci",
8
+ "verify",
9
+ "tiers",
10
+ "report",
11
+ "hooks"
12
+ ],
13
+ "homepage": "https://github.com/microcompanies/geonosis/tree/main/packages/verify",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/microcompanies/geonosis.git",
17
+ "directory": "packages/verify"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "type": "module",
21
+ "main": "dist/index.js",
22
+ "bin": {
23
+ "geonosis-verify": "bin/geonosis-verify.mjs"
24
+ },
25
+ "exports": {
26
+ ".": "./dist/index.js"
27
+ },
28
+ "files": [
29
+ "bin",
30
+ "dist"
31
+ ],
32
+ "dependencies": {
33
+ "@geonosis/ratchet": "1.0.0"
34
+ },
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup",
43
+ "typecheck": "tsc --noEmit"
44
+ }
45
+ }