@imdeadpool/guardex 8.4.0 → 8.4.2
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/CONTRIBUTING.md +13 -4
- package/README.md +223 -1
- package/THIRD-PARTY-NOTICES.md +29 -0
- package/bin/multiagent-safety.js +9 -12
- package/package.json +4 -2
- package/skills/gitguardex/SKILL.md +28 -0
- package/skills/pr-lens/SKILL.md +87 -0
- package/src/abide.js +534 -0
- package/src/agents/activity.js +23 -4
- package/src/agents/inspect.js +15 -6
- package/src/agents/launch.js +6 -1
- package/src/agents/process-lease.js +84 -0
- package/src/agents/sessions.js +96 -16
- package/src/agents/start.js +18 -9
- package/src/agents/status.js +35 -14
- package/src/agents/supervise.js +87 -0
- package/src/budget/index.js +6 -1
- package/src/cli/args.js +71 -77
- package/src/cli/commands/agents.js +38 -10
- package/src/cli/commands/branch.js +116 -103
- package/src/cli/commands/claude.js +604 -50
- package/src/cli/commands/codex.js +359 -0
- package/src/cli/commands/context.js +52 -0
- package/src/cli/commands/mcp.js +5 -1
- package/src/cli/commands/pr.js +138 -3
- package/src/cli/commands/review.js +3 -1
- package/src/cli/commands/setup.js +25 -0
- package/src/cli/commands/status.js +128 -60
- package/src/cli/commands/storage.js +24 -0
- package/src/cli/commands/usage.js +48 -0
- package/src/cli/commands/watch.js +157 -47
- package/src/cli/commands/worktree-copy-ignored.js +38 -0
- package/src/cli/commands/worktree-estimate.js +69 -0
- package/src/cli/commands/worktree-hooks.js +62 -0
- package/src/cli/commands/worktree-navigation.js +71 -0
- package/src/cli/commands/worktree-provision.js +92 -0
- package/src/cli/main.js +229 -110
- package/src/cli/shared/gate-flags.js +131 -0
- package/src/cli/shared/scaffolding.js +31 -3
- package/src/cli/shared-locks.js +3 -1
- package/src/cockpit/pane-actions.js +43 -7
- package/src/context.js +373 -17
- package/src/doctor/index.js +29 -35
- package/src/finish/events.js +254 -0
- package/src/finish/index.js +322 -62
- package/src/finish/post-branch-finish-cleanup.js +316 -22
- package/src/finish/preflight.js +44 -1
- package/src/finish/progress.js +36 -0
- package/src/finish/review-gate.js +317 -127
- package/src/finish/review-receipt.js +156 -0
- package/src/finish/with-claims-lock.py +29 -0
- package/src/git/index.js +179 -42
- package/src/hooks/index.js +68 -3
- package/src/mcp/collect.js +61 -5
- package/src/mcp/server.js +4 -0
- package/src/output/index.js +167 -1
- package/src/pr-lens-publish.js +93 -0
- package/src/pr-lens.js +184 -0
- package/src/pr-respond.js +860 -0
- package/src/pr-review.js +519 -159
- package/src/pr.js +73 -14
- package/src/provider-binary.js +21 -0
- package/src/review-diff-context.js +90 -0
- package/src/review-fix.js +23 -17
- package/src/scaffold/agent-worktree-prep.js +14 -12
- package/src/scaffold/dependency-store.js +234 -0
- package/src/scaffold/index.js +13 -1
- package/src/scaffold/provision-approvals.js +83 -0
- package/src/scaffold/provision-config.js +169 -40
- package/src/shared-git-state.js +11 -1
- package/src/speckit/index.js +12 -1
- package/src/storage/run-artifacts.js +185 -0
- package/src/toolchain/index.js +322 -2
- package/src/worktree-copy-ignored.js +200 -0
- package/src/worktree-hook-worker.js +29 -0
- package/src/worktree-hooks.js +333 -0
- package/src/worktree-navigation.js +248 -0
- package/src/worktree-picker.js +89 -0
- package/src/worktree-quota.js +100 -0
- package/src/worktree-start.js +100 -0
- package/templates/AGENTS.multiagent-safety.md +8 -0
- package/templates/AGENTS.multiagent-safety.min.md +3 -1
- package/templates/codex/skills/gitguardex/SKILL.md +28 -0
- package/templates/codex/skills/opensrc/SKILL.md +24 -0
- package/templates/githooks/post-merge +16 -2
- package/templates/scripts/agent-autofinish-watch.sh +17 -18
- package/templates/scripts/agent-branch-finish.sh +180 -19
- package/templates/scripts/agent-branch-merge.sh +7 -32
- package/templates/scripts/agent-branch-start.sh +202 -43
- package/templates/scripts/agent-claude-stop-finish.sh +4 -27
- package/templates/scripts/agent-file-locks.py +257 -29
- package/templates/scripts/agent-preflight.sh +3 -0
- package/templates/scripts/agent-worktree-prune.sh +975 -63
- package/templates/scripts/codex-agent.sh +55 -5
- package/templates/scripts/lib/guardex-base-branch.sh +207 -0
- package/templates/scripts/openspec/init-change-workspace.sh +10 -18
- package/templates/scripts/review-bot-watch.sh +171 -4
package/src/doctor/index.js
CHANGED
|
@@ -177,21 +177,6 @@ function collectDoctorDeletedPaths(worktreePath) {
|
|
|
177
177
|
return Array.from(deleted);
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
function collectWorktreeDirtyPaths(worktreePath) {
|
|
181
|
-
const dirty = new Set();
|
|
182
|
-
const commands = [
|
|
183
|
-
['diff', '--name-only'],
|
|
184
|
-
['diff', '--cached', '--name-only'],
|
|
185
|
-
['ls-files', '--others', '--exclude-standard'],
|
|
186
|
-
];
|
|
187
|
-
for (const gitArgs of commands) {
|
|
188
|
-
const result = run('git', ['-C', worktreePath, ...gitArgs], { timeout: 20_000 });
|
|
189
|
-
for (const filePath of parseGitPathList(result.stdout)) {
|
|
190
|
-
dirty.add(filePath);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
return Array.from(dirty);
|
|
194
|
-
}
|
|
195
180
|
|
|
196
181
|
function collectDoctorForceAddPaths(worktreePath) {
|
|
197
182
|
return REQUIRED_MANAGED_REPO_FILES
|
|
@@ -572,6 +557,16 @@ function finishDoctorSandboxBranch(blocked, metadata, options = {}) {
|
|
|
572
557
|
};
|
|
573
558
|
}
|
|
574
559
|
|
|
560
|
+
function applyStashOrWarn(repoRoot, stashRef) {
|
|
561
|
+
const result = run('git', ['-C', repoRoot, 'stash', 'apply', stashRef], { timeout: 30_000 });
|
|
562
|
+
if (result.status !== 0 || isSpawnFailure(result)) {
|
|
563
|
+
const warning = `stash apply failed for ${stashRef}; user changes may be stranded in the stash`;
|
|
564
|
+
process.stderr.write(`[${TOOL_NAME}] warning: ${warning}\n`);
|
|
565
|
+
return { warning, stashRef };
|
|
566
|
+
}
|
|
567
|
+
return {};
|
|
568
|
+
}
|
|
569
|
+
|
|
575
570
|
function mergeDoctorSandboxRepairsBackToProtectedBase(options, blocked, metadata, autoCommitResult, finishResult) {
|
|
576
571
|
if (options.dryRun) {
|
|
577
572
|
return {
|
|
@@ -610,7 +605,7 @@ function mergeDoctorSandboxRepairsBackToProtectedBase(options, blocked, metadata
|
|
|
610
605
|
'.gitignore',
|
|
611
606
|
'AGENTS.md',
|
|
612
607
|
]);
|
|
613
|
-
const dirtyPaths =
|
|
608
|
+
const dirtyPaths = collectDoctorChangedPaths(blocked.repoRoot);
|
|
614
609
|
let stashRef = '';
|
|
615
610
|
if (dirtyPaths.length > 0) {
|
|
616
611
|
const unexpectedPaths = dirtyPaths.filter((filePath) => {
|
|
@@ -664,14 +659,12 @@ function mergeDoctorSandboxRepairsBackToProtectedBase(options, blocked, metadata
|
|
|
664
659
|
|
|
665
660
|
const restoreResult = ensureRepoBranch(blocked.repoRoot, blocked.branch);
|
|
666
661
|
if (!restoreResult.ok) {
|
|
667
|
-
if (stashRef) {
|
|
668
|
-
run('git', ['-C', blocked.repoRoot, 'stash', 'apply', stashRef], { timeout: 30_000 });
|
|
669
|
-
}
|
|
670
662
|
return {
|
|
671
663
|
status: 'failed',
|
|
672
664
|
note: `could not restore protected branch '${blocked.branch}' before applying sandbox repairs`,
|
|
673
665
|
stdout: restoreResult.stdout || '',
|
|
674
666
|
stderr: restoreResult.stderr || '',
|
|
667
|
+
...(stashRef ? applyStashOrWarn(blocked.repoRoot, stashRef) : {}),
|
|
675
668
|
};
|
|
676
669
|
}
|
|
677
670
|
|
|
@@ -681,25 +674,21 @@ function mergeDoctorSandboxRepairsBackToProtectedBase(options, blocked, metadata
|
|
|
681
674
|
{ timeout: 30_000 },
|
|
682
675
|
);
|
|
683
676
|
if (isSpawnFailure(mergeResult)) {
|
|
684
|
-
if (stashRef) {
|
|
685
|
-
run('git', ['-C', blocked.repoRoot, 'stash', 'apply', stashRef], { timeout: 30_000 });
|
|
686
|
-
}
|
|
687
677
|
return {
|
|
688
678
|
status: 'failed',
|
|
689
679
|
note: 'tracked doctor repair merge errored',
|
|
690
680
|
stdout: mergeResult.stdout || '',
|
|
691
681
|
stderr: mergeResult.stderr || '',
|
|
682
|
+
...(stashRef ? applyStashOrWarn(blocked.repoRoot, stashRef) : {}),
|
|
692
683
|
};
|
|
693
684
|
}
|
|
694
685
|
if (mergeResult.status !== 0) {
|
|
695
|
-
if (stashRef) {
|
|
696
|
-
run('git', ['-C', blocked.repoRoot, 'stash', 'apply', stashRef], { timeout: 30_000 });
|
|
697
|
-
}
|
|
698
686
|
return {
|
|
699
687
|
status: 'failed',
|
|
700
688
|
note: 'tracked doctor repair merge failed',
|
|
701
689
|
stdout: mergeResult.stdout || '',
|
|
702
690
|
stderr: mergeResult.stderr || '',
|
|
691
|
+
...(stashRef ? applyStashOrWarn(blocked.repoRoot, stashRef) : {}),
|
|
703
692
|
};
|
|
704
693
|
}
|
|
705
694
|
|
|
@@ -881,18 +870,17 @@ function runAutoShipGateForBranch({ autoShip, fallbackMode, repoRoot, branch, ba
|
|
|
881
870
|
return { skip: false };
|
|
882
871
|
}
|
|
883
872
|
const gate = deps.runReviewGate || runReviewGate;
|
|
884
|
-
//
|
|
885
|
-
//
|
|
886
|
-
|
|
887
|
-
const reviewProvider = process.env.GUARDEX_AUTO_SHIP_REVIEW_PROVIDER || 'codex';
|
|
873
|
+
// An explicit unattended override pins the provider; otherwise the gate
|
|
874
|
+
// uses automatic selection (Codex with Claude as its launch fallback).
|
|
875
|
+
const reviewProvider = process.env.GUARDEX_AUTO_SHIP_REVIEW_PROVIDER || undefined;
|
|
888
876
|
try {
|
|
889
|
-
gate({
|
|
877
|
+
const gateResult = gate({
|
|
890
878
|
repoRoot,
|
|
891
879
|
branch,
|
|
892
880
|
baseBranch,
|
|
893
881
|
options: { reviewProvider, allowNoChecks: false },
|
|
894
882
|
});
|
|
895
|
-
return { skip: false };
|
|
883
|
+
return { skip: false, gateResult };
|
|
896
884
|
} catch (error) {
|
|
897
885
|
return { skip: true, reason: `merge gate blocked (${error.message})` };
|
|
898
886
|
}
|
|
@@ -949,7 +937,7 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
|
|
|
949
937
|
const ghAvailable =
|
|
950
938
|
originAvailable &&
|
|
951
939
|
(explicitGhBin || originRemoteLooksLikeGithub(repoRoot)) &&
|
|
952
|
-
run(ghBin, ['--version']).status === 0;
|
|
940
|
+
run(ghBin, ['--version'], { timeout: 5000 }).status === 0;
|
|
953
941
|
|
|
954
942
|
let fallbackMode = '';
|
|
955
943
|
if (!originAvailable) {
|
|
@@ -1043,7 +1031,15 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
|
|
|
1043
1031
|
finishArgs.push(waitForMerge ? '--wait-for-merge' : '--no-wait-for-merge');
|
|
1044
1032
|
finishArgs.push('--cleanup');
|
|
1045
1033
|
|
|
1046
|
-
const finishResult = runPackageAsset('branchFinish', finishArgs, {
|
|
1034
|
+
const finishResult = runPackageAsset('branchFinish', finishArgs, {
|
|
1035
|
+
cwd: repoRoot,
|
|
1036
|
+
env: {
|
|
1037
|
+
GUARDEX_FINISH_GATE_DONE: autoShip && fallbackMode === '' ? '1' : '0',
|
|
1038
|
+
GUARDEX_FINISH_REVIEWED_HEAD: gateOutcome.gateResult?.reviewedHeadSha || '',
|
|
1039
|
+
GUARDEX_FINISH_REVIEWED_BASE: gateOutcome.gateResult?.reviewedBaseSha || '',
|
|
1040
|
+
GUARDEX_FINISH_REQUIRE_PREFLIGHT: gateOutcome.gateResult?.requiresLocalPreflight ? '1' : '0',
|
|
1041
|
+
},
|
|
1042
|
+
});
|
|
1047
1043
|
const combinedOutput = [finishResult.stdout || '', finishResult.stderr || ''].join('\n').trim();
|
|
1048
1044
|
|
|
1049
1045
|
if (finishResult.status === 0) {
|
|
@@ -1143,8 +1139,6 @@ function executeDoctorSandboxLifecycle(options, blocked, metadata, integrations)
|
|
|
1143
1139
|
const autoFinishRunner =
|
|
1144
1140
|
resolvedIntegrations.autoFinishReadyAgentBranches || autoFinishReadyAgentBranches;
|
|
1145
1141
|
|
|
1146
|
-
execution.omxScaffoldSync = summarizeDoctorOmxScaffoldSync(blocked.repoRoot, dryRun);
|
|
1147
|
-
|
|
1148
1142
|
// `gx doctor` is the explicit recovery path for an invalid lock registry.
|
|
1149
1143
|
// Publish the repaired sandbox copy before claiming changed files so the
|
|
1150
1144
|
// fail-closed lock tool never has to ignore corrupt sibling state.
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const { createHash } = require('node:crypto');
|
|
4
|
+
const { setTimeout: delay } = require('node:timers/promises');
|
|
5
|
+
|
|
6
|
+
const MAX_READ_BYTES = 256 * 1024;
|
|
7
|
+
const RUN_ID = /^finish-[a-z0-9]+-[0-9]+-[a-f0-9]{8}$/;
|
|
8
|
+
|
|
9
|
+
// Observation only: event files never authorize a merge or replace gate checks.
|
|
10
|
+
function readEventPage(repoRoot, runId, cursor = '', stateOptions) {
|
|
11
|
+
if (!RUN_ID.test(runId)) throw new Error('Invalid finish run ID');
|
|
12
|
+
let directory = fs.realpathSync(repoRoot);
|
|
13
|
+
for (const part of ['.omx', 'state', 'finish-runs']) {
|
|
14
|
+
directory = path.join(directory, part);
|
|
15
|
+
const stat = fs.lstatSync(directory);
|
|
16
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
17
|
+
throw new Error('Unsafe finish event directory');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const file = path.join(directory, `${runId}.jsonl`);
|
|
21
|
+
const entry = fs.lstatSync(file);
|
|
22
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error('Unsafe finish event file');
|
|
23
|
+
const fd = fs.openSync(
|
|
24
|
+
file,
|
|
25
|
+
fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK
|
|
26
|
+
);
|
|
27
|
+
try {
|
|
28
|
+
const stat = fs.fstatSync(fd);
|
|
29
|
+
if (
|
|
30
|
+
!stat.isFile() ||
|
|
31
|
+
stat.dev !== entry.dev ||
|
|
32
|
+
stat.ino !== entry.ino ||
|
|
33
|
+
(stat.mode & 0o077) !== 0 ||
|
|
34
|
+
stat.nlink !== 1 ||
|
|
35
|
+
(process.getuid && stat.uid !== process.getuid())
|
|
36
|
+
) {
|
|
37
|
+
throw new Error('Unsafe finish event file');
|
|
38
|
+
}
|
|
39
|
+
const identity = `${runId}:${stat.dev}:${stat.ino}`;
|
|
40
|
+
let offset = 0;
|
|
41
|
+
if (cursor) {
|
|
42
|
+
const prefix = `${identity}:`;
|
|
43
|
+
const value = cursor.slice(prefix.length);
|
|
44
|
+
if (!cursor.startsWith(prefix) || !/^(0|[1-9][0-9]*)$/.test(value)) {
|
|
45
|
+
throw new Error('Finish cursor belongs to another run or replaced file');
|
|
46
|
+
}
|
|
47
|
+
offset = Number(value);
|
|
48
|
+
if (!Number.isSafeInteger(offset) || offset > stat.size) {
|
|
49
|
+
throw new Error('Finish event file was truncated or cursor is invalid');
|
|
50
|
+
}
|
|
51
|
+
if (offset > 0) {
|
|
52
|
+
const previous = Buffer.alloc(1);
|
|
53
|
+
if (fs.readSync(fd, previous, 0, 1, offset - 1) !== 1 || previous[0] !== 10) {
|
|
54
|
+
throw new Error('Finish cursor is not at an event boundary');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const anchorAt = (position) => {
|
|
59
|
+
const buffer = Buffer.alloc(Math.min(64, position));
|
|
60
|
+
fs.readSync(fd, buffer, 0, buffer.length, position - buffer.length);
|
|
61
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
62
|
+
};
|
|
63
|
+
if (stateOptions?.anchor && stateOptions.anchor !== anchorAt(offset)) {
|
|
64
|
+
throw new Error('Finish event cursor anchor changed; reset the state view');
|
|
65
|
+
}
|
|
66
|
+
const watermark = stateOptions?.watermark ?? stat.size;
|
|
67
|
+
if (!Number.isSafeInteger(watermark) || watermark < offset || watermark > stat.size) {
|
|
68
|
+
throw new Error('Finish snapshot file was truncated or watermark is invalid');
|
|
69
|
+
}
|
|
70
|
+
const bytes = Buffer.alloc(Math.min(MAX_READ_BYTES, watermark - offset));
|
|
71
|
+
const count = fs.readSync(fd, bytes, 0, bytes.length, offset);
|
|
72
|
+
const end = bytes.subarray(0, count).lastIndexOf(10) + 1;
|
|
73
|
+
if (!end && count === MAX_READ_BYTES) throw new Error('Finish event exceeds read limit');
|
|
74
|
+
const events = bytes
|
|
75
|
+
.subarray(0, end)
|
|
76
|
+
.toString('utf8')
|
|
77
|
+
.split('\n')
|
|
78
|
+
.filter(Boolean)
|
|
79
|
+
.map((line) => JSON.parse(line));
|
|
80
|
+
if (events.some((event) => !event || event.runId !== runId || event.schemaVersion !== 1)) {
|
|
81
|
+
throw new Error('Finish event run or schema mismatch');
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
runId,
|
|
85
|
+
cursor: `${identity}:${offset + end}`,
|
|
86
|
+
events,
|
|
87
|
+
...(stateOptions
|
|
88
|
+
? { watermark, pageComplete: offset + count >= watermark, anchor: anchorAt(offset + end) }
|
|
89
|
+
: {})
|
|
90
|
+
};
|
|
91
|
+
} finally {
|
|
92
|
+
fs.closeSync(fd);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Bounded observation cursor: only stage fingerprints, never merge authority.
|
|
97
|
+
// Snapshot pages are patches; consumers merge them by stage until complete.
|
|
98
|
+
function readStatePage(repoRoot, runId, cursor = '') {
|
|
99
|
+
let previous = { hashes: [] };
|
|
100
|
+
if (cursor) {
|
|
101
|
+
try {
|
|
102
|
+
if (!cursor.startsWith('state1.') || cursor.length > 16384) throw new Error();
|
|
103
|
+
previous = JSON.parse(Buffer.from(cursor.slice(7), 'base64url').toString('utf8'));
|
|
104
|
+
if (
|
|
105
|
+
typeof previous.cursor !== 'string' ||
|
|
106
|
+
!previous.cursor ||
|
|
107
|
+
typeof previous.anchor !== 'string' ||
|
|
108
|
+
!/^[a-f0-9]{64}$/.test(previous.anchor) ||
|
|
109
|
+
!Array.isArray(previous.hashes) ||
|
|
110
|
+
previous.hashes.length > 64 ||
|
|
111
|
+
previous.hashes.some(
|
|
112
|
+
(pair) =>
|
|
113
|
+
!Array.isArray(pair) ||
|
|
114
|
+
pair.length !== 2 ||
|
|
115
|
+
typeof pair[0] !== 'string' ||
|
|
116
|
+
pair[0].length > 128 ||
|
|
117
|
+
!/^[a-f0-9]{64}$/.test(pair[1])
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
throw new Error();
|
|
121
|
+
} catch {
|
|
122
|
+
throw new Error('Invalid state cursor; restart without cursor');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const page = readEventPage(repoRoot, runId, previous.cursor || '', {
|
|
126
|
+
anchor: previous.anchor,
|
|
127
|
+
watermark: previous.watermark
|
|
128
|
+
});
|
|
129
|
+
const hashes = new Map(previous.hashes);
|
|
130
|
+
const latest = new Map();
|
|
131
|
+
const alerts = [];
|
|
132
|
+
for (const event of page.events) {
|
|
133
|
+
if (
|
|
134
|
+
!event.stage ||
|
|
135
|
+
event.error ||
|
|
136
|
+
event.warning ||
|
|
137
|
+
/warn|error|fail/i.test(`${event.kind || ''} ${event.state || ''} ${event.level || ''}`) ||
|
|
138
|
+
/\bwarn(?:ing)?\b|⚠/i.test(event.detail || '')
|
|
139
|
+
)
|
|
140
|
+
alerts.push(event);
|
|
141
|
+
if (typeof event.stage !== 'string' || event.stage.length > 128) {
|
|
142
|
+
throw new Error('Invalid finish stage in state view; use raw view');
|
|
143
|
+
}
|
|
144
|
+
latest.set(event.stage, event);
|
|
145
|
+
}
|
|
146
|
+
const stages = [];
|
|
147
|
+
for (const [stage, event] of latest) {
|
|
148
|
+
const normalized = Object.fromEntries(
|
|
149
|
+
Object.entries(event)
|
|
150
|
+
.filter(([key]) => !['timestamp', 'elapsedMs', 'kind'].includes(key))
|
|
151
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
152
|
+
);
|
|
153
|
+
const hash = createHash('sha256').update(JSON.stringify(normalized)).digest('hex');
|
|
154
|
+
if (hashes.get(stage) !== hash) stages.push(event);
|
|
155
|
+
hashes.set(stage, hash);
|
|
156
|
+
}
|
|
157
|
+
if (hashes.size > 64) throw new Error('Too many finish stages; use raw view');
|
|
158
|
+
const next = {
|
|
159
|
+
cursor: page.cursor,
|
|
160
|
+
anchor: page.anchor,
|
|
161
|
+
hashes: [...hashes],
|
|
162
|
+
...(!page.pageComplete ? { watermark: page.watermark } : {})
|
|
163
|
+
};
|
|
164
|
+
const nextCursor = `state1.${Buffer.from(JSON.stringify(next)).toString('base64url')}`;
|
|
165
|
+
if (nextCursor.length > 16384) throw new Error('State cursor exceeds limit; use raw view');
|
|
166
|
+
return {
|
|
167
|
+
runId,
|
|
168
|
+
view: 'state',
|
|
169
|
+
cursor: nextCursor,
|
|
170
|
+
snapshotComplete: page.pageComplete,
|
|
171
|
+
stages,
|
|
172
|
+
alerts
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function waitForEvents(
|
|
177
|
+
repoRoot,
|
|
178
|
+
runId,
|
|
179
|
+
{ cursor = '', waitMs = 0, signal, view = 'raw' } = {}
|
|
180
|
+
) {
|
|
181
|
+
if (!['raw', 'state'].includes(view)) throw new Error('--view must be raw or state');
|
|
182
|
+
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 300000) {
|
|
183
|
+
throw new Error('--wait-ms must be an integer between 0 and 300000');
|
|
184
|
+
}
|
|
185
|
+
const deadline = Date.now() + waitMs;
|
|
186
|
+
let current = cursor;
|
|
187
|
+
while (true) {
|
|
188
|
+
signal?.throwIfAborted();
|
|
189
|
+
const page =
|
|
190
|
+
view === 'state'
|
|
191
|
+
? readStatePage(repoRoot, runId, current)
|
|
192
|
+
: readEventPage(repoRoot, runId, current);
|
|
193
|
+
if (
|
|
194
|
+
view === 'state'
|
|
195
|
+
? page.stages.length || page.alerts.length || !page.snapshotComplete
|
|
196
|
+
: page.events.length
|
|
197
|
+
)
|
|
198
|
+
return { ...page, status: 'events' };
|
|
199
|
+
current = page.cursor;
|
|
200
|
+
const remaining = deadline - Date.now();
|
|
201
|
+
if (remaining <= 0) return { ...page, status: 'timeout' };
|
|
202
|
+
await delay(Math.min(250, remaining), undefined, { signal });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function finishEvents(args) {
|
|
207
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
208
|
+
console.log(
|
|
209
|
+
'gx finish events --run <run-id> [--view raw|state] [--cursor <cursor>] [--wait-ms <0..300000>] [--target <repo>]\nRead new finish events as JSON; repeat with the returned cursor. State pages are stage patches; accumulate until snapshotComplete. Observation only, not merge evidence.'
|
|
210
|
+
);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const options = { target: process.cwd(), run: '', cursor: '', waitMs: 0 };
|
|
214
|
+
const flags = {
|
|
215
|
+
'--target': 'target',
|
|
216
|
+
'--run': 'run',
|
|
217
|
+
'--cursor': 'cursor',
|
|
218
|
+
'--view': 'view',
|
|
219
|
+
'--wait-ms': 'waitMs'
|
|
220
|
+
};
|
|
221
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
222
|
+
const key = Object.hasOwn(flags, args[i]) ? flags[args[i]] : undefined;
|
|
223
|
+
const value = args[i + 1];
|
|
224
|
+
if (!key || !value || value.startsWith('--'))
|
|
225
|
+
throw new Error('Invalid finish events arguments; use --help');
|
|
226
|
+
options[key] = key === 'waitMs' ? Number(value) : value;
|
|
227
|
+
}
|
|
228
|
+
const controller = new AbortController();
|
|
229
|
+
const interrupt = () => {
|
|
230
|
+
process.exitCode = 130;
|
|
231
|
+
controller.abort();
|
|
232
|
+
};
|
|
233
|
+
const terminate = () => {
|
|
234
|
+
process.exitCode = 143;
|
|
235
|
+
controller.abort();
|
|
236
|
+
};
|
|
237
|
+
process.once('SIGINT', interrupt);
|
|
238
|
+
process.once('SIGTERM', terminate);
|
|
239
|
+
try {
|
|
240
|
+
const root = require('../git').resolveRepoRoot(options.target);
|
|
241
|
+
const result = await waitForEvents(root, options.run, {
|
|
242
|
+
...options,
|
|
243
|
+
signal: controller.signal
|
|
244
|
+
});
|
|
245
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (!controller.signal.aborted) throw error;
|
|
248
|
+
} finally {
|
|
249
|
+
process.removeListener('SIGINT', interrupt);
|
|
250
|
+
process.removeListener('SIGTERM', terminate);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
module.exports = { readEventPage, readStatePage, waitForEvents, finishEvents };
|