axstack 0.66.0 → 0.68.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/README.md +3 -3
- package/docs/host-operations.md +8 -8
- package/docs/installation.md +8 -8
- package/docs/workflows.md +5 -9
- package/package.json +2 -2
- package/skills/axstack/references/automations.md +11 -19
- package/skills/axstack/references/autopilot.md +1 -0
- package/skills/axstack/references/candidate-publication.md +7 -12
- package/skills/axstack/references/capture-receipts.md +22 -0
- package/skills/axstack/references/fleet-verification.md +3 -3
- package/skills/axstack/references/lifecycle.md +2 -2
- package/skills/axstack/references/live-run.md +59 -0
- package/skills/axstack/references/pr-shape.md +14 -9
- package/skills/axstack/references/review-manager-prompt.md +37 -19
- package/skills/axstack/references/run-record.md +2 -2
- package/skills/axstack/references/schedule-policy.json +123 -0
- package/skills/axstack/references/t3-runtime.md +5 -5
- package/skills/axstack/references/test-audit-weekly.md +1 -2
- package/skills/axstack/references/ui-verification.md +5 -3
- package/skills/axstack/references/workspace-hygiene.md +12 -3
- package/skills/axstack/sandbox/Dockerfile +28 -0
- package/skills/axstack/sandbox/host-execution.md +14 -0
- package/skills/axstack/sandbox/inventory.json +503 -0
- package/skills/axstack/sandbox/launcher-capture.js +63 -0
- package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
- package/skills/axstack/sandbox/launcher-contracts.js +35 -0
- package/skills/axstack/sandbox/launcher-docker.js +75 -0
- package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
- package/skills/axstack/sandbox/launcher-host.js +165 -0
- package/skills/axstack/sandbox/launcher-host.json +5 -0
- package/skills/axstack/sandbox/launcher-image.json +4 -0
- package/skills/axstack/sandbox/launcher-interface.md +7 -0
- package/skills/axstack/sandbox/launcher-policy.js +135 -0
- package/skills/axstack/sandbox/launcher-policy.json +121 -0
- package/skills/axstack/sandbox/launcher-runtime.js +157 -0
- package/skills/axstack/sandbox/launcher-source.js +72 -0
- package/skills/axstack/sandbox/launcher.js +106 -0
- package/skills/axstack/sandbox/network-address.js +39 -0
- package/skills/axstack/sandbox/network-firewall.js +81 -0
- package/skills/axstack/sandbox/network-rules.js +86 -0
- package/skills/axstack/sandbox/network-runtime.js +109 -0
- package/skills/axstack/sandbox/network.js +49 -0
- package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
- package/skills/axstack/sandbox/probes-check.js +185 -0
- package/skills/axstack/sandbox/probes-exec.js +20 -0
- package/skills/axstack/sandbox/probes-image-build.js +129 -0
- package/skills/axstack/sandbox/probes-image-pins.json +370 -0
- package/skills/axstack/sandbox/probes-link-local.js +25 -0
- package/skills/axstack/sandbox/probes-storage.js +33 -0
- package/skills/axstack/sandbox/probes-udp.js +44 -0
- package/skills/axstack/sandbox/probes.js +239 -0
- package/skills/axstack/sandbox/proxy-command.js +6 -0
- package/skills/axstack/sandbox/proxy-config.json +9 -0
- package/skills/axstack/sandbox/proxy-dns.js +114 -0
- package/skills/axstack/sandbox/proxy-policy.js +22 -0
- package/skills/axstack/sandbox/proxy.js +119 -0
- package/skills/axstack/sandbox/reap.md +7 -0
- package/skills/axstack/sandbox/sidecars.json +153 -0
- package/skills/axstack/sandbox/storage-checks.js +39 -0
- package/skills/axstack/sandbox/storage-cleanup.js +49 -0
- package/skills/axstack/sandbox/storage-execution.js +110 -0
- package/skills/axstack/sandbox/storage-plan.js +78 -0
- package/skills/axstack/sandbox/storage-support.js +91 -0
- package/skills/axstack/sandbox/storage.js +75 -0
- package/skills/axstack/scripts/archive-evidence.js +2 -2
- package/skills/axstack/scripts/capture-identity.js +122 -0
- package/skills/axstack/scripts/check-run.js +248 -0
- package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
- package/skills/axstack/scripts/command-capture.js +81 -0
- package/skills/axstack/scripts/evidence-inspector.js +182 -0
- package/skills/axstack/scripts/git-argv.js +6 -0
- package/skills/axstack/scripts/image-evidence.js +183 -0
- package/skills/axstack/scripts/pr-shape.js +206 -22
- package/skills/axstack/scripts/readiness-run.js +3 -75
- package/skills/axstack/scripts/readiness.js +2 -2
- package/skills/axstack/scripts/run-init.js +13 -11
- package/skills/axstack/scripts/schedule-drift.js +132 -0
- package/skills/axstack/scripts/scratch.js +201 -0
- package/skills/axstack-audit/SKILL.md +2 -0
- package/skills/axstack-audit/references/record.md +1 -1
- package/skills/axstack-explain/references/inline-pages.md +8 -4
- package/skills/axstack-implement/SKILL.md +6 -5
- package/skills/axstack-review/references/candidate-brief.md +12 -21
- package/skills/axstack-review/references/codebase-brief.md +1 -0
- package/skills/axstack-review/references/codebase-mode.md +4 -1
- package/skills/axstack-review/references/codebase-report.md +2 -1
- package/skills/axstack-review/references/review-candidate.md +2 -2
- package/skills/axstack-review/references/review-receipt.md +8 -3
- package/skills/axstack-verify/SKILL.md +18 -5
- package/skills/axstack-watch/references/proven-verification.md +3 -2
- package/skills/axstack-watch/references/readiness.md +56 -61
- package/skills/voa/references/verification.md +5 -2
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
import { gitArgv } from './git-argv.js';
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
1
|
+
import { gitArgv, gitEnv } from './git-argv.js';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
3
|
|
|
4
4
|
const lockfiles = ['bun.lock', 'bun.lockb', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock'];
|
|
5
|
-
const
|
|
6
|
-
|
|
5
|
+
const sandboxDirectory = 'skills/axstack/sandbox';
|
|
6
|
+
const sandboxPrefix = `${sandboxDirectory}/`;
|
|
7
|
+
const help = `Usage: bun scripts/pr-shape.js --base <ref> --head <ref> --repo <path>
|
|
8
|
+
Example: bun scripts/pr-shape.js --base main --head HEAD --repo /path/to/repo
|
|
7
9
|
|
|
8
10
|
--base Required actual PR base (parent branch for a stacked child)
|
|
9
11
|
--head Required candidate commit or branch
|
|
12
|
+
--repo Required Git checkout path; run the installed helper from a trusted cwd
|
|
10
13
|
--source Optional source ref for the read-only sync term; no source means n/a
|
|
11
14
|
--help Show flags, example, bucket definitions and exit codes
|
|
12
15
|
|
|
@@ -14,6 +17,7 @@ Read-only Git; writes nothing, retains no state. Prints a bounded JSON summary:
|
|
|
14
17
|
input refs and resolved SHAs, merge-base, full additions/deletions, rename and
|
|
15
18
|
binary counts, and overlapping lockfile/generated buckets, with status and
|
|
16
19
|
reproducing argv plus calculation instructions. No path inventory is emitted.
|
|
20
|
+
For untrusted checkouts, use --repo from a trusted cwd with bun --no-env-file.
|
|
17
21
|
Lockfiles match these exact basenames at any depth: ${lockfiles.join(', ')}.
|
|
18
22
|
Generated means linguist-generated set or true in .gitattributes at the head;
|
|
19
23
|
uses the destination path for renames. Unset, false and unspecified are excluded.
|
|
@@ -21,6 +25,10 @@ Ignores system/global attributes; local info/attributes causes an unknown bucket
|
|
|
21
25
|
Never subtract buckets; formatter-only changes require manual disclosure.
|
|
22
26
|
Sync reports B <= H AND (H <= S OR (B <= S AND H tree == S tree)).
|
|
23
27
|
Ancestor exit 1 means fail; other Git errors or missing source objects mean unknown.
|
|
28
|
+
Shape term sandbox-path: fail (user-merge hold) when either rename endpoint or
|
|
29
|
+
another changed path equals ${sandboxDirectory} or starts with ${sandboxPrefix}; otherwise pass.
|
|
30
|
+
Shape diff overrides submodule-ignore settings so committed gitlink changes stay visible.
|
|
31
|
+
Unavailable path evidence is unknown, including Git errors (existing exits retained).
|
|
24
32
|
No term grants authority. No cohesion or approval verdict.
|
|
25
33
|
Exit codes: 0 measured (including failed terms), 1 input/Git error,
|
|
26
34
|
2 incomplete (unknown sync, no merge-base or unavailable committed-attribute evidence).
|
|
@@ -28,24 +36,26 @@ Exit codes: 0 measured (including failed terms), 1 input/Git error,
|
|
|
28
36
|
|
|
29
37
|
function optionsFrom(argv) {
|
|
30
38
|
const options = {};
|
|
39
|
+
const missing = (flag) => new Error(flag === '--repo'
|
|
40
|
+
? 'missing path; pass --repo <Git-checkout-path>' : `missing ref; pass ${flag} <commit-or-branch>`);
|
|
31
41
|
for (let i = 0; i < argv.length; i += 2) {
|
|
32
42
|
const flag = argv[i];
|
|
33
|
-
if (!['--base', '--head', '--source'].includes(flag)) throw new Error(`unexpected argument ${flag}; use --help`);
|
|
43
|
+
if (!['--base', '--head', '--source', '--repo'].includes(flag)) throw new Error(`unexpected argument ${flag}; use --help`);
|
|
34
44
|
const value = argv[i + 1];
|
|
35
|
-
if (!value || value.startsWith('-')) throw
|
|
45
|
+
if (!value || value.startsWith('-')) throw missing(flag);
|
|
36
46
|
if (flag in options) throw new Error(`duplicate ${flag}; pass it once`);
|
|
37
47
|
options[flag] = value;
|
|
38
48
|
}
|
|
39
|
-
for (const flag of ['--base', '--head']) {
|
|
40
|
-
if (!options[flag]) throw
|
|
49
|
+
for (const flag of ['--base', '--head', '--repo']) {
|
|
50
|
+
if (!options[flag]) throw missing(flag);
|
|
41
51
|
}
|
|
42
52
|
return options;
|
|
43
53
|
}
|
|
44
54
|
|
|
45
|
-
const command = (...args) => gitArgv('-c', 'core.attributesFile=/dev/null', ...args);
|
|
55
|
+
const command = (repo, ...args) => gitArgv('-c', 'core.attributesFile=/dev/null', '-C', repo, ...args);
|
|
46
56
|
function run(argv, input) {
|
|
47
57
|
const result = Bun.spawnSync(argv, { stdin: input === undefined ? 'ignore' : new TextEncoder().encode(input),
|
|
48
|
-
stdout: 'pipe', stderr: 'pipe', env: { ...
|
|
58
|
+
stdout: 'pipe', stderr: 'pipe', env: { ...gitEnv(), GIT_ATTR_NOSYSTEM: '1' } });
|
|
49
59
|
return { code: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() };
|
|
50
60
|
}
|
|
51
61
|
|
|
@@ -85,8 +95,9 @@ function numstat(text) {
|
|
|
85
95
|
const added = tokens[i].slice(0, firstTab), deleted = tokens[i].slice(firstTab + 1, secondTab);
|
|
86
96
|
let path = tokens[i].slice(secondTab + 1);
|
|
87
97
|
const renamed = path === '';
|
|
88
|
-
|
|
89
|
-
|
|
98
|
+
let sourcePath;
|
|
99
|
+
if (renamed) { sourcePath = tokens[++i]; path = tokens[++i]; } // -z rename: empty path, old path, new path.
|
|
100
|
+
rows.push({ path, sourcePath, renamed, binary: added === '-', additions: added === '-' ? 0 : Number(added),
|
|
90
101
|
deletions: deleted === '-' ? 0 : Number(deleted) });
|
|
91
102
|
}
|
|
92
103
|
return rows;
|
|
@@ -106,16 +117,179 @@ function summarize(rows, evidence) {
|
|
|
106
117
|
} } };
|
|
107
118
|
}
|
|
108
119
|
|
|
120
|
+
const proofFields = { files: 'Files', additions: 'Lines added', deletions: 'Lines removed',
|
|
121
|
+
commits: 'Commits', head: 'Head SHA', base: 'Base SHA' };
|
|
122
|
+
const proofHelp = `Usage: bun scripts/pr-shape.js --proof --repo <path> --base <ref> --head <ref> [--body <path>]
|
|
123
|
+
bun scripts/pr-shape.js --proof --pr <number> --repo <owner/repo> [--body <path>]
|
|
124
|
+
|
|
125
|
+
--proof Render/check PR Proof facts (separate from the unchanged shape mode)
|
|
126
|
+
--base Actual current PR base ref, resolved with read-only Git
|
|
127
|
+
--head Current candidate ref, resolved with read-only Git
|
|
128
|
+
--body Optional UTF-8 PR body file to check; never modified
|
|
129
|
+
--pr Positive PR number; read-only gh api fetches current facts and body
|
|
130
|
+
--repo Required Git checkout path, or owner/repo with --pr; --pr excludes --base/--head
|
|
131
|
+
--help Show this mode's flags, output and exit codes
|
|
132
|
+
|
|
133
|
+
JSON: block (Markdown or null if facts unavailable), terms (each status, value,
|
|
134
|
+
evidence including reproducing commands, separate child exit codes/errors,
|
|
135
|
+
and stated body values when checked).
|
|
136
|
+
Git counts use the merge-base diff (-M numstat; binary lines count as zero),
|
|
137
|
+
and commits reachable from head but not base. PR mode reads REST pull facts,
|
|
138
|
+
including numeric commits (no truncated commit-list pagination), then resolves
|
|
139
|
+
the live base tip via git/ref/heads/<base.ref>. Evidence keeps snapshot/live SHAs.
|
|
140
|
+
No --body in Git mode renders only; PR mode checks the fetched body by default.
|
|
141
|
+
Checks require exactly one <!-- axstack:proof --> ... <!-- /axstack:proof -->
|
|
142
|
+
block and one line per field: Files, Lines added, Lines removed, Commits,
|
|
143
|
+
Head SHA, Base SHA. Counts must match; SHA prefixes need at least 7 hex digits.
|
|
144
|
+
Other prose and SHAs are ignored. Refresh refs before checking a local candidate.
|
|
145
|
+
Missing/duplicate/invalid body facts fail; unavailable Git/gh/body data is unknown.
|
|
146
|
+
This fact mode is read-only and stateless: writes nothing, grants no authority,
|
|
147
|
+
and supplies no aggregate verdict. No dispatch, retry, scheduling or merge.
|
|
148
|
+
Exit codes: 0 measured (including failed terms), 1 invalid input,
|
|
149
|
+
2 incomplete (one or more unknown terms).
|
|
150
|
+
`;
|
|
151
|
+
|
|
152
|
+
function proofOptions(argv) {
|
|
153
|
+
const options = {};
|
|
154
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
155
|
+
const flag = argv[i], value = argv[i + 1];
|
|
156
|
+
if (!['--base', '--head', '--body', '--pr', '--repo'].includes(flag) ||
|
|
157
|
+
!value || value.startsWith('-') || flag in options) throw Error(`invalid proof argument ${flag}; use --proof --help`);
|
|
158
|
+
options[flag] = value;
|
|
159
|
+
}
|
|
160
|
+
if (options['--pr']) {
|
|
161
|
+
if (!/^[1-9]\d*$/.test(options['--pr']) || !/^[\w.-]+\/[\w.-]+$/.test(options['--repo'] ?? '') ||
|
|
162
|
+
options['--base'] || options['--head']) throw Error('--pr requires --repo owner/repo and excludes --base/--head');
|
|
163
|
+
} else if (!options['--base'] || !options['--head'] || !options['--repo']) {
|
|
164
|
+
throw Error('proof requires --repo with --base and --head, or --pr');
|
|
165
|
+
}
|
|
166
|
+
return options;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function proof(argv, io) {
|
|
170
|
+
if (argv.includes('--help')) { io.stdout(proofHelp); return 0; }
|
|
171
|
+
const options = proofOptions(argv);
|
|
172
|
+
const terms = Object.keys(proofFields).map((id) => ({ id, status: 'unknown', value: null,
|
|
173
|
+
evidence: { cwd: options['--pr'] ? process.cwd() : options['--repo'], commands: [], results: [], reason: 'data unavailable' } }));
|
|
174
|
+
const term = (id) => terms.find((t) => t.id === id);
|
|
175
|
+
const query = (ids, args) => {
|
|
176
|
+
for (const id of ids) term(id).evidence.commands.push(args);
|
|
177
|
+
try {
|
|
178
|
+
const result = run(args);
|
|
179
|
+
for (const id of ids) term(id).evidence.results.push({ exitCode: result.code, stderr: result.stderr.trim() });
|
|
180
|
+
if (result.code) {
|
|
181
|
+
for (const id of ids) term(id).evidence.reason = result.stderr.trim() || `command exit ${result.code}`;
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
return result.stdout;
|
|
185
|
+
} catch (error) {
|
|
186
|
+
for (const id of ids) {
|
|
187
|
+
term(id).evidence.results.push({ exitCode: null, error: error.message });
|
|
188
|
+
term(id).evidence.reason = error.message;
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const assign = (id, value) => {
|
|
194
|
+
const valid = ['head', 'base'].includes(id) ? /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i.test(value ?? '')
|
|
195
|
+
: Number.isSafeInteger(value) && value >= 0;
|
|
196
|
+
if (valid) Object.assign(term(id), { status: 'pass', value, evidence: { ...term(id).evidence, reason: 'observed current fact' } });
|
|
197
|
+
};
|
|
198
|
+
let body, bodyError;
|
|
199
|
+
if (options['--pr']) {
|
|
200
|
+
const raw = query(Object.keys(proofFields), ['gh', 'api', `repos/${options['--repo']}/pulls/${options['--pr']}`]);
|
|
201
|
+
try {
|
|
202
|
+
const data = JSON.parse(raw ?? '{}');
|
|
203
|
+
for (const [id, value] of Object.entries({ files: data.changed_files, additions: data.additions,
|
|
204
|
+
deletions: data.deletions, commits: data.commits, head: data.head?.sha })) assign(id, value);
|
|
205
|
+
const base = term('base');
|
|
206
|
+
Object.assign(base.evidence, { snapshotSha: data.base?.sha ?? null, liveSha: null,
|
|
207
|
+
baseRef: typeof data.base?.ref === 'string' ? data.base.ref : null });
|
|
208
|
+
if (base.evidence.baseRef) {
|
|
209
|
+
const ref = base.evidence.baseRef.split('/').map(encodeURIComponent).join('/');
|
|
210
|
+
const live = query(['base'], ['gh', 'api', `repos/${options['--repo']}/git/ref/heads/${ref}`]);
|
|
211
|
+
if (live !== null) {
|
|
212
|
+
try {
|
|
213
|
+
base.evidence.liveSha = JSON.parse(live)?.object?.sha ?? null;
|
|
214
|
+
base.evidence.reason = 'live base ref response has no valid commit SHA';
|
|
215
|
+
assign('base', base.evidence.liveSha);
|
|
216
|
+
} catch { base.evidence.reason = 'invalid live base ref JSON response'; }
|
|
217
|
+
}
|
|
218
|
+
} else base.evidence.reason = 'PR base.ref unavailable; cannot resolve live base tip';
|
|
219
|
+
if (typeof data.body === 'string') body = data.body;
|
|
220
|
+
else bodyError = 'PR body unavailable in gh response';
|
|
221
|
+
} catch { bodyError = 'invalid gh JSON response'; }
|
|
222
|
+
} else {
|
|
223
|
+
const gitCommand = (...args) => command(options['--repo'], ...args);
|
|
224
|
+
for (const id of ['base', 'head']) {
|
|
225
|
+
const raw = query([id], gitCommand('rev-parse', '--verify', '--end-of-options', `${options[`--${id}`]}^{commit}`));
|
|
226
|
+
if (raw !== null) assign(id, raw.trim());
|
|
227
|
+
}
|
|
228
|
+
const counts = ['files', 'additions', 'deletions', 'commits'];
|
|
229
|
+
if (term('base').value && term('head').value) {
|
|
230
|
+
const base = term('base').value, head = term('head').value;
|
|
231
|
+
const commits = query(['commits'], gitCommand('rev-list', '--count', `${base}..${head}`, '--'));
|
|
232
|
+
if (commits !== null && /^\d+\s*$/.test(commits)) assign('commits', Number(commits));
|
|
233
|
+
const ids = counts.slice(0, 3);
|
|
234
|
+
const merge = query(ids, gitCommand('merge-base', base, head));
|
|
235
|
+
if (merge !== null) {
|
|
236
|
+
const diff = query(ids, gitCommand('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--numstat', '-z', `${merge.trim()}..${head}`, '--'));
|
|
237
|
+
if (diff !== null) {
|
|
238
|
+
const rows = numstat(diff);
|
|
239
|
+
assign('files', rows.length);
|
|
240
|
+
assign('additions', rows.reduce((sum, row) => sum + row.additions, 0));
|
|
241
|
+
assign('deletions', rows.reduce((sum, row) => sum + row.deletions, 0));
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
} else {
|
|
245
|
+
for (const id of counts) term(id).evidence = { ...term(id).evidence,
|
|
246
|
+
commands: [...term('base').evidence.commands, ...term('head').evidence.commands],
|
|
247
|
+
results: [...term('base').evidence.results, ...term('head').evidence.results],
|
|
248
|
+
reason: 'base/head resolution unavailable; counts cannot be measured' };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const block = terms.every((t) => t.status === 'pass')
|
|
252
|
+
? ['<!-- axstack:proof -->', ...terms.map((t) => `${proofFields[t.id]}: ${t.value}`), '<!-- /axstack:proof -->'].join('\n') : null;
|
|
253
|
+
if (options['--body']) {
|
|
254
|
+
try { body = readFileSync(options['--body'], 'utf8'); bodyError = null; }
|
|
255
|
+
catch (error) { bodyError = error.message; }
|
|
256
|
+
}
|
|
257
|
+
if (options['--body'] || options['--pr']) {
|
|
258
|
+
const blocks = [...(body ?? '').matchAll(/<!-- axstack:proof -->\r?\n([\s\S]*?)\r?\n<!-- \/axstack:proof -->/g)];
|
|
259
|
+
for (const t of terms) {
|
|
260
|
+
if (options['--body']) t.evidence.bodyPath = options['--body'];
|
|
261
|
+
if (bodyError) { t.status = 'unknown'; t.evidence.reason = bodyError; continue; }
|
|
262
|
+
if (t.status === 'unknown') continue;
|
|
263
|
+
const values = blocks.length === 1 ? blocks[0][1].split(/\r?\n/)
|
|
264
|
+
.filter((line) => line.startsWith(`${proofFields[t.id]}:`)).map((line) => line.slice(proofFields[t.id].length + 1).trim()) : [];
|
|
265
|
+
t.evidence.stated = values;
|
|
266
|
+
const stated = values[0] ?? '';
|
|
267
|
+
const matches = ['base', 'head'].includes(t.id)
|
|
268
|
+
? /^[a-f0-9]{7,64}$/i.test(stated) && t.value.toLowerCase().startsWith(stated.toLowerCase())
|
|
269
|
+
: /^(0|[1-9]\d*)$/.test(stated) && Number(stated) === t.value;
|
|
270
|
+
t.status = values.length === 1 && matches ? 'pass' : 'fail';
|
|
271
|
+
t.evidence.reason = blocks.length === 0 ? 'no facts block; render with --proof and paste the returned block into the PR body'
|
|
272
|
+
: blocks.length !== 1 ? 'expected exactly one facts block' : 'compare stated value with current fact; one field required';
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
io.stdout(`${JSON.stringify({ block, terms })}\n`);
|
|
276
|
+
return terms.some((t) => t.status === 'unknown') ? 2 : 0;
|
|
277
|
+
}
|
|
278
|
+
|
|
109
279
|
export function main(argv, io = { stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }) {
|
|
280
|
+
let sandboxPath;
|
|
110
281
|
try {
|
|
111
|
-
if (argv
|
|
282
|
+
if (argv[0] === '--proof') return proof(argv.slice(1), io);
|
|
283
|
+
if (argv.includes('--help')) { io.stdout(`${help}\n${proofHelp}`); return 0; }
|
|
112
284
|
const options = optionsFrom(argv);
|
|
113
|
-
|
|
114
|
-
|
|
285
|
+
sandboxPath = { status: 'unknown', evidence: { prefix: sandboxPrefix, commands: [] } };
|
|
286
|
+
const query = (argv) => { sandboxPath.evidence.commands.push(argv); return run(argv); };
|
|
287
|
+
const root = query(command(options['--repo'], 'rev-parse', '--show-toplevel'));
|
|
288
|
+
if (root.code) throw new Error('invalid --repo; pass --repo <Git-checkout-path>');
|
|
115
289
|
const repo = root.stdout.replace(/\n$/, '');
|
|
116
|
-
const gitCommand = (...args) => command(
|
|
290
|
+
const gitCommand = (...args) => command(repo, ...args);
|
|
117
291
|
const resolve = (flag) => {
|
|
118
|
-
const result =
|
|
292
|
+
const result = query(gitCommand('rev-parse', '--verify', '--end-of-options', `${options[flag]}^{commit}`));
|
|
119
293
|
if (result.code) throw new Error(`unresolved ${flag}; pass ${flag} <existing-commit-or-branch>`);
|
|
120
294
|
return result.stdout.trim();
|
|
121
295
|
};
|
|
@@ -123,18 +297,24 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
|
|
|
123
297
|
if (options['--source']) inputs.sourceRef = options['--source'];
|
|
124
298
|
const sync = syncTerm(inputs, gitCommand);
|
|
125
299
|
const mergeCommand = gitCommand('merge-base', inputs.base, inputs.head);
|
|
126
|
-
const merge =
|
|
300
|
+
const merge = query(mergeCommand);
|
|
127
301
|
if (merge.code) {
|
|
128
302
|
const unknown = { status: 'unknown', evidence: { commands: [mergeCommand], reason: merge.stderr.trim() || 'no common ancestor' } };
|
|
129
303
|
io.stdout(`${JSON.stringify({ inputs, sync, mergeBase: { ...unknown, value: null }, totals: unknown,
|
|
130
|
-
buckets: { lockfiles: unknown, generated: unknown }
|
|
304
|
+
buckets: { lockfiles: unknown, generated: unknown },
|
|
305
|
+
'sandbox-path': { ...unknown, evidence: { ...unknown.evidence, prefix: sandboxPrefix } } })}\n`);
|
|
131
306
|
return 2;
|
|
132
307
|
}
|
|
133
308
|
const mergeBase = merge.stdout.trim();
|
|
134
|
-
const diffCommand = gitCommand('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--numstat', '-z', `${mergeBase}..${inputs.head}`, '--');
|
|
135
|
-
const diff =
|
|
309
|
+
const diffCommand = gitCommand('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--ignore-submodules=none', '--numstat', '-z', `${mergeBase}..${inputs.head}`, '--');
|
|
310
|
+
const diff = query(diffCommand);
|
|
136
311
|
if (diff.code) throw new Error(`diff unavailable; verify --base and --head refer to readable commits: ${diff.stderr.trim()}`);
|
|
137
312
|
const rows = numstat(diff.stdout);
|
|
313
|
+
const sandboxFiles = rows.filter((row) => [row.sourcePath, row.path]
|
|
314
|
+
.some((path) => path === sandboxDirectory || path?.startsWith(sandboxPrefix))).length;
|
|
315
|
+
sandboxPath = { status: sandboxFiles ? 'fail' : 'pass', evidence: { commands: [diffCommand],
|
|
316
|
+
prefix: sandboxPrefix, files: sandboxFiles,
|
|
317
|
+
reason: sandboxFiles ? 'sandbox paths touched; user merge required on the forge' : 'no sandbox paths touched' } };
|
|
138
318
|
const attrCommand = gitCommand('check-attr', `--source=${inputs.head}`, '--stdin', '-z', 'linguist-generated');
|
|
139
319
|
const attrEvidence = { commands: [diffCommand, attrCommand], environment: { GIT_ATTR_NOSYSTEM: '1' },
|
|
140
320
|
stdin: 'feed check-attr the NUL-separated destination paths from the full numstat records',
|
|
@@ -153,7 +333,8 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
|
|
|
153
333
|
}
|
|
154
334
|
generated = summarize(rows.filter((row) => paths.has(row.path)), attrEvidence);
|
|
155
335
|
}
|
|
156
|
-
io.stdout(`${JSON.stringify({ inputs, sync,
|
|
336
|
+
io.stdout(`${JSON.stringify({ inputs, sync, 'sandbox-path': sandboxPath,
|
|
337
|
+
mergeBase: { status: 'pass', value: mergeBase, evidence: { commands: [mergeCommand] } },
|
|
157
338
|
totals: summarize(rows, { commands: [diffCommand], select: 'all records; no exclusions' }),
|
|
158
339
|
buckets: { lockfiles: summarize(rows.filter((row) => lockfiles.includes(row.path.split('/').at(-1))),
|
|
159
340
|
{ commands: [diffCommand], select: 'destination basename is exactly one of lockfileNames', lockfileNames: lockfiles }), generated },
|
|
@@ -161,6 +342,9 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
|
|
|
161
342
|
})}\n`);
|
|
162
343
|
return generated.status === 'unknown' || sync.status === 'unknown' ? 2 : 0;
|
|
163
344
|
} catch (error) {
|
|
345
|
+
if (sandboxPath) io.stdout(`${JSON.stringify({ 'sandbox-path': {
|
|
346
|
+
status: 'unknown', evidence: { ...sandboxPath.evidence, reason: error.message },
|
|
347
|
+
} })}\n`);
|
|
164
348
|
io.stderr(`pr-shape error: ${error.message}\n`);
|
|
165
349
|
return 1;
|
|
166
350
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { killGroup, runCommand } from './command-capture.js';
|
|
1
2
|
import { gitArgv } from './git-argv.js';
|
|
2
|
-
import { chmodSync,
|
|
3
|
+
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
|
|
3
4
|
|
|
4
5
|
const installs = {
|
|
5
6
|
bun: ['install', '--frozen-lockfile'], npm: ['ci'],
|
|
@@ -7,85 +8,12 @@ const installs = {
|
|
|
7
8
|
};
|
|
8
9
|
/** @type {[string, string[]][]} */
|
|
9
10
|
const groups = [['env.build', ['build']], ['testing.test', ['test']], ['testing.lint-typecheck', ['lint', 'typecheck']]];
|
|
10
|
-
const drainGraceMs = 200;
|
|
11
11
|
// No shell interpolation, and the wrapper preserves the command's allowlisted env.
|
|
12
12
|
const networkWrapper = `const ip = Bun.spawnSync([process.argv[1], 'link', 'set', 'lo', 'up'], { stdin: 'ignore', stdout: 'inherit', stderr: 'inherit' });
|
|
13
13
|
if (ip.exitCode !== 0) process.exit(ip.exitCode || 1);
|
|
14
14
|
const command = Bun.spawn(process.argv.slice(2), { stdin: 'ignore', stdout: 'inherit', stderr: 'inherit' });
|
|
15
15
|
process.exit(await command.exited);`;
|
|
16
16
|
|
|
17
|
-
function killGroup(proc) {
|
|
18
|
-
try { process.kill(-proc.pid, 'SIGKILL'); }
|
|
19
|
-
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
async function runCommand(commands, paths, kind, argv, cwd, env, limits, state, spawnArgv = argv) {
|
|
23
|
-
const started = performance.now();
|
|
24
|
-
const step = { kind, argv, spawnArgv, exitCode: null, durationMs: 0, logPath: `${paths.evidence}/${crypto.randomUUID()}-${kind}.log`, timedOut: false, logBytes: 0, omittedBytes: 0, logIncomplete: false };
|
|
25
|
-
step.receiptPath = `${step.logPath.slice(0, -4)}.json`;
|
|
26
|
-
commands.push(step);
|
|
27
|
-
const fd = openSync(step.logPath, 'wx', 0o600);
|
|
28
|
-
let proc;
|
|
29
|
-
let timer;
|
|
30
|
-
let graceTimer;
|
|
31
|
-
let logging = true;
|
|
32
|
-
const readers = [];
|
|
33
|
-
function log(chunk) {
|
|
34
|
-
if (!logging) return;
|
|
35
|
-
const kept = Math.min(chunk.length, limits.logBytes - step.logBytes);
|
|
36
|
-
if (kept) writeSync(fd, chunk.subarray(0, kept));
|
|
37
|
-
step.logBytes += kept;
|
|
38
|
-
step.omittedBytes += chunk.length - kept;
|
|
39
|
-
}
|
|
40
|
-
async function drain(reader) {
|
|
41
|
-
try {
|
|
42
|
-
while (true) {
|
|
43
|
-
const { done, value } = await reader.read();
|
|
44
|
-
if (done) return;
|
|
45
|
-
log(value);
|
|
46
|
-
}
|
|
47
|
-
} catch (error) {
|
|
48
|
-
if (logging) { step.error = error.message; killGroup(proc); }
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
try {
|
|
52
|
-
proc = Bun.spawn(spawnArgv, { cwd, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', detached: true });
|
|
53
|
-
state.active = proc;
|
|
54
|
-
readers.push(proc.stdout.getReader(), proc.stderr.getReader());
|
|
55
|
-
const drained = Promise.all(readers.map(drain));
|
|
56
|
-
const exited = proc.exited.then((code) => {
|
|
57
|
-
if (logging) step.exitCode = code;
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
killGroup(proc);
|
|
60
|
-
});
|
|
61
|
-
/** @type {Promise<void>} */
|
|
62
|
-
const timeout = new Promise((resolve) => {
|
|
63
|
-
timer = setTimeout(() => { step.timedOut = true; killGroup(proc); resolve(); }, limits.timeoutMs);
|
|
64
|
-
});
|
|
65
|
-
await Promise.race([exited, timeout]);
|
|
66
|
-
const complete = await Promise.race([
|
|
67
|
-
Promise.all([exited, drained]).then(() => true),
|
|
68
|
-
new Promise((resolve) => { graceTimer = setTimeout(() => resolve(false), drainGraceMs); }),
|
|
69
|
-
]);
|
|
70
|
-
step.logIncomplete = !complete;
|
|
71
|
-
} catch (error) {
|
|
72
|
-
step.error = error.message;
|
|
73
|
-
log(new TextEncoder().encode(error.message));
|
|
74
|
-
} finally {
|
|
75
|
-
clearTimeout(timer);
|
|
76
|
-
clearTimeout(graceTimer);
|
|
77
|
-
logging = false;
|
|
78
|
-
if (proc) killGroup(proc);
|
|
79
|
-
// Cancel without another EOF wait. Escaped writers may retain the other pipe end forever.
|
|
80
|
-
for (const reader of readers) reader.cancel().then(() => reader.releaseLock()).catch(() => {});
|
|
81
|
-
state.active = null;
|
|
82
|
-
closeSync(fd);
|
|
83
|
-
step.durationMs = Math.round(performance.now() - started);
|
|
84
|
-
writeFileSync(step.receiptPath, `${JSON.stringify(step, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
85
|
-
}
|
|
86
|
-
return step;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
17
|
export async function executeDeclared(repo, revision, paths, criteria, manager, pkg, limits) {
|
|
90
18
|
const pending = groups.filter(([id]) => criteria.find((item) => item.id === id).reason === 'not run');
|
|
91
19
|
const commands = [];
|
|
@@ -130,7 +58,7 @@ export async function executeDeclared(repo, revision, paths, criteria, manager,
|
|
|
130
58
|
const probe = await run('network-probe', argv, scratch, argv);
|
|
131
59
|
if (probe.exitCode === 0 && !probe.timedOut && !probe.error) result.network = 'isolated';
|
|
132
60
|
}
|
|
133
|
-
const clone = await run('clone', gitArgv('clone', '--no-hardlinks', '--no-checkout', '--', realpathSync(repo), cwd), scratch);
|
|
61
|
+
const clone = await run('clone', gitArgv('-C', scratch, 'clone', '--no-hardlinks', '--no-checkout', '--', realpathSync(repo), cwd), scratch);
|
|
134
62
|
if (clone.exitCode !== 0 || clone.timedOut) throw new Error(`clone failed; see ${clone.logPath}`);
|
|
135
63
|
const checkout = await run('checkout', gitArgv('-C', cwd, 'checkout', '--detach', revision), scratch);
|
|
136
64
|
if (checkout.exitCode !== 0 || checkout.timedOut) throw new Error(`checkout failed; see ${checkout.logPath}`);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import { gitArgv } from './git-argv.js';
|
|
2
|
+
import { gitArgv, gitEnv } from './git-argv.js';
|
|
3
3
|
import { readFileSync, mkdirSync, writeFileSync, lstatSync, realpathSync, renameSync, unlinkSync } from 'node:fs';
|
|
4
4
|
import { executeDeclared } from './readiness-run.js';
|
|
5
5
|
|
|
@@ -9,7 +9,7 @@ const criteriaVersion = 1;
|
|
|
9
9
|
/** @param {"ignore" | Uint8Array} [stdin] */
|
|
10
10
|
function gitOutput(repo, args, stdin = 'ignore') {
|
|
11
11
|
const argv = gitArgv('-C', repo, ...args);
|
|
12
|
-
const result = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe', stdin });
|
|
12
|
+
const result = Bun.spawnSync(argv, { env: gitEnv(), stdout: 'pipe', stderr: 'pipe', stdin });
|
|
13
13
|
if (result.exitCode !== 0) throw new Error(result.stderr.toString().trim());
|
|
14
14
|
return result.stdout;
|
|
15
15
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { gitArgv } from './git-argv.js';
|
|
1
|
+
import { gitArgv, gitEnv } from './git-argv.js';
|
|
2
2
|
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
3
3
|
|
|
4
|
-
const help = `Usage: bun scripts/run-init.js --slug <slug> [--date YYYYMMDD]
|
|
5
|
-
Example: bun scripts/run-init.js --slug cli-lessons --date 20261008
|
|
4
|
+
const help = `Usage: bun scripts/run-init.js --slug <slug> --repo <path> [--date YYYYMMDD]
|
|
5
|
+
Example: bun scripts/run-init.js --slug cli-lessons --date 20261008 --repo /path/to/repo
|
|
6
6
|
|
|
7
|
+
--repo Required Git checkout path; run the installed helper from a trusted cwd
|
|
7
8
|
--slug Required run slug: lowercase letters, digits and hyphens only
|
|
8
9
|
--date Valid calendar date in YYYYMMDD; defaults to today's UTC date
|
|
9
10
|
--help Show flags, side effects and exit codes without writing
|
|
@@ -23,7 +24,7 @@ function optionsFrom(argv) {
|
|
|
23
24
|
const options = {};
|
|
24
25
|
for (let i = 0; i < argv.length; i += 2) {
|
|
25
26
|
const flag = argv[i];
|
|
26
|
-
if (!['--slug', '--date'].includes(flag)) throw new Error(`unexpected argument ${flag}; use --help`);
|
|
27
|
+
if (!['--slug', '--date', '--repo'].includes(flag)) throw new Error(`unexpected argument ${flag}; use --help`);
|
|
27
28
|
const value = argv[i + 1];
|
|
28
29
|
if (!value || value.startsWith('--')) throw new Error(`missing value; pass ${flag} <value>`);
|
|
29
30
|
if (flag in options) throw new Error(`duplicate ${flag}; pass it once`);
|
|
@@ -32,17 +33,18 @@ function optionsFrom(argv) {
|
|
|
32
33
|
if (!options['--slug'] || !/^[a-z0-9-]+$/.test(options['--slug'])) {
|
|
33
34
|
throw new Error('pass --slug <slug> using only lowercase letters, digits and hyphens');
|
|
34
35
|
}
|
|
36
|
+
if (!options['--repo']) throw new Error('pass --repo <Git-checkout-path>');
|
|
35
37
|
const date = options['--date'] ?? new Date().toISOString().slice(0, 10).replaceAll('-', '');
|
|
36
38
|
const iso = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`;
|
|
37
39
|
const parsed = new Date(`${iso}T00:00:00Z`);
|
|
38
40
|
if (!/^\d{8}$/.test(date) || Number.isNaN(parsed.valueOf()) || parsed.toISOString().slice(0, 10) !== iso) {
|
|
39
41
|
throw new Error('pass --date YYYYMMDD with a valid calendar date');
|
|
40
42
|
}
|
|
41
|
-
return { slug: options['--slug'], date };
|
|
43
|
+
return { repo: options['--repo'], slug: options['--slug'], date };
|
|
42
44
|
}
|
|
43
45
|
|
|
44
|
-
function git(...args) {
|
|
45
|
-
const result = Bun.spawnSync(gitArgv(...args), { stdout: 'pipe', stderr: 'pipe' });
|
|
46
|
+
function git(repo, ...args) {
|
|
47
|
+
const result = Bun.spawnSync(gitArgv('-C', repo, ...args), { env: gitEnv(), stdout: 'pipe', stderr: 'pipe' });
|
|
46
48
|
return result.exitCode === 0 ? result.stdout.toString().trim() : null;
|
|
47
49
|
}
|
|
48
50
|
|
|
@@ -52,10 +54,10 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
|
|
|
52
54
|
io.stdout(help);
|
|
53
55
|
return 0;
|
|
54
56
|
}
|
|
55
|
-
const { slug, date } = optionsFrom(argv);
|
|
56
|
-
const gitCommonDir = git('rev-parse', '--path-format=absolute', '--git-common-dir');
|
|
57
|
-
if (!gitCommonDir) throw new Error('not
|
|
58
|
-
const head = git('rev-parse', '--verify', 'HEAD');
|
|
57
|
+
const { repo, slug, date } = optionsFrom(argv);
|
|
58
|
+
const gitCommonDir = git(repo, 'rev-parse', '--path-format=absolute', '--git-common-dir');
|
|
59
|
+
if (!gitCommonDir) throw new Error('not a Git repository; run with --repo <Git-checkout-path>');
|
|
60
|
+
const head = git(repo, 'rev-parse', '--verify', 'HEAD');
|
|
59
61
|
const source = realpathSync(`${import.meta.dir}/../references/run-record.md`);
|
|
60
62
|
const template = readFileSync(source, 'utf8').match(/^## Compact template\r?\n[\s\S]*?^```text\r?\n([\s\S]*?)^```/m)?.[1];
|
|
61
63
|
if (!template) throw new Error('compact template missing; restore references/run-record.md');
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const HELP = `schedule-drift — canonical schedule comparison (R2 fact mode)
|
|
5
|
+
bun schedule-drift.js --export FILE --bindings FILE [--prompts DIR] [--now ISO] [--max-age-seconds N]
|
|
6
|
+
--export FILE Saved JSON: {version:1,host,exportedAt,complete:true,tasks:[{scheduledTaskId,
|
|
7
|
+
projectId,prompt,schedule,enabled}]}. Export every relevant project; never use a live database.
|
|
8
|
+
--bindings FILE Private JSON: {host,schedules:[{promptFile,scheduledTaskId,projectId,enabled,schedule,
|
|
9
|
+
values:{HOST_TOKEN:"literal value"}}]}. Declare all three packaged prompt filenames exactly once.
|
|
10
|
+
For intentional host exclusions use {promptFile,absent:true,scheduledTaskId?:expectedId}.
|
|
11
|
+
Fresh complete matching-host coverage yields n/a; any matching declared task ID fails.
|
|
12
|
+
Without a task ID, absent:true is an explicit host-scope declaration, not identity discovery.
|
|
13
|
+
Values substitute only explicit {{HOST_TOKEN}} placeholders.
|
|
14
|
+
Prompt comparison ignores trailing LF characters only; all other whitespace remains exact.
|
|
15
|
+
A live prompt containing any unfilled {{HOST_ prefix fails, even if bound bytes match.
|
|
16
|
+
Schedule is the exact host declaration; review-manager additionally requires interval 1800000.
|
|
17
|
+
--prompts DIR Directory containing the three packaged prompt files; default: installed ../references.
|
|
18
|
+
--now ISO Observation time with timezone; default: current UTC. Saved times prove no live delivery.
|
|
19
|
+
--max-age-seconds N Maximum export age, inclusive; positive integer, default 300. Future exports are unknown.
|
|
20
|
+
--help Show flags, schema, effects and limitations.
|
|
21
|
+
No writes, subprocesses, network, database access, schedule mutations or persistent state.
|
|
22
|
+
Stdout reports per-term pass/fail/unknown/n/a with evidence and counts only; no aggregate verdict or authority.
|
|
23
|
+
Exports and bindings stay private. Output contains hashes and filenames, never prompts, IDs or host values.
|
|
24
|
+
Missing, malformed, unavailable, stale or incomplete evidence is unknown; no comparison passes without fresh coverage.
|
|
25
|
+
Exit: 0 measured (including failed facts), 1 invalid CLI/error, 2 incomplete (unknown facts).
|
|
26
|
+
`;
|
|
27
|
+
const files = ['review-manager-prompt.md', 'pr-triage-nightly.md', 'test-audit-weekly.md'];
|
|
28
|
+
const sha256 = (bytes) => new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
|
|
29
|
+
const time = (value) => typeof value === 'string' && /T.*(?:Z|[+-]\d\d:\d\d)$/.test(value) ? Date.parse(value) : NaN;
|
|
30
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
31
|
+
const nonempty = (v) => typeof v === 'string' && v.length > 0;
|
|
32
|
+
const ordered = (value) => Array.isArray(value) ? value.map(ordered) : object(value)
|
|
33
|
+
? Object.fromEntries(Object.keys(value).sort().map((key) => [key, ordered(value[key])])) : value;
|
|
34
|
+
const equal = (a, b) => JSON.stringify(ordered(a)) === JSON.stringify(ordered(b));
|
|
35
|
+
|
|
36
|
+
function options(argv) {
|
|
37
|
+
const args = { '--prompts': `${import.meta.dir}/../references`, '--now': new Date().toISOString(), '--max-age-seconds': '300' };
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
40
|
+
const key = argv[i];
|
|
41
|
+
if (!['--export', '--bindings', '--prompts', '--now', '--max-age-seconds'].includes(key) || !argv[i + 1] || seen.has(key)) {
|
|
42
|
+
throw new Error(`invalid argument: ${key}`);
|
|
43
|
+
}
|
|
44
|
+
seen.add(key);
|
|
45
|
+
args[key] = argv[i + 1];
|
|
46
|
+
}
|
|
47
|
+
if (!args['--export'] || !args['--bindings'] || !Number.isFinite(time(args['--now'])) ||
|
|
48
|
+
!/^[1-9]\d*$/.test(args['--max-age-seconds']) || !Number.isSafeInteger(Number(args['--max-age-seconds']))) {
|
|
49
|
+
throw new Error('expected --export, --bindings, timezone-qualified --now and positive --max-age-seconds');
|
|
50
|
+
}
|
|
51
|
+
return args;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function compare(args) {
|
|
55
|
+
const terms = [];
|
|
56
|
+
const term = (id, status, evidence) => terms.push({ id, status, evidence });
|
|
57
|
+
let source, bindings, exportSha256 = null, bindingsSha256 = null;
|
|
58
|
+
try {
|
|
59
|
+
const bytes = readFileSync(args['--export']);
|
|
60
|
+
exportSha256 = sha256(bytes);
|
|
61
|
+
source = JSON.parse(bytes.toString());
|
|
62
|
+
const declared = readFileSync(args['--bindings']);
|
|
63
|
+
bindingsSha256 = sha256(declared);
|
|
64
|
+
bindings = JSON.parse(declared.toString());
|
|
65
|
+
} catch { /* A missing or malformed saved export/binding is unavailable evidence. */ }
|
|
66
|
+
const age = (time(args['--now']) - time(source?.exportedAt)) / 1000;
|
|
67
|
+
const fresh = source?.version === 1 && source.complete === true && nonempty(source.host) &&
|
|
68
|
+
Array.isArray(source.tasks) && Number.isFinite(age) && age >= 0 && age <= Number(args['--max-age-seconds']);
|
|
69
|
+
const declared = object(bindings) && nonempty(bindings.host) && Array.isArray(bindings.schedules);
|
|
70
|
+
term('export', fresh ? 'pass' : 'unknown', fresh ? `complete export; age ${age}s; sha256 ${exportSha256}` : 'unavailable, incomplete, malformed, stale or future export');
|
|
71
|
+
term('host', !fresh || !declared ? 'unknown' : source.host === bindings.host ? 'pass' : 'fail', 'export host compared with private declared host');
|
|
72
|
+
for (const file of files) {
|
|
73
|
+
const rows = declared ? bindings.schedules.filter((b) => b?.promptFile === file) : [];
|
|
74
|
+
const binding = rows.length === 1 ? rows[0] : null;
|
|
75
|
+
const tasks = fresh && nonempty(binding?.scheduledTaskId)
|
|
76
|
+
? source.tasks.filter((t) => t?.scheduledTaskId === binding.scheduledTaskId) : [];
|
|
77
|
+
const task = tasks.length === 1 ? tasks[0] : null;
|
|
78
|
+
if (binding?.absent === true) {
|
|
79
|
+
const status = !fresh || source.host !== bindings.host ? 'unknown' : tasks.length ? 'fail' : 'n/a';
|
|
80
|
+
for (const suffix of ['binding', 'prompt', 'cadence', 'enabled']) {
|
|
81
|
+
term(`${file}.${suffix}`, status, 'explicit host exclusion; fresh complete matching-host export required; any declared task ID must be absent');
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const usable = fresh && declared && rows.length === 1 && task !== null;
|
|
86
|
+
const fact = (suffix, known, matches, evidence) => term(`${file}.${suffix}`,
|
|
87
|
+
!usable || !known ? 'unknown' : matches ? 'pass' : 'fail', evidence);
|
|
88
|
+
fact('binding', nonempty(binding?.projectId) && nonempty(task?.projectId),
|
|
89
|
+
task?.projectId === binding?.projectId, 'exact schedule ID and project binding; missing or duplicate identities are unknown');
|
|
90
|
+
let expected = null, packagedSha256 = null;
|
|
91
|
+
try {
|
|
92
|
+
const bytes = readFileSync(`${args['--prompts']}/${file}`);
|
|
93
|
+
packagedSha256 = sha256(bytes);
|
|
94
|
+
expected = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
95
|
+
expected = expected.replace(/\{\{(HOST_[A-Z_]+)\}\}/g, (_, key) => {
|
|
96
|
+
if (!object(binding?.values) || typeof binding.values[key] !== 'string') throw new Error('unbound host token');
|
|
97
|
+
return binding.values[key];
|
|
98
|
+
});
|
|
99
|
+
} catch { expected = null; }
|
|
100
|
+
const unfilled = nonempty(task?.prompt) && task.prompt.includes('{{HOST_');
|
|
101
|
+
fact('prompt', nonempty(task?.prompt) && (unfilled || expected !== null),
|
|
102
|
+
!unfilled && expected !== null && nonempty(task?.prompt) && expected.replace(/\n+$/, '') === task.prompt.replace(/\n+$/, ''),
|
|
103
|
+
`live host tokens must be filled; exact UTF-8 bytes after declared host-token substitution, excluding trailing LF; packaged sha256 ${packagedSha256 ?? 'unavailable'}`);
|
|
104
|
+
const scheduleKnown = validSchedule(binding?.schedule) && validSchedule(task?.schedule);
|
|
105
|
+
const canonical = file !== files[0] || equal(binding?.schedule, { type: 'interval', everyMs: 1800000 });
|
|
106
|
+
fact('cadence', scheduleKnown, canonical && equal(task?.schedule, binding?.schedule), 'exact declared schedule; review-manager interval fixed at 1800000ms');
|
|
107
|
+
fact('enabled', typeof binding?.enabled === 'boolean' && typeof task?.enabled === 'boolean',
|
|
108
|
+
task?.enabled === binding?.enabled, 'enabled state compared with private declaration');
|
|
109
|
+
}
|
|
110
|
+
const counts = Object.fromEntries(['pass', 'fail', 'unknown', 'n/a'].map((s) => [s, terms.filter((t) => t.status === s).length]));
|
|
111
|
+
return { version: 1, observedAt: args['--now'], exportSha256, bindingsSha256, terms, counts };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function validSchedule(s) {
|
|
115
|
+
if (!object(s)) return false;
|
|
116
|
+
if (s.type === 'interval') return Number.isSafeInteger(s.everyMs) && s.everyMs > 0;
|
|
117
|
+
if (s.type !== 'fixed_time' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(s.timeOfDay)) return false;
|
|
118
|
+
return s.weekdays === undefined || s.weekdays === null || Array.isArray(s.weekdays) && s.weekdays.length > 0 &&
|
|
119
|
+
s.weekdays.every((d) => Number.isSafeInteger(d) && d >= 0 && d <= 6);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
if (process.argv.slice(2).length === 1 && process.argv[2] === '--help') console.log(HELP);
|
|
124
|
+
else {
|
|
125
|
+
const report = compare(options(process.argv.slice(2)));
|
|
126
|
+
console.log(JSON.stringify(report, null, 2));
|
|
127
|
+
process.exitCode = report.counts.unknown ? 2 : 0;
|
|
128
|
+
}
|
|
129
|
+
} catch (error) {
|
|
130
|
+
console.error(`schedule-drift: ${error.message}`);
|
|
131
|
+
process.exitCode = 1;
|
|
132
|
+
}
|