axstack 0.67.0 → 0.69.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.
Files changed (97) hide show
  1. package/README.md +2 -2
  2. package/docs/host-operations.md +3 -6
  3. package/docs/installation.md +10 -10
  4. package/docs/workflows.md +7 -11
  5. package/package.json +2 -2
  6. package/profiles/presets/claude-only.json +2 -2
  7. package/profiles/presets/codex-only.json +2 -2
  8. package/profiles/presets/mixed.json +2 -2
  9. package/skills/axstack/references/automations.md +18 -33
  10. package/skills/axstack/references/autopilot.md +1 -0
  11. package/skills/axstack/references/capture-receipts.md +22 -0
  12. package/skills/axstack/references/contracts.md +1 -1
  13. package/skills/axstack/references/lifecycle.md +1 -1
  14. package/skills/axstack/references/live-run.md +59 -0
  15. package/skills/axstack/references/local-artifacts.md +1 -1
  16. package/skills/axstack/references/pr-shape.md +13 -16
  17. package/skills/axstack/references/review-manager-prompt.md +38 -42
  18. package/skills/axstack/references/role-roster.md +1 -1
  19. package/skills/axstack/references/run-record.md +7 -5
  20. package/skills/axstack/references/test-audit-weekly.md +1 -2
  21. package/skills/axstack/references/ui-verification.md +5 -3
  22. package/skills/axstack/references/workspace-hygiene.md +3 -0
  23. package/skills/axstack/sandbox/Dockerfile +28 -0
  24. package/skills/axstack/sandbox/host-execution.md +14 -0
  25. package/skills/axstack/sandbox/inventory.json +503 -0
  26. package/skills/axstack/sandbox/launcher-capture.js +63 -0
  27. package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
  28. package/skills/axstack/sandbox/launcher-contracts.js +35 -0
  29. package/skills/axstack/sandbox/launcher-docker.js +75 -0
  30. package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
  31. package/skills/axstack/sandbox/launcher-host.js +165 -0
  32. package/skills/axstack/sandbox/launcher-host.json +5 -0
  33. package/skills/axstack/sandbox/launcher-image.json +4 -0
  34. package/skills/axstack/sandbox/launcher-interface.md +7 -0
  35. package/skills/axstack/sandbox/launcher-policy.js +135 -0
  36. package/skills/axstack/sandbox/launcher-policy.json +121 -0
  37. package/skills/axstack/sandbox/launcher-runtime.js +157 -0
  38. package/skills/axstack/sandbox/launcher-source.js +72 -0
  39. package/skills/axstack/sandbox/launcher.js +106 -0
  40. package/skills/axstack/sandbox/network-address.js +39 -0
  41. package/skills/axstack/sandbox/network-firewall.js +81 -0
  42. package/skills/axstack/sandbox/network-rules.js +86 -0
  43. package/skills/axstack/sandbox/network-runtime.js +109 -0
  44. package/skills/axstack/sandbox/network.js +49 -0
  45. package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
  46. package/skills/axstack/sandbox/probes-check.js +185 -0
  47. package/skills/axstack/sandbox/probes-exec.js +20 -0
  48. package/skills/axstack/sandbox/probes-image-build.js +129 -0
  49. package/skills/axstack/sandbox/probes-image-pins.json +370 -0
  50. package/skills/axstack/sandbox/probes-link-local.js +25 -0
  51. package/skills/axstack/sandbox/probes-storage.js +33 -0
  52. package/skills/axstack/sandbox/probes-udp.js +44 -0
  53. package/skills/axstack/sandbox/probes.js +239 -0
  54. package/skills/axstack/sandbox/proxy-command.js +6 -0
  55. package/skills/axstack/sandbox/proxy-config.json +9 -0
  56. package/skills/axstack/sandbox/proxy-dns.js +114 -0
  57. package/skills/axstack/sandbox/proxy-policy.js +22 -0
  58. package/skills/axstack/sandbox/proxy.js +119 -0
  59. package/skills/axstack/sandbox/reap.md +7 -0
  60. package/skills/axstack/sandbox/sidecars.json +153 -0
  61. package/skills/axstack/sandbox/storage-checks.js +39 -0
  62. package/skills/axstack/sandbox/storage-cleanup.js +49 -0
  63. package/skills/axstack/sandbox/storage-execution.js +110 -0
  64. package/skills/axstack/sandbox/storage-plan.js +78 -0
  65. package/skills/axstack/sandbox/storage-support.js +91 -0
  66. package/skills/axstack/sandbox/storage.js +75 -0
  67. package/skills/axstack/scripts/archive-evidence.js +2 -2
  68. package/skills/axstack/scripts/capture-identity.js +122 -0
  69. package/skills/axstack/scripts/check-run.js +248 -0
  70. package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
  71. package/skills/axstack/scripts/command-capture.js +81 -0
  72. package/skills/axstack/scripts/evidence-inspector.js +182 -0
  73. package/skills/axstack/scripts/git-argv.js +6 -0
  74. package/skills/axstack/scripts/image-evidence.js +183 -0
  75. package/skills/axstack/scripts/lane-owner.js +183 -0
  76. package/skills/axstack/scripts/pr-digest.js +17 -1
  77. package/skills/axstack/scripts/pr-fresh.js +139 -0
  78. package/skills/axstack/scripts/pr-shape.js +54 -29
  79. package/skills/axstack/scripts/readiness-run.js +3 -75
  80. package/skills/axstack/scripts/readiness.js +2 -2
  81. package/skills/axstack/scripts/run-init.js +13 -11
  82. package/skills/axstack/scripts/schedule-drift.js +221 -4
  83. package/skills/axstack-audit/references/record.md +1 -1
  84. package/skills/axstack-brainstorm/references/arena.md +5 -5
  85. package/skills/axstack-explain/references/inline-pages.md +8 -4
  86. package/skills/axstack-implement/SKILL.md +6 -5
  87. package/skills/axstack-review/SKILL.md +2 -3
  88. package/skills/axstack-review/references/candidate-brief.md +12 -21
  89. package/skills/axstack-review/references/codebase-brief.md +1 -0
  90. package/skills/axstack-review/references/codebase-mode.md +4 -1
  91. package/skills/axstack-review/references/codebase-report.md +2 -1
  92. package/skills/axstack-review/references/peer-mode.md +11 -12
  93. package/skills/axstack-review/references/review-candidate.md +2 -2
  94. package/skills/axstack-review/references/review-receipt.md +8 -3
  95. package/skills/axstack-verify/SKILL.md +10 -4
  96. package/skills/axstack-watch/references/proven-verification.md +3 -2
  97. package/skills/axstack-watch/references/readiness.md +56 -61
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env bun
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ const HELP = `pr-fresh — review event observations (R2 fact mode)
5
+ Run from trusted cwd / with bun --no-env-file <installed-script> and explicit:
6
+ --repo OWNER/NAME --pr N --head SHA --base SHA --base-ref NAME --phase admission|submission
7
+ --repo, --pr Expected repository and PR identity (also required with saved input).
8
+ --head, --base Pinned full commit SHAs; --base-ref pins the base branch identity.
9
+ --phase Select review.admission or review.submission in the policy artifact.
10
+ --policy FILE Default: installed ../references/schedule-policy.json (W2-1).
11
+ Supported version:1 review phase: {status:"known",headAgeThresholdSeconds:N,
12
+ clockSemantics:"head-commit-committed-date",pendingCheckTreatment:"defer"|"allow"}.
13
+ N is a nonnegative integer, inclusive. This clock is commit age, NOT push/settle age.
14
+ Driver: recorded age < N defers; age >= N meets the age term. defer waits on
15
+ pending checks; allow adds no pending gate. Unknown applicable gating terms hold.
16
+ status:"unknown" with all three gate fields null is unrecorded, with no gate.
17
+ policy.evidence.unrecorded distinguishes it from malformed/unavailable policy.
18
+ Both report unknown; the driver ignores non-event terms only for unrecorded phases.
19
+ --input FILE Saved gh api graphql response; no network. Saved bytes prove no live freshness.
20
+ --now ISO Timezone-qualified comparison time; default current UTC.
21
+ --help Show flags, effects and limitations.
22
+ Without --input, one read-only gh api graphql query observes the PR and head checks.
23
+ No writes, persistent state, retries, dispatch, submission, merge, scheduling or authority.
24
+ API/permission/pagination gaps are unknown; unobserved checks never imply success.
25
+ pendingChecks passes iff no observed pending checks; checksSuccessful measures terminal checks.
26
+ The driver applies the recorded policy and discard/hold rules, before dispatch and submission.
27
+ Stdout: per-term pass/fail/unknown/n/a with evidence and counts only, no aggregate verdict.
28
+ Exit: 0 measured (including failed facts), 1 invalid CLI/error, 2 incomplete (unknown facts).
29
+ `;
30
+ const time = (s) => typeof s === 'string' && /T.*(?:Z|[+-]\d\d:\d\d)$/.test(s) ? Date.parse(s) : NaN;
31
+ const sha = (s) => typeof s === 'string' && /^[a-f0-9]{40}$/.test(s);
32
+ function options(argv) {
33
+ const args = { '--policy': `${import.meta.dir}/../references/schedule-policy.json`, '--now': new Date().toISOString() };
34
+ const seen = new Set();
35
+ for (let i = 0; i < argv.length; i += 2) {
36
+ const key = argv[i], value = argv[i + 1];
37
+ if (!['--repo', '--pr', '--head', '--base', '--base-ref', '--phase', '--policy', '--input', '--now'].includes(key) ||
38
+ !value || value.startsWith('--') || seen.has(key)) throw Error(`invalid argument: ${key}`);
39
+ args[key] = value;
40
+ seen.add(key);
41
+ }
42
+ if (!/^[\w.-]+\/[\w.-]+$/.test(args['--repo'] ?? '') || !/^[1-9]\d*$/.test(args['--pr'] ?? '') ||
43
+ !Number.isSafeInteger(Number(args['--pr'])) || !sha(args['--head']) || !sha(args['--base']) ||
44
+ !args['--base-ref'] || !['admission', 'submission'].includes(args['--phase']) || !Number.isFinite(time(args['--now']))) {
45
+ throw Error('expected repo, PR, full head/base SHAs, base-ref, phase and timezone-qualified now; see --help');
46
+ }
47
+ return args;
48
+ }
49
+ function observe(args) {
50
+ if (args['--input']) return JSON.parse(readFileSync(args['--input'], 'utf8'));
51
+ const [owner, name] = args['--repo'].split('/');
52
+ const query = `query { repository(owner:${JSON.stringify(owner)},name:${JSON.stringify(name)}) {
53
+ nameWithOwner pullRequest(number:${args['--pr']}) {
54
+ number state isDraft merged headRefOid baseRefOid baseRefName
55
+ commits(last:1) { nodes { commit { oid committedDate statusCheckRollup {
56
+ contexts(first:100) { pageInfo { hasNextPage } nodes {
57
+ __typename ... on CheckRun { name status conclusion } ... on StatusContext { context state }
58
+ } }
59
+ } } } }
60
+ }
61
+ } }`;
62
+ const r = Bun.spawnSync(['gh', 'api', 'graphql', '-f', `query=${query}`], { cwd: '/', stdout: 'pipe', stderr: 'pipe' });
63
+ if (r.exitCode !== 0) throw Error('gh api unavailable or failed');
64
+ return JSON.parse(r.stdout.toString());
65
+ }
66
+ function report(args) {
67
+ const terms = [];
68
+ const add = (id, status, evidence) => terms.push({ id, status, evidence });
69
+ let policy, policySha256 = null, response, observationError;
70
+ try {
71
+ const bytes = readFileSync(args['--policy']);
72
+ policySha256 = new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
73
+ policy = JSON.parse(bytes.toString());
74
+ } catch { /* Unavailable policy does not erase independently observed PR facts. */ }
75
+ const phase = policy?.review?.[args['--phase']];
76
+ const knownPolicy = policy?.version === 1 && phase?.status === 'known' &&
77
+ Number.isSafeInteger(phase.headAgeThresholdSeconds) && phase.headAgeThresholdSeconds >= 0 &&
78
+ phase.clockSemantics === 'head-commit-committed-date' && ['defer', 'allow'].includes(phase.pendingCheckTreatment);
79
+ const unrecorded = policy?.version === 1 && phase?.status === 'unknown' &&
80
+ phase.headAgeThresholdSeconds === null && phase.clockSemantics === null && phase.pendingCheckTreatment === null;
81
+ add('policy', knownPolicy ? 'pass' : 'unknown', { phase: args['--phase'], sha256: policySha256,
82
+ recorded: phase ?? null, unrecorded, malformed: !knownPolicy && !unrecorded,
83
+ reason: knownPolicy ? 'supported recorded policy' : unrecorded ? 'unrecorded phase; no gate' : 'absent, unreadable, malformed or unsupported policy' });
84
+ try { response = observe(args); } catch { observationError = 'saved input or gh api unavailable/malformed'; }
85
+ const repository = response?.data?.repository;
86
+ const pr = !response?.errors?.length && repository?.nameWithOwner?.toLowerCase() === args['--repo'].toLowerCase() &&
87
+ repository?.pullRequest?.number === Number(args['--pr']) ? repository.pullRequest : null;
88
+ const fact = (id, known, passes, evidence) => add(id, !pr || !known ? 'unknown' : passes ? 'pass' : 'fail',
89
+ pr ? evidence : { reason: observationError ?? 'incomplete API response or identity mismatch' });
90
+ fact('open', ['OPEN', 'CLOSED', 'MERGED'].includes(pr?.state), pr?.state === 'OPEN', { state: pr?.state });
91
+ fact('nonDraft', typeof pr?.isDraft === 'boolean', pr?.isDraft === false, { isDraft: pr?.isDraft });
92
+ fact('unmerged', typeof pr?.merged === 'boolean', pr?.merged === false, { merged: pr?.merged });
93
+ fact('pinnedHead', sha(pr?.headRefOid), pr?.headRefOid === args['--head'], { expected: args['--head'], observed: pr?.headRefOid });
94
+ fact('baseUnchanged', sha(pr?.baseRefOid) && typeof pr?.baseRefName === 'string',
95
+ pr?.baseRefOid === args['--base'] && pr?.baseRefName === args['--base-ref'],
96
+ { expected: { sha: args['--base'], ref: args['--base-ref'] }, observed: { sha: pr?.baseRefOid, ref: pr?.baseRefName } });
97
+ const commits = pr?.commits?.nodes;
98
+ const commit = Array.isArray(commits) && commits.length === 1 && commits[0]?.commit?.oid === pr.headRefOid ? commits[0].commit : null;
99
+ const age = (time(args['--now']) - time(commit?.committedDate)) / 1000;
100
+ fact('headAge', knownPolicy && Number.isFinite(age) && age >= 0, age >= phase?.headAgeThresholdSeconds,
101
+ { committedDate: commit?.committedDate, ageSeconds: Number.isFinite(age) ? age : null,
102
+ thresholdSeconds: knownPolicy ? phase.headAgeThresholdSeconds : null, clock: 'head-commit-committed-date' });
103
+ const rollup = commit?.statusCheckRollup;
104
+ const connection = rollup?.contexts;
105
+ const checks = rollup === null ? [] : connection?.pageInfo?.hasNextPage === false && Array.isArray(connection.nodes) ? connection.nodes : null;
106
+ const pending = [], failed = [], unknown = [], terminal = [];
107
+ for (const c of checks ?? []) {
108
+ const name = c?.name ?? c?.context ?? '(unnamed)';
109
+ if (c?.__typename === 'CheckRun' && ['QUEUED', 'IN_PROGRESS', 'WAITING', 'PENDING', 'REQUESTED'].includes(c.status) ||
110
+ c?.__typename === 'StatusContext' && ['PENDING', 'EXPECTED'].includes(c.state)) pending.push(name);
111
+ else if (c?.__typename === 'CheckRun' && c.status === 'COMPLETED' &&
112
+ ['SUCCESS', 'NEUTRAL', 'SKIPPED', 'FAILURE', 'CANCELLED', 'TIMED_OUT', 'ACTION_REQUIRED', 'STALE', 'STARTUP_FAILURE'].includes(c.conclusion)) {
113
+ terminal.push(name);
114
+ if (!['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(c.conclusion)) failed.push(name);
115
+ } else if (c?.__typename === 'StatusContext' && ['SUCCESS', 'FAILURE', 'ERROR'].includes(c.state)) {
116
+ terminal.push(name);
117
+ if (c.state !== 'SUCCESS') failed.push(name);
118
+ } else unknown.push(name);
119
+ }
120
+ const evidence = { pending, failed, unknown, terminal, complete: checks !== null && unknown.length === 0 };
121
+ fact('pendingChecks', evidence.complete, pending.length === 0, evidence);
122
+ if (pr && evidence.complete && !terminal.length) add('checksSuccessful', 'n/a', evidence);
123
+ else fact('checksSuccessful', evidence.complete, failed.length === 0, evidence);
124
+ const counts = { pass: 0, fail: 0, unknown: 0, 'n/a': 0 };
125
+ for (const t of terms) counts[t.status]++;
126
+ return { version: 1, repo: args['--repo'], pr: Number(args['--pr']), phase: args['--phase'],
127
+ source: args['--input'] ? 'saved' : 'gh api graphql', comparedAt: args['--now'], terms, counts };
128
+ }
129
+ try {
130
+ if (process.argv.slice(2).length === 1 && process.argv[2] === '--help') console.log(HELP);
131
+ else {
132
+ const result = report(options(process.argv.slice(2)));
133
+ console.log(JSON.stringify(result, null, 2));
134
+ process.exitCode = result.counts.unknown ? 2 : 0;
135
+ }
136
+ } catch (error) {
137
+ console.error(`pr-fresh: ${error.message}`);
138
+ process.exitCode = 1;
139
+ }
@@ -1,12 +1,15 @@
1
- import { gitArgv } from './git-argv.js';
1
+ import { gitArgv, gitEnv } from './git-argv.js';
2
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 help = `Usage: bun scripts/pr-shape.js --base <ref> --head <ref>
6
- Example: bun scripts/pr-shape.js --base main --head HEAD
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 new Error(`missing ref; pass ${flag} <commit-or-branch>`);
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 new Error(`missing ref; pass ${flag} <commit-or-branch>`);
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: { ...process.env, GIT_ATTR_NOSYSTEM: '1' } });
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
- if (renamed) { i++; path = tokens[++i]; } // -z rename: empty path, old path, new path.
89
- rows.push({ path, renamed, binary: added === '-', additions: added === '-' ? 0 : Number(added),
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;
@@ -108,7 +119,7 @@ function summarize(rows, evidence) {
108
119
 
109
120
  const proofFields = { files: 'Files', additions: 'Lines added', deletions: 'Lines removed',
110
121
  commits: 'Commits', head: 'Head SHA', base: 'Base SHA' };
111
- const proofHelp = `Usage: bun scripts/pr-shape.js --proof --base <ref> --head <ref> [--body <path>]
122
+ const proofHelp = `Usage: bun scripts/pr-shape.js --proof --repo <path> --base <ref> --head <ref> [--body <path>]
112
123
  bun scripts/pr-shape.js --proof --pr <number> --repo <owner/repo> [--body <path>]
113
124
 
114
125
  --proof Render/check PR Proof facts (separate from the unchanged shape mode)
@@ -116,7 +127,7 @@ const proofHelp = `Usage: bun scripts/pr-shape.js --proof --base <ref> --head <r
116
127
  --head Current candidate ref, resolved with read-only Git
117
128
  --body Optional UTF-8 PR body file to check; never modified
118
129
  --pr Positive PR number; read-only gh api fetches current facts and body
119
- --repo Explicit owner/repo for --pr; cannot combine --pr with --base/--head
130
+ --repo Required Git checkout path, or owner/repo with --pr; --pr excludes --base/--head
120
131
  --help Show this mode's flags, output and exit codes
121
132
 
122
133
  JSON: block (Markdown or null if facts unavailable), terms (each status, value,
@@ -149,8 +160,8 @@ function proofOptions(argv) {
149
160
  if (options['--pr']) {
150
161
  if (!/^[1-9]\d*$/.test(options['--pr']) || !/^[\w.-]+\/[\w.-]+$/.test(options['--repo'] ?? '') ||
151
162
  options['--base'] || options['--head']) throw Error('--pr requires --repo owner/repo and excludes --base/--head');
152
- } else if (!options['--base'] || !options['--head'] || options['--repo']) {
153
- throw Error('proof requires --base and --head, or --pr and --repo');
163
+ } else if (!options['--base'] || !options['--head'] || !options['--repo']) {
164
+ throw Error('proof requires --repo with --base and --head, or --pr');
154
165
  }
155
166
  return options;
156
167
  }
@@ -159,7 +170,7 @@ function proof(argv, io) {
159
170
  if (argv.includes('--help')) { io.stdout(proofHelp); return 0; }
160
171
  const options = proofOptions(argv);
161
172
  const terms = Object.keys(proofFields).map((id) => ({ id, status: 'unknown', value: null,
162
- evidence: { cwd: process.cwd(), commands: [], results: [], reason: 'data unavailable' } }));
173
+ evidence: { cwd: options['--pr'] ? process.cwd() : options['--repo'], commands: [], results: [], reason: 'data unavailable' } }));
163
174
  const term = (id) => terms.find((t) => t.id === id);
164
175
  const query = (ids, args) => {
165
176
  for (const id of ids) term(id).evidence.commands.push(args);
@@ -209,19 +220,20 @@ function proof(argv, io) {
209
220
  else bodyError = 'PR body unavailable in gh response';
210
221
  } catch { bodyError = 'invalid gh JSON response'; }
211
222
  } else {
223
+ const gitCommand = (...args) => command(options['--repo'], ...args);
212
224
  for (const id of ['base', 'head']) {
213
- const raw = query([id], command('rev-parse', '--verify', '--end-of-options', `${options[`--${id}`]}^{commit}`));
225
+ const raw = query([id], gitCommand('rev-parse', '--verify', '--end-of-options', `${options[`--${id}`]}^{commit}`));
214
226
  if (raw !== null) assign(id, raw.trim());
215
227
  }
216
228
  const counts = ['files', 'additions', 'deletions', 'commits'];
217
229
  if (term('base').value && term('head').value) {
218
230
  const base = term('base').value, head = term('head').value;
219
- const commits = query(['commits'], command('rev-list', '--count', `${base}..${head}`, '--'));
231
+ const commits = query(['commits'], gitCommand('rev-list', '--count', `${base}..${head}`, '--'));
220
232
  if (commits !== null && /^\d+\s*$/.test(commits)) assign('commits', Number(commits));
221
233
  const ids = counts.slice(0, 3);
222
- const merge = query(ids, command('merge-base', base, head));
234
+ const merge = query(ids, gitCommand('merge-base', base, head));
223
235
  if (merge !== null) {
224
- const diff = query(ids, command('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--numstat', '-z', `${merge.trim()}..${head}`, '--'));
236
+ const diff = query(ids, gitCommand('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--numstat', '-z', `${merge.trim()}..${head}`, '--'));
225
237
  if (diff !== null) {
226
238
  const rows = numstat(diff);
227
239
  assign('files', rows.length);
@@ -265,16 +277,19 @@ function proof(argv, io) {
265
277
  }
266
278
 
267
279
  export function main(argv, io = { stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }) {
280
+ let sandboxPath;
268
281
  try {
269
282
  if (argv[0] === '--proof') return proof(argv.slice(1), io);
270
283
  if (argv.includes('--help')) { io.stdout(`${help}\n${proofHelp}`); return 0; }
271
284
  const options = optionsFrom(argv);
272
- const root = run(command('rev-parse', '--show-toplevel'));
273
- if (root.code) throw new Error('run this helper from a Git checkout');
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>');
274
289
  const repo = root.stdout.replace(/\n$/, '');
275
- const gitCommand = (...args) => command('-C', repo, ...args);
290
+ const gitCommand = (...args) => command(repo, ...args);
276
291
  const resolve = (flag) => {
277
- const result = run(gitCommand('rev-parse', '--verify', '--end-of-options', `${options[flag]}^{commit}`));
292
+ const result = query(gitCommand('rev-parse', '--verify', '--end-of-options', `${options[flag]}^{commit}`));
278
293
  if (result.code) throw new Error(`unresolved ${flag}; pass ${flag} <existing-commit-or-branch>`);
279
294
  return result.stdout.trim();
280
295
  };
@@ -282,18 +297,24 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
282
297
  if (options['--source']) inputs.sourceRef = options['--source'];
283
298
  const sync = syncTerm(inputs, gitCommand);
284
299
  const mergeCommand = gitCommand('merge-base', inputs.base, inputs.head);
285
- const merge = run(mergeCommand);
300
+ const merge = query(mergeCommand);
286
301
  if (merge.code) {
287
302
  const unknown = { status: 'unknown', evidence: { commands: [mergeCommand], reason: merge.stderr.trim() || 'no common ancestor' } };
288
303
  io.stdout(`${JSON.stringify({ inputs, sync, mergeBase: { ...unknown, value: null }, totals: unknown,
289
- buckets: { lockfiles: unknown, generated: unknown } })}\n`);
304
+ buckets: { lockfiles: unknown, generated: unknown },
305
+ 'sandbox-path': { ...unknown, evidence: { ...unknown.evidence, prefix: sandboxPrefix } } })}\n`);
290
306
  return 2;
291
307
  }
292
308
  const mergeBase = merge.stdout.trim();
293
- const diffCommand = gitCommand('diff', '-M', '--no-relative', '--no-ext-diff', '--no-textconv', '--numstat', '-z', `${mergeBase}..${inputs.head}`, '--');
294
- const diff = run(diffCommand);
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);
295
311
  if (diff.code) throw new Error(`diff unavailable; verify --base and --head refer to readable commits: ${diff.stderr.trim()}`);
296
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' } };
297
318
  const attrCommand = gitCommand('check-attr', `--source=${inputs.head}`, '--stdin', '-z', 'linguist-generated');
298
319
  const attrEvidence = { commands: [diffCommand, attrCommand], environment: { GIT_ATTR_NOSYSTEM: '1' },
299
320
  stdin: 'feed check-attr the NUL-separated destination paths from the full numstat records',
@@ -312,7 +333,8 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
312
333
  }
313
334
  generated = summarize(rows.filter((row) => paths.has(row.path)), attrEvidence);
314
335
  }
315
- io.stdout(`${JSON.stringify({ inputs, sync, mergeBase: { status: 'pass', value: mergeBase, evidence: { commands: [mergeCommand] } },
336
+ io.stdout(`${JSON.stringify({ inputs, sync, 'sandbox-path': sandboxPath,
337
+ mergeBase: { status: 'pass', value: mergeBase, evidence: { commands: [mergeCommand] } },
316
338
  totals: summarize(rows, { commands: [diffCommand], select: 'all records; no exclusions' }),
317
339
  buckets: { lockfiles: summarize(rows.filter((row) => lockfiles.includes(row.path.split('/').at(-1))),
318
340
  { commands: [diffCommand], select: 'destination basename is exactly one of lockfileNames', lockfileNames: lockfiles }), generated },
@@ -320,6 +342,9 @@ export function main(argv, io = { stdout: (text) => process.stdout.write(text),
320
342
  })}\n`);
321
343
  return generated.status === 'unknown' || sync.status === 'unknown' ? 2 : 0;
322
344
  } catch (error) {
345
+ if (sandboxPath) io.stdout(`${JSON.stringify({ 'sandbox-path': {
346
+ status: 'unknown', evidence: { ...sandboxPath.evidence, reason: error.message },
347
+ } })}\n`);
323
348
  io.stderr(`pr-shape error: ${error.message}\n`);
324
349
  return 1;
325
350
  }
@@ -1,5 +1,6 @@
1
+ import { killGroup, runCommand } from './command-capture.js';
1
2
  import { gitArgv } from './git-argv.js';
2
- import { chmodSync, closeSync, lstatSync, mkdirSync, mkdtempSync, openSync, realpathSync, rmSync, writeFileSync, writeSync } from 'node:fs';
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 in a Git repository; run this helper from a Git checkout');
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');