axstack 0.67.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 +2 -2
- package/docs/host-operations.md +3 -6
- package/docs/installation.md +8 -8
- package/docs/workflows.md +5 -9
- package/package.json +2 -2
- package/skills/axstack/references/automations.md +3 -14
- package/skills/axstack/references/autopilot.md +1 -0
- package/skills/axstack/references/capture-receipts.md +22 -0
- package/skills/axstack/references/lifecycle.md +1 -1
- package/skills/axstack/references/live-run.md +59 -0
- package/skills/axstack/references/pr-shape.md +13 -16
- package/skills/axstack/references/review-manager-prompt.md +21 -19
- package/skills/axstack/references/run-record.md +2 -2
- 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 +3 -0
- 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 +54 -29
- 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 +5 -3
- 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 +10 -4
- package/skills/axstack-watch/references/proven-verification.md +3 -2
- package/skills/axstack-watch/references/readiness.md +56 -61
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { gitArgv, gitEnv } from './git-argv.js';
|
|
3
|
+
|
|
4
|
+
export const captureVersion = '1.0.0';
|
|
5
|
+
export const sha256 = (bytes) => new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
|
|
6
|
+
function git(repo, ...args) {
|
|
7
|
+
const r = Bun.spawnSync(gitArgv('-C', repo, ...args), { env: gitEnv(), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
|
|
8
|
+
if (r.exitCode !== 0) throw Error(r.stderr.toString().trim() || 'git identity unavailable');
|
|
9
|
+
return args.includes('-z') ? r.stdout.toString() : r.stdout.toString().trim();
|
|
10
|
+
}
|
|
11
|
+
function snapshotTree(root) {
|
|
12
|
+
const hash = new Bun.CryptoHasher('sha256');
|
|
13
|
+
const included = new Set(git(root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard').split('\0').filter(Boolean));
|
|
14
|
+
const directories = new Set();
|
|
15
|
+
for (const path of included) {
|
|
16
|
+
const parts = path.split('/');
|
|
17
|
+
while (parts.length > 1) { parts.pop(); directories.add(parts.join('/')); }
|
|
18
|
+
}
|
|
19
|
+
function walk(relative) {
|
|
20
|
+
for (const name of readdirSync(`${root}/${relative}`).sort()) {
|
|
21
|
+
if (!relative && name === '.git') continue;
|
|
22
|
+
const path = relative ? `${relative}/${name}` : name;
|
|
23
|
+
if (!included.has(path) && !directories.has(path)) continue;
|
|
24
|
+
const stat = lstatSync(`${root}/${path}`);
|
|
25
|
+
hash.update(`${JSON.stringify([path, stat.mode & 0o177777])}\n`);
|
|
26
|
+
if (stat.isSymbolicLink()) hash.update(JSON.stringify(readlinkSync(`${root}/${path}`)));
|
|
27
|
+
else if (stat.isDirectory()) walk(path);
|
|
28
|
+
else if (stat.isFile()) hash.update(sha256(readFileSync(`${root}/${path}`)));
|
|
29
|
+
else throw Error(`unsupported source entry: ${path}`);
|
|
30
|
+
hash.update('\n');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
walk('');
|
|
34
|
+
return hash.digest('hex');
|
|
35
|
+
}
|
|
36
|
+
function requestedCommit(repo, flag, ref) {
|
|
37
|
+
try { return git(repo, 'rev-parse', '--verify', `${ref}^{commit}`); }
|
|
38
|
+
catch (error) { throw Error(`--${flag} ${JSON.stringify(ref)}: commit unavailable locally; ${error.message}`); }
|
|
39
|
+
}
|
|
40
|
+
// Binds tracked and non-ignored untracked entries; ignored bytes and Git metadata are excluded.
|
|
41
|
+
export function sourceIdentity(binding) {
|
|
42
|
+
const repo = realpathSync(binding.repo);
|
|
43
|
+
if (realpathSync(git(repo, 'rev-parse', '--show-toplevel')) !== repo) throw Error('repo must be the source root');
|
|
44
|
+
const requestedHead = requestedCommit(repo, 'head', binding.head);
|
|
45
|
+
const base = requestedCommit(repo, 'base', binding.base);
|
|
46
|
+
return {
|
|
47
|
+
root: repo, repository: git(repo, 'remote', 'get-url', 'origin'),
|
|
48
|
+
head: git(repo, 'rev-parse', '--verify', 'HEAD^{commit}'),
|
|
49
|
+
requestedHead, base,
|
|
50
|
+
dirty: Boolean(git(repo, 'status', '--porcelain', '--untracked-files=all')),
|
|
51
|
+
snapshot: snapshotTree(repo),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function hold(message) {
|
|
55
|
+
throw Object.assign(new Error(message), { captureHold: true });
|
|
56
|
+
}
|
|
57
|
+
const within = (path, root) => path === root || path.startsWith(root === '/' ? '/' : `${root}/`);
|
|
58
|
+
export function admitCapture(binding, evidence, cwd) {
|
|
59
|
+
if (!binding.repo || !binding.repository || !binding.head || !binding.base) throw Error('missing capture identity: repo, repository, head and base required');
|
|
60
|
+
if (!binding.tool?.name || !binding.tool?.version) throw Error('capture tool name and version required');
|
|
61
|
+
const output = realpathSync(evidence);
|
|
62
|
+
const stat = lstatSync(evidence);
|
|
63
|
+
if (stat.isSymbolicLink() || !stat.isDirectory() || stat.uid !== process.getuid() || (stat.mode & 0o777) !== 0o700) throw Error('evidence must be an owned 0700 directory');
|
|
64
|
+
for (const root of [binding.repo, cwd, ...(binding.writableRoots ?? [])]) {
|
|
65
|
+
if (within(output, realpathSync(root))) hold('receipt output must be outside every untrusted writable root (source and cwd included)');
|
|
66
|
+
}
|
|
67
|
+
if (binding.sandboxImageDigest != null && !/^sha256:[a-f0-9]{64}$/.test(binding.sandboxImageDigest)) throw Error('sandbox image digest must be sha256:<64 hex>');
|
|
68
|
+
const before = sourceIdentity(binding);
|
|
69
|
+
if (before.repository !== binding.repository || before.head !== before.requestedHead) hold('repository or requested head does not match source');
|
|
70
|
+
if (before.dirty && binding.snapshot !== before.snapshot) hold(`dirty source requires exact --snapshot ${before.snapshot}`);
|
|
71
|
+
if (binding.snapshot && binding.snapshot !== before.snapshot) hold(`declared snapshot does not match source; computed --snapshot ${before.snapshot}`);
|
|
72
|
+
return before;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// These are capture facts, never a proof-sufficiency or authority verdict.
|
|
76
|
+
export function finishCapture(step, binding, before, cwd, signal) {
|
|
77
|
+
Object.assign(step, {
|
|
78
|
+
schemaVersion: 1, tool: { name: binding.tool.name, version: binding.tool.version, bun: Bun.version },
|
|
79
|
+
repository: binding.repository, pr: binding.pr ?? null,
|
|
80
|
+
requested: { head: before.requestedHead, base: before.base },
|
|
81
|
+
requestedRefs: { head: binding.head, base: binding.base },
|
|
82
|
+
snapshotScope: { files: 'tracked+untracked-nonignored', ignoreSources: ['.gitignore', '.git/info/exclude', 'core.excludesFile-or-git-default'] },
|
|
83
|
+
cwd, sandboxImageDigest: binding.sandboxImageDigest ?? null,
|
|
84
|
+
declaredSnapshot: binding.snapshot ?? null, sourceBefore: before, sourceAfter: null,
|
|
85
|
+
interrupted: signal, logSha256: sha256(readFileSync(step.logPath)),
|
|
86
|
+
});
|
|
87
|
+
try { step.sourceAfter = sourceIdentity(binding); } catch (error) { step.sourceError = error.message; }
|
|
88
|
+
step.terms = captureTerms(step, { repository: binding.repository, head: before.requestedHead, base: before.base });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Revalidation requires caller-supplied expectations; a receipt cannot attest itself.
|
|
92
|
+
export function captureTerms(step, expected = null) {
|
|
93
|
+
const unchanged = JSON.stringify(step.sourceBefore) === JSON.stringify(step.sourceAfter);
|
|
94
|
+
const identities = [step.sourceBefore, step.sourceAfter];
|
|
95
|
+
const identityPresent = identities.every(s => s && ['root', 'repository', 'head', 'requestedHead', 'base', 'snapshot'].every(k => typeof s[k] === 'string' && s[k]) && typeof s.dirty === 'boolean');
|
|
96
|
+
const fullSha = value => typeof value === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
|
|
97
|
+
const schema = step.schemaVersion === 1 && typeof step.tool?.name === 'string' && step.tool.name.length > 0 && typeof step.tool.version === 'string' && step.tool.version.length > 0
|
|
98
|
+
&& Array.isArray(step.argv) && step.argv.length > 0 && step.argv.every(a => typeof a === 'string')
|
|
99
|
+
&& typeof step.cwd === 'string' && step.cwd.startsWith('/') && identityPresent
|
|
100
|
+
&& fullSha(step.requested?.head) && fullSha(step.requested?.base)
|
|
101
|
+
&& typeof step.repository === 'string' && typeof step.logSha256 === 'string'
|
|
102
|
+
&& (step.sandboxImageDigest === null || /^sha256:[a-f0-9]{64}$/.test(step.sandboxImageDigest));
|
|
103
|
+
const bound = schema && expected?.repository && fullSha(expected?.head) && fullSha(expected?.base)
|
|
104
|
+
&& step.repository === expected.repository && step.requested.head === expected.head && step.requested.base === expected.base
|
|
105
|
+
&& step.sourceBefore.repository === step.repository && step.sourceBefore.head === step.requested.head
|
|
106
|
+
&& step.sourceBefore.requestedHead === step.requested.head && step.sourceBefore.base === step.requested.base
|
|
107
|
+
&& (!step.sourceBefore.dirty || step.declaredSnapshot === step.sourceBefore.snapshot);
|
|
108
|
+
let logStatus = 'unknown', logEvidence;
|
|
109
|
+
try {
|
|
110
|
+
const bytes = readFileSync(step.logPath);
|
|
111
|
+
logStatus = typeof step.logSha256 !== 'string' ? 'unknown' : sha256(bytes) === step.logSha256 && bytes.length === step.logBytes ? 'pass' : 'fail';
|
|
112
|
+
logEvidence = step.logPath;
|
|
113
|
+
} catch (error) { logEvidence = error.message; }
|
|
114
|
+
const observed = source => source ? { repository: source.repository, head: source.head, requestedHead: source.requestedHead, base: source.base } : null;
|
|
115
|
+
return [
|
|
116
|
+
{ id: 'identity', status: !schema || !expected?.repository || !expected?.head || !expected?.base ? 'unknown' : bound ? 'pass' : 'fail', evidence: { expected: expected ? { repository: expected.repository, head: expected.head, base: expected.base } : null, requested: step.requested, sourceBefore: observed(step.sourceBefore), sourceAfter: observed(step.sourceAfter) } },
|
|
117
|
+
{ id: 'log', status: logStatus, evidence: logEvidence },
|
|
118
|
+
{ id: 'source', status: !step.sourceAfter ? 'unknown' : unchanged ? 'pass' : 'fail', evidence: !step.sourceAfter ? step.sourceError ?? 'source unavailable' : unchanged ? 'before/after identity equal' : 'source identity changed' },
|
|
119
|
+
{ id: 'capture', status: step.error || step.timedOut !== false || step.interrupted !== null || step.omittedBytes !== 0 || step.logIncomplete !== false || !Number.isInteger(step.exitCode) ? 'unknown' : 'pass',
|
|
120
|
+
evidence: { exitCode: step.exitCode, error: step.error ?? null, timedOut: step.timedOut, interrupted: step.interrupted, omittedBytes: step.omittedBytes, logIncomplete: step.logIncomplete } },
|
|
121
|
+
];
|
|
122
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { captureTerms, captureVersion, sha256 } from './capture-identity.js';
|
|
4
|
+
import { killGroup, runCommand } from './command-capture.js';
|
|
5
|
+
import { gitArgv } from './git-argv.js';
|
|
6
|
+
|
|
7
|
+
export const help = `Usage: check-run.js --repo PATH --repository ORIGIN --head REF --base REF --out DIR [options] -- COMMAND [ARG...]
|
|
8
|
+
Capture v${captureVersion}; receipt schema v1. Flags:
|
|
9
|
+
--repo PATH Git source root (origin URL must match --repository)
|
|
10
|
+
--repository ORIGIN Exact repository identity, as reported by git remote get-url origin
|
|
11
|
+
--head REF Resolve to a full commit SHA; must match source HEAD
|
|
12
|
+
--base REF Resolve to a full base SHA; typed refs are informational only
|
|
13
|
+
--out DIR Existing owned 0700 receipt directory outside all writable roots
|
|
14
|
+
--cwd PATH Command cwd (default: --repo)
|
|
15
|
+
--snapshot SHA256 Exact source digest required when dirty; holds print the digest
|
|
16
|
+
--pr URL Optional PR identity, recorded alongside repository
|
|
17
|
+
--image-digest VALUE Optional sandbox image sha256:<64 hex>; default null
|
|
18
|
+
--writable-root PATH Additional untrusted writable mount; repeat for every mount
|
|
19
|
+
--timeout-ms N Deadline (default 300000)
|
|
20
|
+
--log-bytes N Combined stdout/stderr byte cap (default 1048576)
|
|
21
|
+
--help Show help; runs no child, writes nothing
|
|
22
|
+
Effects: reads Git identity/status using local git subprocesses with hooks/fsmonitor
|
|
23
|
+
disabled, and hashes tracked and non-ignored untracked files, modes and
|
|
24
|
+
symlink targets. Ignored untracked files (e.g. node_modules) and .git metadata
|
|
25
|
+
are not bound; ignored-file changes cannot be detected by source comparison.
|
|
26
|
+
The receipt snapshotScope names the ignore sources: .gitignore, .git/info/exclude
|
|
27
|
+
and core.excludesFile (or Git's user-ignore default); local/user excludes widen
|
|
28
|
+
the unbound set. Starts one detached command without a
|
|
29
|
+
shell, with inherited environment, closed stdin, piped stdout/stderr and cwd.
|
|
30
|
+
Creates two exclusive 0600 files (combined .log and schema-v1 .json) in --out;
|
|
31
|
+
creates no directories, overwrites nothing, and retains both files for the caller.
|
|
32
|
+
No container or network isolation is created; the command may use the network,
|
|
33
|
+
spawn descendants and write anywhere its credentials permit. Declare all sandbox
|
|
34
|
+
writable mounts with --writable-root; mount discovery is not performed.
|
|
35
|
+
On exit, timeout, SIGINT, SIGTERM or SIGHUP, SIGKILLs the command's process group, drains
|
|
36
|
+
pipes for up to 200ms, then cancels readers/closes handles. Escaped process groups
|
|
37
|
+
are not contained. SIGKILL of check-run cannot clean up the process group; it
|
|
38
|
+
may remain running without a receipt. A crash may do the same. No filesystem
|
|
39
|
+
cleanup or source restoration is performed. Receipt path placement is not OS
|
|
40
|
+
isolation from malicious commands running with the writer's credentials.
|
|
41
|
+
Exit: 0 measured (child may fail), 1 invocation/writer error, 2 hold/incomplete.
|
|
42
|
+
Child exitCode is separate; terms describe capture facts, never proof sufficiency.
|
|
43
|
+
Silence is valid. Timeout/spawn failure/interruption/truncation/incomplete drain
|
|
44
|
+
leave capture unknown; changed source fails source identity. Neither closes a
|
|
45
|
+
proof term that needs the missing evidence. No dispatch, retry, schedule or merge.
|
|
46
|
+
|
|
47
|
+
R5 read-only modes (no writes, network, cleanup or runtime enforcement):
|
|
48
|
+
check-run.js r5-plan --input FILE
|
|
49
|
+
check-run.js r5-trace --plan-receipt FILE --result FILE --repository ORIGIN --head SHA --base SHA
|
|
50
|
+
--input FILE Before JSON: catalog path, scenario id, version, host,
|
|
51
|
+
tokenLimit, timeLimitMs, attempt:1, nonce, recordedAt,
|
|
52
|
+
requested:{provider,model,options}. Limits are positive integers.
|
|
53
|
+
--plan-receipt FILE Schema-v1 receipt of a captured r5-plan invocation
|
|
54
|
+
--result FILE After JSON; see references/live-run.md for its fields
|
|
55
|
+
--repository ORIGIN --head SHA --base SHA Independent full capture identities
|
|
56
|
+
These modes read explicit local JSON/catalog/receipt/log/helper files and print per-term
|
|
57
|
+
facts and counts. Wrap each mode with ordinary check-run to retain schema-v1
|
|
58
|
+
receipts; keep the before receipt before launching the scenario yourself.
|
|
59
|
+
The plan stamps its own plannedAt and helper realpath/SHA256. Caller recordedAt
|
|
60
|
+
must not be future-dated; the literal placeholder nonce is rejected. Trace reads
|
|
61
|
+
package.json and catalog bytes at the captured head through read-only git with
|
|
62
|
+
replacement objects, hooks and fsmonitor disabled; unreadable bytes stay unknown.
|
|
63
|
+
Trace trusts the release checkout's object database as Git reads it, the Git
|
|
64
|
+
environment and git binary. Overwritten loose objects or a redirected
|
|
65
|
+
GIT_OBJECT_DIRECTORY are not detected. git fsck in a clean environment helps
|
|
66
|
+
but does not close the redirected-object-directory case. Verify independently.
|
|
67
|
+
Both R5 captures and trace's planning-command check require the same realpath Bun
|
|
68
|
+
as process.execPath. Trace trusts its own interpreter: a fake bun earlier on PATH
|
|
69
|
+
than the trace's own bun stays undetectable. Verify that interpreter independently.
|
|
70
|
+
The trace binds result bytes to the plan hash and nonce and rechecks capture
|
|
71
|
+
identity/log integrity. T3 observations are caller-supplied, never authenticated
|
|
72
|
+
by this helper. Missing observations stay unknown. Failed criteria exit 0;
|
|
73
|
+
unknown exits 2, invalid invocation/JSON exits 1. No publication verdict.
|
|
74
|
+
`;
|
|
75
|
+
|
|
76
|
+
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
77
|
+
const positive = value => Number.isSafeInteger(value) && value > 0;
|
|
78
|
+
const settings = value => value && text(value.provider) && text(value.model)
|
|
79
|
+
&& value.options && typeof value.options === 'object' && !Array.isArray(value.options);
|
|
80
|
+
const timestamp = value => typeof value === 'string' && /T.*(?:Z|[+-]\d\d:\d\d)$/.test(value) && Number.isFinite(Date.parse(value));
|
|
81
|
+
function canonical(value) {
|
|
82
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
83
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])]));
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
const equal = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
87
|
+
const term = (id, ok, evidence) => ({ id, status: ok === null ? 'unknown' : ok ? 'pass' : 'fail', evidence });
|
|
88
|
+
const readJSON = path => JSON.parse(readFileSync(path, 'utf8'));
|
|
89
|
+
function fileIdentity(path) {
|
|
90
|
+
try { return { path: realpathSync(path), sha256: sha256(readFileSync(path)) }; }
|
|
91
|
+
catch (error) { return { path: null, sha256: null, error: error.message }; }
|
|
92
|
+
}
|
|
93
|
+
function interpreterPath(executable) {
|
|
94
|
+
try { return realpathSync(Bun.which(executable) ?? executable); }
|
|
95
|
+
catch { return null; }
|
|
96
|
+
}
|
|
97
|
+
function committedFile(source, path) {
|
|
98
|
+
if (!source?.root || !/^[a-f0-9]{40,64}$/.test(source.head)) throw Error('missing captured source identity');
|
|
99
|
+
const r = Bun.spawnSync(gitArgv('--no-replace-objects', '-C', source.root, 'show', `${source.head}:${path}`), { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
|
|
100
|
+
if (r.exitCode !== 0) throw Error(r.stderr.toString().trim());
|
|
101
|
+
return r.stdout;
|
|
102
|
+
}
|
|
103
|
+
function capturedVersion(source) {
|
|
104
|
+
try {
|
|
105
|
+
const { version } = JSON.parse(committedFile(source, 'package.json').toString());
|
|
106
|
+
if (!text(version)) throw Error('package version missing');
|
|
107
|
+
return { version, head: source.head };
|
|
108
|
+
} catch (error) { return { version: null, error: error.message }; }
|
|
109
|
+
}
|
|
110
|
+
function capturedCatalog(source, catalog) {
|
|
111
|
+
try {
|
|
112
|
+
if (!catalog.path?.startsWith(`${source?.root}/`)) throw Error('catalog outside captured source');
|
|
113
|
+
const path = catalog.path.slice(source.root.length + 1);
|
|
114
|
+
return { path, head: source.head, sha256: sha256(committedFile(source, path)) };
|
|
115
|
+
} catch (error) { return { sha256: null, error: error.message }; }
|
|
116
|
+
}
|
|
117
|
+
function r5Plan(input) {
|
|
118
|
+
const plannedAt = new Date().toISOString();
|
|
119
|
+
const bytes = readFileSync(input.catalog);
|
|
120
|
+
const catalog = JSON.parse(bytes.toString());
|
|
121
|
+
const matches = catalog.cases?.filter(c => c.id === input.scenario) ?? [];
|
|
122
|
+
const scenario = matches.length === 1 ? matches[0] : null;
|
|
123
|
+
return { schemaVersion: 1, kind: 'r5-plan', version: input.version, host: input.host,
|
|
124
|
+
tokenLimit: input.tokenLimit, timeLimitMs: input.timeLimitMs, attempt: input.attempt,
|
|
125
|
+
nonce: input.nonce, recordedAt: input.recordedAt, plannedAt, planner: fileIdentity(import.meta.path), requested: input.requested,
|
|
126
|
+
catalog: { path: realpathSync(input.catalog), sha256: sha256(bytes) },
|
|
127
|
+
scenario: scenario ? { id: scenario.id, title: scenario.title ?? scenario.id, input: scenario.input } : null,
|
|
128
|
+
terms: [
|
|
129
|
+
term('scenario', Boolean(scenario?.input), { catalog: input.catalog, id: input.scenario, matches: matches.length }),
|
|
130
|
+
term('installation', text(input.version) && text(input.host), { version: input.version, host: input.host, basis: 'caller declaration; verify installed release before launch' }),
|
|
131
|
+
term('limits', positive(input.tokenLimit) && positive(input.timeLimitMs) && input.attempt === 1,
|
|
132
|
+
{ tokenLimit: input.tokenLimit, timeLimitMs: input.timeLimitMs, attempt: input.attempt, enforcement: 'agent/runtime, not this helper' }),
|
|
133
|
+
term('settings', Boolean(settings(input.requested)), input.requested ?? null),
|
|
134
|
+
term('freshness', text(input.nonce) && input.nonce.length >= 16 && input.nonce !== 'replace-with-fresh-uuid'
|
|
135
|
+
&& timestamp(input.recordedAt) && Date.parse(input.recordedAt) <= Date.parse(plannedAt), { nonce: input.nonce, recordedAt: input.recordedAt, plannedAt }),
|
|
136
|
+
] };
|
|
137
|
+
}
|
|
138
|
+
function r5Trace(flags) {
|
|
139
|
+
const receiptBytes = readFileSync(flags['plan-receipt']);
|
|
140
|
+
const receipt = JSON.parse(receiptBytes.toString());
|
|
141
|
+
const planBytes = readFileSync(receipt.logPath), before = JSON.parse(planBytes.toString());
|
|
142
|
+
const resultBytes = readFileSync(flags.result), after = JSON.parse(resultBytes.toString());
|
|
143
|
+
const planner = fileIdentity(import.meta.path), command = fileIdentity(receipt.argv?.[1]);
|
|
144
|
+
const catalog = fileIdentity(before.catalog?.path), source = receipt.sourceBefore;
|
|
145
|
+
const committedCatalog = capturedCatalog(source, catalog);
|
|
146
|
+
const interpreter = interpreterPath(receipt.argv?.[0]), trustedInterpreter = realpathSync(process.execPath);
|
|
147
|
+
const version = capturedVersion(source);
|
|
148
|
+
const unavailable = after.outcome === 'unavailable';
|
|
149
|
+
const elapsed = timestamp(after.startedAt) && timestamp(after.finishedAt) ? Date.parse(after.finishedAt) - Date.parse(after.startedAt) : null;
|
|
150
|
+
const terms = [
|
|
151
|
+
...captureTerms(receipt, { repository: flags.repository, head: flags.head, base: flags.base }).map(t => ({ ...t, id: `plan-${t.id}` })),
|
|
152
|
+
term('plan-kind', before.schemaVersion === 1 && before.kind === 'r5-plan' && receipt.exitCode === 0
|
|
153
|
+
&& receipt.tool?.name === 'check-run' && receipt.argv?.length === 5
|
|
154
|
+
&& command.path === planner.path && receipt.argv[2] === 'r5-plan' && receipt.argv[3] === '--input' && interpreter === trustedInterpreter,
|
|
155
|
+
{ kind: before.kind, exitCode: receipt.exitCode, argv: receipt.argv, interpreter, trustedInterpreter }),
|
|
156
|
+
term('plan-tool', !command.path || !planner.path ? null : command.path === planner.path
|
|
157
|
+
&& before.planner?.path === planner.path && before.planner?.sha256 === planner.sha256,
|
|
158
|
+
{ current: planner, captured: before.planner ?? null, command }),
|
|
159
|
+
term('catalog', !catalog.path || !source?.root ? null : catalog.path.startsWith(`${source.root}/`)
|
|
160
|
+
&& (committedCatalog.sha256 === null ? null : catalog.sha256 === before.catalog.sha256 && committedCatalog.sha256 === before.catalog.sha256),
|
|
161
|
+
{ sourceRoot: source?.root, planned: before.catalog, observed: catalog, committed: committedCatalog }),
|
|
162
|
+
...(Array.isArray(before.terms) ? before.terms.map(t => ({ ...t, id: `before-${t.id}` })) : [term('before', null, 'missing plan terms')]),
|
|
163
|
+
term('installation', version.version === null ? null : after.version === before.version && after.host === before.host && before.version === version.version,
|
|
164
|
+
{ planned: { version: before.version, host: before.host }, observed: { version: after.version, host: after.host }, capturedPackage: version, basis: 'package at captured head plus caller-supplied T3 observations' }),
|
|
165
|
+
term('settings', !settings(after.effective) || !settings(after.requested) ? null : equal(after.requested, before.requested) && equal(after.effective, before.requested),
|
|
166
|
+
{ requested: before.requested, observedRequested: after.requested ?? null, effective: after.effective ?? null }),
|
|
167
|
+
term('terminal', !text(after.outcome) || !text(after.threadId) || !text(after.runId) ? null : ['completed', 'failed', 'unavailable', 'budget-exhausted', 'cancelled'].includes(after.outcome),
|
|
168
|
+
{ outcome: after.outcome, threadId: after.threadId ?? null, runId: after.runId ?? null }),
|
|
169
|
+
term('stale-result', !unavailable && after.output == null ? null : after.planSha256 === sha256(planBytes) && after.nonce === before.nonce && after.attempt === 1
|
|
170
|
+
&& (unavailable || (typeof after.output === 'string' && after.output.split(/\r?\n/).includes(`nonce: ${before.nonce}`))),
|
|
171
|
+
{ planSha256: sha256(planBytes), observedPlanSha256: after.planSha256, nonce: after.nonce, attempt: after.attempt, nonceEchoRequired: !unavailable }),
|
|
172
|
+
term('tokens', !Number.isSafeInteger(after.tokensUsed) || after.tokensUsed < 0 ? null : after.tokensUsed <= before.tokenLimit,
|
|
173
|
+
{ used: after.tokensUsed ?? null, limit: before.tokenLimit }),
|
|
174
|
+
term('time', elapsed === null || !timestamp(before.plannedAt) ? null : Date.parse(after.startedAt) >= Date.parse(before.plannedAt) && elapsed >= 0 && elapsed <= before.timeLimitMs,
|
|
175
|
+
{ plannedAt: before.plannedAt, startedAt: after.startedAt ?? null, finishedAt: after.finishedAt ?? null, elapsedMs: elapsed, limitMs: before.timeLimitMs }),
|
|
176
|
+
term('scenario-outcome', !text(after.outcome) || unavailable ? null : after.outcome === 'completed', { outcome: after.outcome, reason: after.reason ?? null }),
|
|
177
|
+
];
|
|
178
|
+
return { schemaVersion: 1, kind: 'r5-trace',
|
|
179
|
+
planReceipt: { path: realpathSync(flags['plan-receipt']), sha256: sha256(receiptBytes) },
|
|
180
|
+
result: { path: realpathSync(flags.result), sha256: sha256(resultBytes) }, before, after, terms };
|
|
181
|
+
}
|
|
182
|
+
function r5Main(args, io) {
|
|
183
|
+
if (args.length === 2 && args[1] === '--help') { io.stdout(help); return 0; }
|
|
184
|
+
try {
|
|
185
|
+
const [mode, ...rest] = args;
|
|
186
|
+
const required = mode === 'r5-plan' ? ['input'] : ['plan-receipt', 'result', 'repository', 'head', 'base'];
|
|
187
|
+
/** @type {Record<string, string>} */
|
|
188
|
+
const flags = {};
|
|
189
|
+
for (let i = 0; i < rest.length; i += 2) {
|
|
190
|
+
const key = rest[i].slice(2);
|
|
191
|
+
if (!rest[i].startsWith('--') || !required.includes(key) || key in flags || !rest[i + 1]) throw Error(`invalid flag: ${rest[i]}`);
|
|
192
|
+
flags[key] = rest[i + 1];
|
|
193
|
+
}
|
|
194
|
+
for (const key of required) if (!flags[key]) throw Error(`--${key} required`);
|
|
195
|
+
const report = mode === 'r5-plan' ? r5Plan(readJSON(flags.input)) : r5Trace(flags);
|
|
196
|
+
report.counts = Object.fromEntries(['pass', 'fail', 'unknown', 'n/a'].map(status => [status, report.terms.filter(t => t.status === status).length]));
|
|
197
|
+
io.stdout(JSON.stringify(report, null, 2));
|
|
198
|
+
return report.terms.some(t => t.status === 'unknown') ? 2 : 0;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (error.code === 'ENOENT' || error.code === 'EACCES') {
|
|
201
|
+
io.stdout(JSON.stringify({ terms: [term('input', null, error.message)], counts: { pass: 0, fail: 0, unknown: 1, 'n/a': 0 } }, null, 2));
|
|
202
|
+
return 2;
|
|
203
|
+
}
|
|
204
|
+
io.stderr(error.message); return 1;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function main(args, io = { stdout: console.log, stderr: console.error }) {
|
|
209
|
+
if (args.length === 1 && args[0] === '--help') { io.stdout(help); return 0; }
|
|
210
|
+
if (['r5-plan', 'r5-trace'].includes(args[0])) return r5Main(args, io);
|
|
211
|
+
/** @type {Record<string, string>} */
|
|
212
|
+
const flags = {};
|
|
213
|
+
const writableRoots = [];
|
|
214
|
+
const allowed = new Set(['repo', 'repository', 'head', 'base', 'out', 'cwd', 'snapshot', 'pr', 'image-digest', 'timeout-ms', 'log-bytes', 'writable-root']);
|
|
215
|
+
let argv;
|
|
216
|
+
try {
|
|
217
|
+
const separator = args.indexOf('--');
|
|
218
|
+
if (separator < 0 || separator === args.length - 1) throw Error('command required after --');
|
|
219
|
+
argv = args.slice(separator + 1);
|
|
220
|
+
for (let i = 0; i < separator; i += 2) {
|
|
221
|
+
const key = args[i].slice(2), value = args[i + 1];
|
|
222
|
+
if (!args[i].startsWith('--') || !allowed.has(key) || !value || i + 1 >= separator || (key !== 'writable-root' && key in flags)) throw Error(`invalid flag: ${args[i]}`);
|
|
223
|
+
if (key === 'writable-root') writableRoots.push(value);
|
|
224
|
+
else flags[key] = value;
|
|
225
|
+
}
|
|
226
|
+
for (const key of ['repo', 'repository', 'head', 'base', 'out']) if (!flags[key]) throw Error(`--${key} required`);
|
|
227
|
+
for (const key of ['timeout-ms', 'log-bytes']) if (flags[key] && (!/^[1-9]\d*$/.test(flags[key]) || !Number.isSafeInteger(Number(flags[key])) || Number(flags[key]) > 2147483647)) throw Error(`invalid --${key}`);
|
|
228
|
+
} catch (error) { io.stderr(error.message); return 1; }
|
|
229
|
+
const state = { active: null, signal: null };
|
|
230
|
+
const interrupt = (signal) => { state.signal = signal; if (state.active) killGroup(state.active); };
|
|
231
|
+
const sigint = () => interrupt('SIGINT'), sigterm = () => interrupt('SIGTERM'), sighup = () => interrupt('SIGHUP');
|
|
232
|
+
process.on('SIGINT', sigint);
|
|
233
|
+
process.on('SIGTERM', sigterm);
|
|
234
|
+
process.on('SIGHUP', sighup);
|
|
235
|
+
try {
|
|
236
|
+
if (['r5-plan', 'r5-trace'].includes(argv[2]) && fileIdentity(argv[1]).path === realpathSync(import.meta.path)
|
|
237
|
+
&& interpreterPath(argv[0]) !== realpathSync(process.execPath)) throw Object.assign(Error('R5 capture requires this helper\'s Bun interpreter'), { captureHold: true });
|
|
238
|
+
const repo = realpathSync(flags.repo), cwd = realpathSync(flags.cwd ?? flags.repo);
|
|
239
|
+
const binding = { tool: { name: 'check-run', version: captureVersion }, repo, repository: flags.repository, head: flags.head, base: flags.base,
|
|
240
|
+
snapshot: flags.snapshot, pr: flags.pr, sandboxImageDigest: flags['image-digest'] ?? null, writableRoots };
|
|
241
|
+
const step = await runCommand([], { evidence: flags.out }, 'check', argv, cwd, process.env,
|
|
242
|
+
{ timeoutMs: Number(flags['timeout-ms'] ?? 300000), logBytes: Number(flags['log-bytes'] ?? 1048576) }, state, argv, binding);
|
|
243
|
+
io.stdout(JSON.stringify(step, null, 2));
|
|
244
|
+
return step.terms.some(t => t.status === 'fail' || t.status === 'unknown') ? 2 : 0;
|
|
245
|
+
} catch (error) { io.stderr(error.message); return error.captureHold ? 2 : 1; }
|
|
246
|
+
finally { process.off('SIGINT', sigint); process.off('SIGTERM', sigterm); process.off('SIGHUP', sighup); }
|
|
247
|
+
}
|
|
248
|
+
if (import.meta.main) process.exit(await main(process.argv.slice(2)));
|
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import { gitArgv } from './git-argv.js';
|
|
2
|
+
import { gitArgv, gitEnv } from './git-argv.js';
|
|
3
3
|
// Read only the index. No hooks, configuration writes or working-tree reads.
|
|
4
4
|
import { readFileSync } from 'node:fs';
|
|
5
5
|
|
|
6
6
|
const ignoredPath = /(^|\/)(?:[^/]*\.lockb?|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|go\.sum)$|(^|\/)(?:dist|build|__mocks__|__fixtures__|fixtures|captures)\/|\.(?:min|generated|gen)\.|\.(?:map|snap)$/i;
|
|
7
7
|
const asset = /\.(?:svg|png|jpe?g|gif|webp|avif|ico|bmp|tiff?|pdf|woff2?|ttf|otf|eot|mp[34]|wav|ogg|flac|webm|mov|avi|zip|gz|bz2|xz|7z|rar|tar|exe|dll|so|dylib|wasm|bin|class|jar|pyc|sqlite3?|db)$/i;
|
|
8
|
-
let root = process.
|
|
8
|
+
let root = process.argv[3];
|
|
9
9
|
function git(...args) {
|
|
10
|
-
const result = Bun.spawnSync(gitArgv('--literal-pathspecs', ...args), {
|
|
10
|
+
const result = Bun.spawnSync(gitArgv('-C', root, '--literal-pathspecs', ...args), { env: gitEnv() });
|
|
11
11
|
if (result.exitCode !== 0) throw Error(result.stderr.toString().trim());
|
|
12
12
|
return result.stdout.toString();
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
try {
|
|
16
|
+
if (process.argv.length !== 4 || process.argv[2] !== '--repo' || !root || root.startsWith('-')) {
|
|
17
|
+
throw Error('pass --repo <Git-checkout-path> from a trusted cwd');
|
|
18
|
+
}
|
|
16
19
|
root = git('rev-parse', '--show-toplevel').trim();
|
|
17
20
|
const ignoreFile = git('rev-parse', '--path-format=absolute', '--git-path', 'info/token-limit-ignore').trim();
|
|
18
21
|
let ignores = [];
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { admitCapture, finishCapture } from './capture-identity.js';
|
|
2
|
+
import { closeSync, openSync, realpathSync, writeFileSync, writeSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const drainGraceMs = 200;
|
|
5
|
+
|
|
6
|
+
export function killGroup(proc) {
|
|
7
|
+
try { process.kill(-proc.pid, 'SIGKILL'); }
|
|
8
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function runCommand(commands, paths, kind, argv, cwd, env, limits, state, spawnArgv = argv, binding = null) {
|
|
12
|
+
let before = null;
|
|
13
|
+
if (binding) before = admitCapture(binding, paths.evidence, cwd);
|
|
14
|
+
const capturedCwd = binding ? realpathSync(cwd) : cwd;
|
|
15
|
+
const started = performance.now();
|
|
16
|
+
const step = { kind, argv, spawnArgv, exitCode: null, durationMs: 0, logPath: `${paths.evidence}/${crypto.randomUUID()}-${kind}.log`, timedOut: false, logBytes: 0, omittedBytes: 0, logIncomplete: false };
|
|
17
|
+
step.receiptPath = `${step.logPath.slice(0, -4)}.json`;
|
|
18
|
+
commands.push(step);
|
|
19
|
+
const fd = openSync(step.logPath, 'wx', 0o600);
|
|
20
|
+
let proc;
|
|
21
|
+
let timer;
|
|
22
|
+
let graceTimer;
|
|
23
|
+
let logging = true;
|
|
24
|
+
const readers = [];
|
|
25
|
+
function log(chunk) {
|
|
26
|
+
if (!logging) return;
|
|
27
|
+
const kept = Math.min(chunk.length, limits.logBytes - step.logBytes);
|
|
28
|
+
if (kept) writeSync(fd, chunk.subarray(0, kept));
|
|
29
|
+
step.logBytes += kept;
|
|
30
|
+
step.omittedBytes += chunk.length - kept;
|
|
31
|
+
}
|
|
32
|
+
async function drain(reader) {
|
|
33
|
+
try {
|
|
34
|
+
while (true) {
|
|
35
|
+
const { done, value } = await reader.read();
|
|
36
|
+
if (done) return;
|
|
37
|
+
log(value);
|
|
38
|
+
}
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (logging) { step.error = error.message; killGroup(proc); }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
proc = Bun.spawn(spawnArgv, { cwd, env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', detached: true });
|
|
45
|
+
state.active = proc;
|
|
46
|
+
readers.push(proc.stdout.getReader(), proc.stderr.getReader());
|
|
47
|
+
const drained = Promise.all(readers.map(drain));
|
|
48
|
+
const exited = proc.exited.then((code) => {
|
|
49
|
+
if (logging) step.exitCode = code;
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
killGroup(proc);
|
|
52
|
+
});
|
|
53
|
+
/** @type {Promise<void>} */
|
|
54
|
+
const timeout = new Promise((resolve) => {
|
|
55
|
+
timer = setTimeout(() => { step.timedOut = true; killGroup(proc); resolve(); }, limits.timeoutMs);
|
|
56
|
+
});
|
|
57
|
+
await Promise.race([exited, timeout]);
|
|
58
|
+
const complete = await Promise.race([
|
|
59
|
+
Promise.all([exited, drained]).then(() => true),
|
|
60
|
+
new Promise((resolve) => { graceTimer = setTimeout(() => resolve(false), drainGraceMs); }),
|
|
61
|
+
]);
|
|
62
|
+
step.logIncomplete = !complete;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
step.error = error.message;
|
|
65
|
+
log(new TextEncoder().encode(error.message));
|
|
66
|
+
} finally {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
clearTimeout(graceTimer);
|
|
69
|
+
logging = false;
|
|
70
|
+
if (proc) killGroup(proc);
|
|
71
|
+
// Cancel without another EOF wait. Escaped writers may retain the other pipe end forever.
|
|
72
|
+
for (const reader of readers) reader.cancel().then(() => reader.releaseLock()).catch(() => {});
|
|
73
|
+
state.active = null;
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
step.durationMs = Math.round(performance.now() - started);
|
|
76
|
+
if (binding) finishCapture(step, binding, before, capturedCwd, state.signal);
|
|
77
|
+
writeFileSync(step.receiptPath, `${JSON.stringify(step, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
78
|
+
}
|
|
79
|
+
return step;
|
|
80
|
+
}
|
|
81
|
+
|