@fitlab-ai/agent-infra 0.9.5 → 0.9.7
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/dist/bin/internal-cli.js +8 -3
- package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +171 -20
- package/dist/lib/agent-clients/adapters/codex-lifecycle/build-identity.js +162 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +244 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +14 -2
- package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +370 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +68 -8
- package/dist/lib/agent-clients/adapters/codex.js +1 -1
- package/dist/lib/defaults.json +10 -2
- package/dist/lib/git/workflow.js +30 -4
- package/dist/lib/internal/codex-lifecycle.js +169 -3
- package/dist/lib/internal/codex-sandbox-controller.js +106 -0
- package/dist/lib/internal/release-workflow.js +108 -11
- package/dist/lib/internal/sandbox-control.js +43 -6
- package/dist/lib/internal/task-create.js +12 -4
- package/dist/lib/internal/task-orchestration.js +40 -7
- package/dist/lib/platform/context.js +6 -4
- package/dist/lib/platform/github-client.js +55 -2
- package/dist/lib/platform/issue-comments.js +2 -1
- package/dist/lib/process-data/checkpoint.js +319 -0
- package/dist/lib/process-data/index.js +128 -60
- package/dist/lib/process-data/materialize.js +84 -0
- package/dist/lib/process-data/normalize.js +34 -1
- package/dist/lib/process-data/reconcile.js +55 -1
- package/dist/lib/process-data/sources.js +422 -1
- package/dist/lib/process-data/store.js +341 -11
- package/dist/lib/release/workflow.js +29 -21
- package/dist/lib/sandbox/commands/create.js +111 -60
- package/dist/lib/sandbox/commands/prune.js +40 -16
- package/dist/lib/sandbox/commands/rm.js +372 -94
- package/dist/lib/sandbox/commands/start.js +4 -3
- package/dist/lib/sandbox/control/client.js +138 -22
- package/dist/lib/sandbox/control/container-identity.js +64 -0
- package/dist/lib/sandbox/control/executor.js +142 -0
- package/dist/lib/sandbox/control/lifecycle.js +557 -0
- package/dist/lib/sandbox/control/protocol.js +69 -26
- package/dist/lib/sandbox/control/server.js +395 -99
- package/dist/lib/sandbox/control/state.js +191 -0
- package/dist/lib/sandbox/control/timing.js +8 -0
- package/dist/lib/sandbox/index.js +2 -2
- package/dist/lib/sandbox/managed-fs.js +14 -2
- package/dist/lib/sandbox/mounts.js +22 -19
- package/dist/lib/sandbox/recovery.js +284 -50
- package/dist/lib/sandbox/workspace-view.js +90 -10
- package/dist/lib/sandbox/worktree-safety.js +196 -0
- package/dist/lib/server/daemon.js +1 -1
- package/dist/lib/server/process-control.js +17 -1
- package/dist/lib/server/process-state.js +57 -20
- package/dist/lib/task/artifact-lifecycle.js +87 -15
- package/dist/lib/task/artifact-receipts.js +128 -0
- package/dist/lib/task/codex-orchestration.js +236 -0
- package/dist/lib/task/commands/status.js +3 -0
- package/dist/lib/task/commands/validate.js +289 -0
- package/dist/lib/task/commit-finalization.js +36 -9
- package/dist/lib/task/create.js +10 -2
- package/dist/lib/task/delegation-receipts.js +109 -2
- package/dist/lib/task/events.js +149 -6
- package/dist/lib/task/finalization-artifacts.js +2 -1
- package/dist/lib/task/implementation-inputs.js +1 -7
- package/dist/lib/task/index.js +9 -0
- package/dist/lib/task/ledger.js +13 -1
- package/dist/lib/task/orchestration.js +365 -15
- package/dist/lib/task/sections.js +5 -1
- package/dist/lib/task/task-execution-lock.js +5 -4
- package/dist/lib/task/verification-engine.js +78 -14
- package/dist/lib/task/verification.js +1 -0
- package/dist/lifecycle-build-manifest.json +6 -0
- package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +202 -18
- package/lib/agent-clients/adapters/codex-lifecycle/build-identity.ts +227 -0
- package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +321 -0
- package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +19 -3
- package/lib/agent-clients/adapters/codex-lifecycle/manifest-files.json +26 -0
- package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +453 -0
- package/lib/agent-clients/adapters/codex-lifecycle/store.ts +83 -6
- package/lib/agent-clients/adapters/codex.ts +1 -1
- package/lib/defaults.json +10 -2
- package/lib/git/workflow.ts +25 -3
- package/lib/internal/codex-lifecycle.ts +175 -4
- package/lib/internal/codex-sandbox-controller.ts +109 -0
- package/lib/internal/release-workflow.ts +107 -11
- package/lib/internal/sandbox-control.ts +38 -6
- package/lib/internal/task-create.ts +16 -4
- package/lib/internal/task-orchestration.ts +34 -7
- package/lib/platform/context.ts +8 -5
- package/lib/platform/github-client.ts +61 -3
- package/lib/platform/issue-comments.ts +2 -1
- package/lib/process-data/checkpoint.ts +335 -0
- package/lib/process-data/index.ts +112 -60
- package/lib/process-data/materialize.ts +83 -0
- package/lib/process-data/normalize.ts +29 -1
- package/lib/process-data/reconcile.ts +64 -2
- package/lib/process-data/sources.ts +449 -2
- package/lib/process-data/store.ts +304 -11
- package/lib/process-data/types.ts +124 -2
- package/lib/release/workflow.ts +69 -20
- package/lib/sandbox/commands/create.ts +70 -25
- package/lib/sandbox/commands/prune.ts +53 -15
- package/lib/sandbox/commands/rm.ts +423 -108
- package/lib/sandbox/commands/start.ts +4 -3
- package/lib/sandbox/control/client.ts +152 -28
- package/lib/sandbox/control/container-identity.ts +93 -0
- package/lib/sandbox/control/executor.ts +167 -0
- package/lib/sandbox/control/lifecycle.ts +573 -0
- package/lib/sandbox/control/protocol.ts +121 -68
- package/lib/sandbox/control/server.ts +398 -109
- package/lib/sandbox/control/state.ts +213 -0
- package/lib/sandbox/control/timing.ts +12 -0
- package/lib/sandbox/index.ts +2 -2
- package/lib/sandbox/managed-fs.ts +17 -2
- package/lib/sandbox/mounts.ts +16 -8
- package/lib/sandbox/recovery.ts +335 -65
- package/lib/sandbox/workspace-view.ts +102 -11
- package/lib/sandbox/worktree-safety.ts +234 -0
- package/lib/server/daemon.ts +1 -1
- package/lib/server/process-control.ts +24 -3
- package/lib/server/process-state.ts +82 -27
- package/lib/task/artifact-lifecycle.ts +78 -14
- package/lib/task/artifact-receipts.ts +161 -0
- package/lib/task/codex-orchestration.ts +319 -0
- package/lib/task/commands/status.ts +2 -0
- package/lib/task/commands/validate.ts +282 -0
- package/lib/task/commit-finalization.ts +52 -9
- package/lib/task/create.ts +11 -2
- package/lib/task/delegation-receipts.ts +208 -7
- package/lib/task/events.ts +131 -5
- package/lib/task/finalization-artifacts.ts +2 -1
- package/lib/task/implementation-inputs.ts +1 -5
- package/lib/task/index.ts +8 -0
- package/lib/task/ledger.ts +16 -1
- package/lib/task/orchestration.ts +552 -18
- package/lib/task/sections.ts +6 -2
- package/lib/task/task-execution-lock.ts +11 -9
- package/lib/task/verification-engine.ts +93 -24
- package/lib/task/verification.ts +2 -1
- package/package.json +1 -1
- package/templates/.agents/README.en.md +7 -0
- package/templates/.agents/README.zh-CN.md +5 -0
- package/templates/.agents/hooks/lifecycle-delegation.js +72 -12
- package/templates/.agents/rules/lifecycle-orchestration.en.md +8 -2
- package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +8 -2
- package/templates/.agents/rules/no-mid-flow-questions.en.md +1 -0
- package/templates/.agents/rules/no-mid-flow-questions.zh-CN.md +1 -0
- package/templates/.agents/rules/pr-checks-commands.github.en.md +1 -1
- package/templates/.agents/rules/pr-checks-commands.github.zh-CN.md +1 -1
- package/templates/.agents/rules/review-handshake.en.md +3 -1
- package/templates/.agents/rules/review-handshake.zh-CN.md +3 -1
- package/templates/.agents/skills/code-task/reference/dual-mode.en.md +3 -1
- package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +3 -1
- package/templates/.agents/skills/complete-task/SKILL.en.md +4 -0
- package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +4 -0
- package/templates/.agents/skills/post-release/SKILL.en.md +32 -6
- package/templates/.agents/skills/post-release/SKILL.zh-CN.md +32 -6
- package/templates/.agents/skills/run-manual-validation/SKILL.en.md +42 -0
- package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +42 -0
- package/templates/.agents/skills/run-manual-validation/config/verify.en.json +25 -0
- package/templates/.agents/skills/run-manual-validation/config/verify.zh-CN.json +25 -0
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +67 -0
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +67 -0
- package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +69 -0
- package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +69 -0
- package/templates/.agents/skills/run-task/SKILL.en.md +9 -7
- package/templates/.agents/skills/run-task/SKILL.zh-CN.md +9 -7
- package/templates/.agents/skills/run-task/reference/host-validation.en.md +5 -3
- package/templates/.agents/skills/run-task/reference/host-validation.zh-CN.md +5 -3
- package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +75 -3
- package/templates/.claude/commands/run-manual-validation.en.md +9 -0
- package/templates/.claude/commands/run-manual-validation.zh-CN.md +9 -0
- package/templates/.codex/hooks.json +8 -8
- package/templates/.opencode/commands/run-manual-validation.en.md +11 -0
- package/templates/.opencode/commands/run-manual-validation.zh-CN.md +11 -0
- package/templates/.agents/workspace/README.en.md +0 -26
- package/templates/.agents/workspace/README.zh-CN.md +0 -26
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { verifySnapshot } from './store.js';
|
|
6
|
+
function repositoryKey(repository) {
|
|
7
|
+
return crypto.createHash('sha256').update(repository).digest('hex').slice(0, 32);
|
|
8
|
+
}
|
|
9
|
+
function checkpointPaths(root, repository) {
|
|
10
|
+
const directory = path.join(root, 'checkpoints', 'github');
|
|
11
|
+
const base = path.join(directory, repositoryKey(repository));
|
|
12
|
+
return { directory, checkpoint: `${base}.json`, lock: `${base}.lock` };
|
|
13
|
+
}
|
|
14
|
+
function processStartToken(pid) {
|
|
15
|
+
if (process.platform === 'linux') {
|
|
16
|
+
try {
|
|
17
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
18
|
+
const closing = stat.lastIndexOf(')');
|
|
19
|
+
const fields = stat.slice(closing + 2).split(' ');
|
|
20
|
+
return fields[19] ?? null;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return pid === process.pid ? `self:${process.pid}` : null;
|
|
27
|
+
}
|
|
28
|
+
function fsyncDirectory(directory) {
|
|
29
|
+
if (process.platform === 'win32')
|
|
30
|
+
return;
|
|
31
|
+
const fd = fs.openSync(directory, 'r');
|
|
32
|
+
try {
|
|
33
|
+
fs.fsyncSync(fd);
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
fs.closeSync(fd);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function ensurePrivateDirectory(directory) {
|
|
40
|
+
const missing = [];
|
|
41
|
+
let current = path.resolve(directory);
|
|
42
|
+
while (!fs.existsSync(current)) {
|
|
43
|
+
missing.push(current);
|
|
44
|
+
const parent = path.dirname(current);
|
|
45
|
+
if (parent === current)
|
|
46
|
+
throw new Error(`cannot create directory tree: ${directory}`);
|
|
47
|
+
current = parent;
|
|
48
|
+
}
|
|
49
|
+
for (const target of missing.reverse()) {
|
|
50
|
+
fs.mkdirSync(target, { mode: 0o700 });
|
|
51
|
+
if (process.platform !== 'win32')
|
|
52
|
+
fs.chmodSync(target, 0o700);
|
|
53
|
+
fsyncDirectory(path.dirname(target));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function writeTemporary(filePath, value) {
|
|
57
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
58
|
+
const temporary = `${filePath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
59
|
+
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
60
|
+
try {
|
|
61
|
+
fs.writeFileSync(fd, `${JSON.stringify(value)}\n`);
|
|
62
|
+
fs.fsyncSync(fd);
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
fs.closeSync(fd);
|
|
66
|
+
}
|
|
67
|
+
return temporary;
|
|
68
|
+
}
|
|
69
|
+
function validCheckpoint(value, repository) {
|
|
70
|
+
if (!value || typeof value !== 'object')
|
|
71
|
+
return false;
|
|
72
|
+
const checkpoint = value;
|
|
73
|
+
return checkpoint.schema === 'github-checkpoint/v1'
|
|
74
|
+
&& checkpoint.repository === repository
|
|
75
|
+
&& Boolean(checkpoint.snapshotId)
|
|
76
|
+
&& Boolean(checkpoint.watermark)
|
|
77
|
+
&& Boolean(checkpoint.committedAt)
|
|
78
|
+
&& /^[a-f0-9]{64}$/.test(checkpoint.manifestSha256);
|
|
79
|
+
}
|
|
80
|
+
function checkpointMatchesSnapshot(root, value) {
|
|
81
|
+
const verified = verifySnapshot(root, value.snapshotId);
|
|
82
|
+
return verified.ok
|
|
83
|
+
&& verified.manifest?.schema === 'raw-manifest/v2'
|
|
84
|
+
&& verified.manifest.snapshotId === value.snapshotId
|
|
85
|
+
&& verified.manifest.repository === value.repository
|
|
86
|
+
&& verified.manifest.manifestSha256 === value.manifestSha256
|
|
87
|
+
&& verified.manifest.watermark === value.watermark;
|
|
88
|
+
}
|
|
89
|
+
function checkpointState(value) {
|
|
90
|
+
return { snapshotId: value?.snapshotId ?? null, manifestSha256: value?.manifestSha256 ?? null };
|
|
91
|
+
}
|
|
92
|
+
function readGitHubCheckpoint(root, repository) {
|
|
93
|
+
const target = checkpointPaths(root, repository).checkpoint;
|
|
94
|
+
if (!fs.existsSync(target))
|
|
95
|
+
return { ok: true, value: null };
|
|
96
|
+
try {
|
|
97
|
+
const parsed = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
98
|
+
const value = {
|
|
99
|
+
schema: parsed.schema,
|
|
100
|
+
repository: parsed.repository,
|
|
101
|
+
snapshotId: parsed.snapshotId,
|
|
102
|
+
watermark: parsed.watermark,
|
|
103
|
+
manifestSha256: parsed.manifestSha256,
|
|
104
|
+
committedAt: parsed.committedAt
|
|
105
|
+
};
|
|
106
|
+
if (!validCheckpoint(value, repository)) {
|
|
107
|
+
return { ok: false, error: { code: 'CHECKPOINT_INVALID', message: 'GitHub checkpoint schema or identity is invalid' } };
|
|
108
|
+
}
|
|
109
|
+
return { ok: true, value };
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return { ok: false, error: { code: 'CHECKPOINT_INVALID', message: 'GitHub checkpoint is not valid JSON' } };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function quarantine(lockPath) {
|
|
116
|
+
const target = `${lockPath}.orphaned-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
|
|
117
|
+
fs.renameSync(lockPath, target);
|
|
118
|
+
return target;
|
|
119
|
+
}
|
|
120
|
+
function acquireGitHubCheckpoint(root, repository) {
|
|
121
|
+
const paths = checkpointPaths(root, repository);
|
|
122
|
+
ensurePrivateDirectory(paths.directory);
|
|
123
|
+
const recovery = { recovered: false, quarantined: [] };
|
|
124
|
+
const owner = {
|
|
125
|
+
schema: 'checkpoint-owner/v1',
|
|
126
|
+
ownerId: crypto.randomUUID(),
|
|
127
|
+
pid: process.pid,
|
|
128
|
+
host: os.hostname(),
|
|
129
|
+
processStartToken: processStartToken(process.pid) ?? '',
|
|
130
|
+
createdAt: new Date().toISOString()
|
|
131
|
+
};
|
|
132
|
+
if (!owner.processStartToken) {
|
|
133
|
+
return { ok: false, error: { code: 'CHECKPOINT_TOPOLOGY_UNSUPPORTED', message: 'Process liveness cannot be verified on this host' } };
|
|
134
|
+
}
|
|
135
|
+
let recoveredOwnerId = null;
|
|
136
|
+
if (fs.existsSync(paths.lock)) {
|
|
137
|
+
let previous;
|
|
138
|
+
try {
|
|
139
|
+
previous = JSON.parse(fs.readFileSync(paths.lock, 'utf8'));
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint lock is unreadable' } };
|
|
143
|
+
}
|
|
144
|
+
if (previous.host !== owner.host || !previous.ownerId || !previous.processStartToken) {
|
|
145
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint lock owner topology is unknown' } };
|
|
146
|
+
}
|
|
147
|
+
const currentToken = processStartToken(previous.pid);
|
|
148
|
+
if (currentToken && currentToken === previous.processStartToken) {
|
|
149
|
+
return { ok: false, error: { code: 'CHECKPOINT_BUSY', message: 'Checkpoint is held by a live process' } };
|
|
150
|
+
}
|
|
151
|
+
if (process.platform !== 'linux') {
|
|
152
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint owner liveness cannot be proven on this host' } };
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
recoveredOwnerId = previous.ownerId;
|
|
156
|
+
recovery.quarantined.push(quarantine(paths.lock));
|
|
157
|
+
recovery.recovered = true;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Unable to quarantine an orphaned checkpoint lock' } };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const fd = fs.openSync(paths.lock, 'wx', 0o600);
|
|
165
|
+
try {
|
|
166
|
+
fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`);
|
|
167
|
+
fs.fsyncSync(fd);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
fs.closeSync(fd);
|
|
171
|
+
}
|
|
172
|
+
fsyncDirectory(paths.directory);
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
if (error.code === 'EEXIST') {
|
|
176
|
+
return { ok: false, error: { code: 'CHECKPOINT_BUSY', message: 'Checkpoint lock was acquired by another process' } };
|
|
177
|
+
}
|
|
178
|
+
return { ok: false, error: { code: 'CHECKPOINT_LOCK_FAILED', message: String(error) } };
|
|
179
|
+
}
|
|
180
|
+
const releaseOwnedLock = () => {
|
|
181
|
+
try {
|
|
182
|
+
fs.unlinkSync(paths.lock);
|
|
183
|
+
fsyncDirectory(paths.directory);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// Preserve the original recovery error; a remaining lock will fail closed next time.
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const beforeResult = readGitHubCheckpoint(root, repository);
|
|
190
|
+
if (!beforeResult.ok) {
|
|
191
|
+
releaseOwnedLock();
|
|
192
|
+
return beforeResult;
|
|
193
|
+
}
|
|
194
|
+
let checkpointBefore = beforeResult.value;
|
|
195
|
+
const temporaryCandidates = fs.readdirSync(paths.directory)
|
|
196
|
+
.filter((entry) => entry.startsWith(path.basename(paths.checkpoint) + '.') && entry.endsWith('.tmp'))
|
|
197
|
+
.map((entry) => path.join(paths.directory, entry));
|
|
198
|
+
if (temporaryCandidates.length > 1) {
|
|
199
|
+
releaseOwnedLock();
|
|
200
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Multiple checkpoint recovery candidates exist' } };
|
|
201
|
+
}
|
|
202
|
+
if (temporaryCandidates.length === 1) {
|
|
203
|
+
const candidate = temporaryCandidates[0];
|
|
204
|
+
try {
|
|
205
|
+
const parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
|
206
|
+
const isCandidate = parsed && typeof parsed === 'object' && 'candidateSchema' in parsed
|
|
207
|
+
&& parsed.candidateSchema === 'github-checkpoint-candidate/v1';
|
|
208
|
+
if (isCandidate) {
|
|
209
|
+
const candidateValue = parsed;
|
|
210
|
+
const value = candidateValue;
|
|
211
|
+
const expected = checkpointState(checkpointBefore);
|
|
212
|
+
const candidateExpected = candidateValue.expectedOld;
|
|
213
|
+
if (!recoveredOwnerId || candidateValue.ownerId !== recoveredOwnerId) {
|
|
214
|
+
recovery.quarantined.push(quarantine(candidate));
|
|
215
|
+
releaseOwnedLock();
|
|
216
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint candidate owner proof does not match the recovered lock owner' } };
|
|
217
|
+
}
|
|
218
|
+
if (!validCheckpoint(value, repository)
|
|
219
|
+
|| candidateExpected?.snapshotId !== expected.snapshotId
|
|
220
|
+
|| candidateExpected?.manifestSha256 !== expected.manifestSha256) {
|
|
221
|
+
releaseOwnedLock();
|
|
222
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint candidate does not match the current head' } };
|
|
223
|
+
}
|
|
224
|
+
if (!checkpointMatchesSnapshot(root, value)) {
|
|
225
|
+
recovery.quarantined.push(quarantine(candidate));
|
|
226
|
+
releaseOwnedLock();
|
|
227
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint candidate snapshot failed full verification' } };
|
|
228
|
+
}
|
|
229
|
+
if (process.platform === 'win32' && checkpointBefore) {
|
|
230
|
+
releaseOwnedLock();
|
|
231
|
+
return { ok: false, error: { code: 'CHECKPOINT_TOPOLOGY_UNSUPPORTED', message: 'Checkpoint replacement durability cannot be proven on this host' } };
|
|
232
|
+
}
|
|
233
|
+
fs.renameSync(candidate, paths.checkpoint);
|
|
234
|
+
recovery.recovered = true;
|
|
235
|
+
fsyncDirectory(paths.directory);
|
|
236
|
+
const recovered = readGitHubCheckpoint(root, repository);
|
|
237
|
+
if (!recovered.ok) {
|
|
238
|
+
releaseOwnedLock();
|
|
239
|
+
return recovered;
|
|
240
|
+
}
|
|
241
|
+
checkpointBefore = recovered.value;
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
recovery.quarantined.push(quarantine(candidate));
|
|
245
|
+
releaseOwnedLock();
|
|
246
|
+
return { ok: false, error: { code: 'CHECKPOINT_RECOVERY_REQUIRED', message: 'Checkpoint candidate lacks owner proof' } };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
recovery.quarantined.push(quarantine(candidate));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return { ok: true, value: { paths, repository, owner, recovery, expectedOld: checkpointBefore } };
|
|
254
|
+
}
|
|
255
|
+
function commitGitHubCheckpoint(lease, value) {
|
|
256
|
+
try {
|
|
257
|
+
const current = JSON.parse(fs.readFileSync(lease.paths.lock, 'utf8'));
|
|
258
|
+
if (current.ownerId !== lease.owner.ownerId) {
|
|
259
|
+
return { ok: false, error: { code: 'CHECKPOINT_OWNER_MISMATCH', message: 'Checkpoint lock ownership changed' } };
|
|
260
|
+
}
|
|
261
|
+
if (value.repository !== lease.repository || !validCheckpoint(value, lease.repository)) {
|
|
262
|
+
return { ok: false, error: { code: 'CHECKPOINT_INVALID', message: 'Checkpoint value is invalid' } };
|
|
263
|
+
}
|
|
264
|
+
const root = path.dirname(path.dirname(lease.paths.directory));
|
|
265
|
+
if (!checkpointMatchesSnapshot(root, value)) {
|
|
266
|
+
return { ok: false, error: { code: 'CHECKPOINT_INVALID', message: 'Checkpoint snapshot does not match a verified v2 manifest' } };
|
|
267
|
+
}
|
|
268
|
+
const currentCheckpoint = readGitHubCheckpoint(root, lease.repository);
|
|
269
|
+
if (!currentCheckpoint.ok)
|
|
270
|
+
return currentCheckpoint;
|
|
271
|
+
if (checkpointState(currentCheckpoint.value).snapshotId !== checkpointState(lease.expectedOld).snapshotId
|
|
272
|
+
|| checkpointState(currentCheckpoint.value).manifestSha256 !== checkpointState(lease.expectedOld).manifestSha256) {
|
|
273
|
+
return { ok: false, error: { code: 'CHECKPOINT_CONFLICT', message: 'Checkpoint head changed before commit' } };
|
|
274
|
+
}
|
|
275
|
+
const candidate = {
|
|
276
|
+
...value,
|
|
277
|
+
candidateSchema: 'github-checkpoint-candidate/v1',
|
|
278
|
+
ownerId: lease.owner.ownerId,
|
|
279
|
+
expectedOld: checkpointState(lease.expectedOld)
|
|
280
|
+
};
|
|
281
|
+
const temporary = writeTemporary(lease.paths.checkpoint, candidate);
|
|
282
|
+
const rechecked = readGitHubCheckpoint(root, lease.repository);
|
|
283
|
+
if (!rechecked.ok) {
|
|
284
|
+
fs.unlinkSync(temporary);
|
|
285
|
+
return rechecked;
|
|
286
|
+
}
|
|
287
|
+
if (checkpointState(rechecked.value).snapshotId !== checkpointState(lease.expectedOld).snapshotId
|
|
288
|
+
|| checkpointState(rechecked.value).manifestSha256 !== checkpointState(lease.expectedOld).manifestSha256) {
|
|
289
|
+
fs.unlinkSync(temporary);
|
|
290
|
+
return { ok: false, error: { code: 'CHECKPOINT_CONFLICT', message: 'Checkpoint head changed during commit' } };
|
|
291
|
+
}
|
|
292
|
+
if (process.platform === 'win32' && fs.existsSync(lease.paths.checkpoint)) {
|
|
293
|
+
fs.unlinkSync(temporary);
|
|
294
|
+
return { ok: false, error: { code: 'CHECKPOINT_TOPOLOGY_UNSUPPORTED', message: 'Checkpoint replacement durability cannot be proven on this host' } };
|
|
295
|
+
}
|
|
296
|
+
fs.renameSync(temporary, lease.paths.checkpoint);
|
|
297
|
+
if (process.platform !== 'win32')
|
|
298
|
+
fs.chmodSync(lease.paths.checkpoint, 0o600);
|
|
299
|
+
fsyncDirectory(lease.paths.directory);
|
|
300
|
+
return { ok: true, value: undefined };
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
return { ok: false, error: { code: 'CHECKPOINT_COMMIT_FAILED', message: String(error) } };
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function releaseGitHubCheckpoint(lease) {
|
|
307
|
+
try {
|
|
308
|
+
const current = JSON.parse(fs.readFileSync(lease.paths.lock, 'utf8'));
|
|
309
|
+
if (current.ownerId === lease.owner.ownerId) {
|
|
310
|
+
fs.unlinkSync(lease.paths.lock);
|
|
311
|
+
fsyncDirectory(lease.paths.directory);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
// The next invocation will fail closed and report recovery if the lock remains.
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
export { acquireGitHubCheckpoint, checkpointPaths, commitGitHubCheckpoint, processStartToken, readGitHubCheckpoint, releaseGitHubCheckpoint };
|
|
319
|
+
//# sourceMappingURL=checkpoint.js.map
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { execFileSync } from 'node:child_process';
|
|
4
3
|
import { detectRepoRoot } from '../task/resolve-ref.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
4
|
+
import { acquireGitHubCheckpoint, commitGitHubCheckpoint, readGitHubCheckpoint, releaseGitHubCheckpoint } from './checkpoint.js';
|
|
5
|
+
import { materializeJson, materializeSnapshot } from './materialize.js';
|
|
6
|
+
import { normalizeResources } from './normalize.js';
|
|
7
|
+
import { reconcileRecords, reconcileResourceRecords } from './reconcile.js';
|
|
7
8
|
import { readAppliedOverlays, repairSnapshot } from './repair.js';
|
|
8
|
-
import {
|
|
9
|
-
import { canonicalJsonBytes, createObjectStore,
|
|
9
|
+
import { collectGitHubBoundary, resolveGitHubRepository } from './sources.js';
|
|
10
|
+
import { canonicalJsonBytes, createObjectStore, findSnapshot, publishSnapshotV2, verifySnapshot } from './store.js';
|
|
11
|
+
import { createGitHubClient } from '../platform/github-client.js';
|
|
10
12
|
const USAGE = `Usage: ai data <command> [options]
|
|
11
13
|
|
|
12
14
|
Commands:
|
|
13
|
-
capture [--source
|
|
15
|
+
capture [--source github] [--root <dir>] [--full-reconcile]
|
|
14
16
|
verify <snapshot-id> [--root <dir>]
|
|
15
17
|
audit <snapshot-id> [--root <dir>] [--format json|text]
|
|
16
18
|
repair <snapshot-id> [--root <dir>] [--apply]
|
|
17
|
-
export <snapshot-id> [--root <dir>] [--repairs none|applied] [--output <file|->]
|
|
19
|
+
export <snapshot-id> [--root <dir>] [--repairs none|applied] [--as-of <ISO>] [--output <file|->]
|
|
18
20
|
`;
|
|
19
21
|
function parseArgs(args, valueOptions, booleanOptions) {
|
|
20
22
|
const positionals = [];
|
|
@@ -61,14 +63,6 @@ function dataRoot(repoRoot, requested) {
|
|
|
61
63
|
}
|
|
62
64
|
return resolved;
|
|
63
65
|
}
|
|
64
|
-
function repositoryIdentity(repoRoot) {
|
|
65
|
-
try {
|
|
66
|
-
return execFileSync('git', ['config', '--get', 'remote.origin.url'], { cwd: repoRoot, encoding: 'utf8' }).trim() || path.basename(repoRoot);
|
|
67
|
-
}
|
|
68
|
-
catch {
|
|
69
|
-
return path.basename(repoRoot);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
66
|
function writeJson(value) {
|
|
73
67
|
process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
74
68
|
}
|
|
@@ -77,61 +71,127 @@ function optionString(parsed, name) {
|
|
|
77
71
|
return typeof value === 'string' ? value : undefined;
|
|
78
72
|
}
|
|
79
73
|
function capture(args) {
|
|
80
|
-
const parsed = parseArgs(args, new Set(['--source', '--root']), new Set(['--include-excerpts']));
|
|
74
|
+
const parsed = parseArgs(args, new Set(['--source', '--root']), new Set(['--full-reconcile', '--include-excerpts']));
|
|
81
75
|
if (parsed.positionals.length > 0)
|
|
82
76
|
throw new Error('capture does not accept positional arguments');
|
|
83
|
-
const scope = optionString(parsed, '--source') ?? '
|
|
84
|
-
if (
|
|
85
|
-
throw new Error('--source
|
|
77
|
+
const scope = optionString(parsed, '--source') ?? 'github';
|
|
78
|
+
if (scope !== 'github')
|
|
79
|
+
throw new Error('new process-data capture only supports --source github; local data is already normalized and --source all is retired');
|
|
80
|
+
if (parsed.options.has('--include-excerpts'))
|
|
81
|
+
throw new Error('--include-excerpts is not supported for GitHub-only capture');
|
|
86
82
|
const repoRoot = detectRepoRoot();
|
|
87
83
|
const root = dataRoot(repoRoot, optionString(parsed, '--root'));
|
|
88
|
-
const
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
84
|
+
const client = createGitHubClient();
|
|
85
|
+
const repositoryResult = resolveGitHubRepository(repoRoot, client);
|
|
86
|
+
if (!repositoryResult.ok) {
|
|
87
|
+
writeJson({ ok: false, error: repositoryResult.error });
|
|
88
|
+
return 2;
|
|
89
|
+
}
|
|
90
|
+
const repository = repositoryResult.value;
|
|
91
|
+
const leaseResult = acquireGitHubCheckpoint(root, repository);
|
|
92
|
+
if (!leaseResult.ok) {
|
|
93
|
+
writeJson({ ok: false, error: leaseResult.error });
|
|
94
|
+
return 2;
|
|
95
|
+
}
|
|
96
|
+
const lease = leaseResult.value;
|
|
97
|
+
try {
|
|
98
|
+
const checkpointResult = readGitHubCheckpoint(root, repository);
|
|
99
|
+
if (!checkpointResult.ok) {
|
|
100
|
+
writeJson({ ok: false, error: checkpointResult.error });
|
|
96
101
|
return 2;
|
|
97
102
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const github =
|
|
103
|
+
const checkpoint = checkpointResult.value;
|
|
104
|
+
const full = parsed.options.has('--full-reconcile');
|
|
105
|
+
const observedFrom = new Date().toISOString();
|
|
106
|
+
const github = collectGitHubBoundary(repoRoot, {
|
|
107
|
+
client,
|
|
108
|
+
fromInclusive: full ? null : checkpoint?.watermark ?? null,
|
|
109
|
+
reconciliation: full ? 'full' : 'incremental'
|
|
110
|
+
});
|
|
102
111
|
if (!github.ok) {
|
|
103
112
|
writeJson({ ok: false, error: github.error });
|
|
104
113
|
return 2;
|
|
105
114
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
115
|
+
const store = createObjectStore(root);
|
|
116
|
+
for (const object of github.value.objects) {
|
|
117
|
+
if (object.content !== undefined && object.disposition?.state === 'included') {
|
|
118
|
+
const stored = store.put(Buffer.from(object.content, 'utf8'));
|
|
119
|
+
if (stored.sha256 !== object.sha256)
|
|
120
|
+
throw new Error(`source hash mismatch: ${object.sourceIdentity}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
let parent = [];
|
|
124
|
+
if (checkpoint) {
|
|
125
|
+
const parentPath = findSnapshot(root, checkpoint.snapshotId);
|
|
126
|
+
if (!parentPath)
|
|
127
|
+
throw new Error(`checkpoint head snapshot is missing: ${checkpoint.snapshotId}`);
|
|
128
|
+
const materialized = materializeSnapshot(root, checkpoint.snapshotId);
|
|
129
|
+
if (!materialized.manifest || materialized.manifest.manifestSha256 !== checkpoint.manifestSha256 || materialized.manifest.watermark !== checkpoint.watermark) {
|
|
130
|
+
throw new Error('checkpoint does not match its verified snapshot head');
|
|
131
|
+
}
|
|
132
|
+
parent = materialized.records;
|
|
116
133
|
}
|
|
134
|
+
const current = normalizeResources(github.value.objects);
|
|
135
|
+
const reconciliation = reconcileResourceRecords(current, {
|
|
136
|
+
parent,
|
|
137
|
+
full,
|
|
138
|
+
deferred: github.value.deferred,
|
|
139
|
+
unavailable: github.value.unavailable
|
|
140
|
+
});
|
|
141
|
+
const quality = reconcileRecords(reconciliation.records, 'github');
|
|
142
|
+
const fromInclusive = checkpoint?.watermark ?? null;
|
|
143
|
+
const hasStrictSinceEndpoint = github.value.endpoints.some((endpoint) => endpoint.queryMode === 'strict-since');
|
|
144
|
+
const queryAfter = !full && fromInclusive && hasStrictSinceEndpoint
|
|
145
|
+
? new Date(new Date(fromInclusive).getTime() - 1000).toISOString()
|
|
146
|
+
: null;
|
|
147
|
+
const responseDates = github.value.responseDates;
|
|
148
|
+
const published = publishSnapshotV2(root, {
|
|
149
|
+
scope: 'github',
|
|
150
|
+
repository,
|
|
151
|
+
observedFrom,
|
|
152
|
+
observedTo: github.value.watermark,
|
|
153
|
+
objects: github.value.objects.map(({ content: _content, ...object }) => object),
|
|
154
|
+
endpoints: github.value.endpoints,
|
|
155
|
+
excerptsEnabled: false,
|
|
156
|
+
records: reconciliation.records,
|
|
157
|
+
quality: quality.findings,
|
|
158
|
+
repairs: quality.repairs,
|
|
159
|
+
snapshotKind: checkpoint ? 'delta' : 'base',
|
|
160
|
+
parentSnapshotId: checkpoint?.snapshotId ?? null,
|
|
161
|
+
checkpointBefore: checkpoint?.snapshotId ?? null,
|
|
162
|
+
watermark: github.value.watermark,
|
|
163
|
+
window: { fromInclusive, queryAfter, toExclusive: github.value.watermark, precision: 'second' },
|
|
164
|
+
observation: {
|
|
165
|
+
cutoffSource: 'github-response-date',
|
|
166
|
+
preflightDate: github.value.preflightDate,
|
|
167
|
+
responseDates
|
|
168
|
+
},
|
|
169
|
+
coverage: { mode: 'boundary-reread-with-full-reconcile', absoluteCompleteness: false },
|
|
170
|
+
reconciliation: full ? 'full' : 'incremental',
|
|
171
|
+
operations: reconciliation.operations
|
|
172
|
+
});
|
|
173
|
+
const verified = verifySnapshot(root, published.snapshotId);
|
|
174
|
+
if (!verified.ok || !verified.manifest || verified.manifest.schema !== 'raw-manifest/v2') {
|
|
175
|
+
throw new Error(`published snapshot failed verification: ${verified.errors.join('; ')}`);
|
|
176
|
+
}
|
|
177
|
+
const committed = commitGitHubCheckpoint(lease, {
|
|
178
|
+
schema: 'github-checkpoint/v1',
|
|
179
|
+
repository,
|
|
180
|
+
snapshotId: published.snapshotId,
|
|
181
|
+
watermark: github.value.watermark,
|
|
182
|
+
manifestSha256: verified.manifest.manifestSha256,
|
|
183
|
+
committedAt: new Date().toISOString()
|
|
184
|
+
});
|
|
185
|
+
if (!committed.ok) {
|
|
186
|
+
writeJson({ ok: false, error: committed.error });
|
|
187
|
+
return 2;
|
|
188
|
+
}
|
|
189
|
+
writeJson({ ok: true, snapshotId: published.snapshotId, scope, snapshotKind: checkpoint ? 'delta' : 'base', reconciliation: full ? 'full' : 'incremental', created: published.created, objects: github.value.objects.length, records: reconciliation.records.length, watermark: github.value.watermark, deferred: github.value.deferred.length });
|
|
190
|
+
return 0;
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
releaseGitHubCheckpoint(lease);
|
|
117
194
|
}
|
|
118
|
-
const records = normalizeObjects(objects);
|
|
119
|
-
const reconciliation = reconcileRecords(records, scope);
|
|
120
|
-
const observedTo = new Date().toISOString();
|
|
121
|
-
const published = publishSnapshot(root, {
|
|
122
|
-
scope: scope,
|
|
123
|
-
repository,
|
|
124
|
-
observedFrom,
|
|
125
|
-
observedTo,
|
|
126
|
-
objects: objects.map(({ content: _content, ...object }) => object),
|
|
127
|
-
endpoints,
|
|
128
|
-
excerptsEnabled: parsed.options.has('--include-excerpts'),
|
|
129
|
-
records,
|
|
130
|
-
quality: reconciliation.findings,
|
|
131
|
-
repairs: reconciliation.repairs
|
|
132
|
-
});
|
|
133
|
-
writeJson({ ok: true, snapshotId: published.snapshotId, scope, created: published.created, objects: objects.length, records: records.length });
|
|
134
|
-
return 0;
|
|
135
195
|
}
|
|
136
196
|
function verify(args) {
|
|
137
197
|
const parsed = parseArgs(args, new Set(['--root']), new Set());
|
|
@@ -182,7 +242,7 @@ function repair(args) {
|
|
|
182
242
|
return 0;
|
|
183
243
|
}
|
|
184
244
|
function exportSnapshot(args) {
|
|
185
|
-
const parsed = parseArgs(args, new Set(['--root', '--repairs', '--output']), new Set());
|
|
245
|
+
const parsed = parseArgs(args, new Set(['--root', '--repairs', '--output', '--as-of']), new Set());
|
|
186
246
|
if (parsed.positionals.length !== 1)
|
|
187
247
|
throw new Error('export requires one snapshot id');
|
|
188
248
|
const repairMode = optionString(parsed, '--repairs') ?? 'none';
|
|
@@ -196,7 +256,15 @@ function exportSnapshot(args) {
|
|
|
196
256
|
writeJson(verified);
|
|
197
257
|
return 1;
|
|
198
258
|
}
|
|
199
|
-
let content
|
|
259
|
+
let content;
|
|
260
|
+
if (verified.manifest?.schema === 'raw-manifest/v2') {
|
|
261
|
+
content = materializeJson(root, parsed.positionals[0], { asOf: optionString(parsed, '--as-of') });
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
if (optionString(parsed, '--as-of'))
|
|
265
|
+
throw new Error('--as-of is only supported for v2 GitHub snapshots');
|
|
266
|
+
content = fs.readFileSync(path.join(verified.snapshotPath, 'normalized.jsonl'), 'utf8');
|
|
267
|
+
}
|
|
200
268
|
if (repairMode === 'applied')
|
|
201
269
|
content += readAppliedOverlays(root, parsed.positionals[0]);
|
|
202
270
|
if (output === '-')
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { findSnapshot, verifySnapshot } from './store.js';
|
|
4
|
+
function readRecords(snapshotPath, schema) {
|
|
5
|
+
const file = path.join(snapshotPath, 'normalized.jsonl');
|
|
6
|
+
if (!fs.existsSync(file))
|
|
7
|
+
return [];
|
|
8
|
+
return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).flatMap((line) => {
|
|
9
|
+
const value = JSON.parse(line);
|
|
10
|
+
if (value.schema !== schema)
|
|
11
|
+
return [];
|
|
12
|
+
const { schema: _schema, ...record } = value;
|
|
13
|
+
return [record];
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function materializeSnapshot(root, snapshotId, options = {}) {
|
|
17
|
+
const target = options.asOf ? new Date(options.asOf) : null;
|
|
18
|
+
if (target && !Number.isFinite(target.getTime()))
|
|
19
|
+
throw new Error('as-of must be an ISO timestamp');
|
|
20
|
+
const chain = [];
|
|
21
|
+
let currentId = snapshotId;
|
|
22
|
+
let repository = null;
|
|
23
|
+
while (currentId) {
|
|
24
|
+
const currentPath = findSnapshot(root, currentId);
|
|
25
|
+
if (!currentPath)
|
|
26
|
+
throw new Error(`snapshot not found: ${currentId}`);
|
|
27
|
+
const verified = verifySnapshot(root, currentId);
|
|
28
|
+
if (!verified.ok || !verified.manifest)
|
|
29
|
+
throw new Error(`snapshot is not verified: ${currentId}`);
|
|
30
|
+
if (verified.manifest.schema !== 'raw-manifest/v2') {
|
|
31
|
+
if (chain.length > 0)
|
|
32
|
+
throw new Error('v1 and v2 snapshots cannot share a lineage');
|
|
33
|
+
return { snapshotId, records: readRecords(currentPath, 'normalized/v1'), manifest: null };
|
|
34
|
+
}
|
|
35
|
+
const manifest = verified.manifest;
|
|
36
|
+
if (repository && manifest.repository !== repository)
|
|
37
|
+
throw new Error('snapshot lineage repository mismatch');
|
|
38
|
+
repository = manifest.repository;
|
|
39
|
+
chain.push({ id: currentId, path: currentPath, manifest });
|
|
40
|
+
currentId = manifest.parentSnapshotId;
|
|
41
|
+
}
|
|
42
|
+
if (chain.length === 0)
|
|
43
|
+
throw new Error('snapshot lineage is empty');
|
|
44
|
+
const chronological = [...chain].reverse();
|
|
45
|
+
for (let index = 1; index < chronological.length; index += 1) {
|
|
46
|
+
if (new Date(chronological[index - 1].manifest.watermark).getTime() >= new Date(chronological[index].manifest.watermark).getTime()) {
|
|
47
|
+
throw new Error('snapshot watermark is not monotonic');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const view = new Map();
|
|
51
|
+
let appliedManifest = null;
|
|
52
|
+
for (const entry of chronological) {
|
|
53
|
+
if (target && new Date(entry.manifest.watermark).getTime() > target.getTime())
|
|
54
|
+
continue;
|
|
55
|
+
appliedManifest = entry.manifest;
|
|
56
|
+
for (const record of readRecords(entry.path, 'normalized/v2')) {
|
|
57
|
+
const identity = record.resourceIdentity ?? record.sourceIdentity;
|
|
58
|
+
switch (record.operation) {
|
|
59
|
+
case 'tombstone':
|
|
60
|
+
view.delete(identity);
|
|
61
|
+
break;
|
|
62
|
+
case 'unavailable':
|
|
63
|
+
view.set(identity, record);
|
|
64
|
+
break;
|
|
65
|
+
default:
|
|
66
|
+
view.set(identity, { ...record, operation: undefined });
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (target && !appliedManifest)
|
|
72
|
+
throw new Error('no verified snapshot is available at the requested as-of time');
|
|
73
|
+
return {
|
|
74
|
+
snapshotId,
|
|
75
|
+
records: [...view.values()].sort((left, right) => left.recordId.localeCompare(right.recordId)),
|
|
76
|
+
manifest: appliedManifest
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function materializeJson(root, snapshotId, options = {}) {
|
|
80
|
+
const result = materializeSnapshot(root, snapshotId, options);
|
|
81
|
+
return result.records.map((record) => JSON.stringify({ schema: 'normalized/v2', ...record })).join('\n') + (result.records.length ? '\n' : '');
|
|
82
|
+
}
|
|
83
|
+
export { materializeJson, materializeSnapshot };
|
|
84
|
+
//# sourceMappingURL=materialize.js.map
|