@robhowley/pi-remembrancer 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -17
- package/extensions/remembrancer/capture-artifacts.ts +211 -0
- package/extensions/remembrancer/capture-handoff.ts +714 -0
- package/extensions/remembrancer/capture-jobs.ts +112 -0
- package/extensions/remembrancer/capture-matches.ts +145 -0
- package/extensions/remembrancer/capture-notices.ts +54 -0
- package/extensions/remembrancer/capture-publication-lock.mjs +37 -0
- package/extensions/remembrancer/capture-review.ts +84 -12
- package/extensions/remembrancer/capture-sizing.ts +63 -0
- package/extensions/remembrancer/capture-submission.ts +289 -0
- package/extensions/remembrancer/capture-worker-bootstrap.mjs +53 -0
- package/extensions/remembrancer/capture-worker.ts +341 -0
- package/extensions/remembrancer/capture.ts +262 -136
- package/extensions/remembrancer/checkpoints.ts +687 -119
- package/extensions/remembrancer/config.ts +31 -1
- package/extensions/remembrancer/evidence.ts +318 -74
- package/extensions/remembrancer/index.ts +260 -14
- package/extensions/remembrancer/private-sqlite.mjs +17 -0
- package/extensions/remembrancer/proposal-read.ts +223 -9
- package/extensions/remembrancer/proposal-ui.ts +608 -191
- package/extensions/remembrancer/proposals.ts +44 -9
- package/extensions/remembrancer/review-findings.ts +178 -0
- package/extensions/remembrancer/review-pages.ts +58 -16
- package/extensions/remembrancer/review-plan.ts +27 -0
- package/extensions/remembrancer/reviewer-budget.ts +53 -0
- package/extensions/remembrancer/reviewer.ts +166 -30
- package/extensions/remembrancer/taskwarrior.ts +95 -14
- package/package.json +5 -4
- package/skills/remembrancer/SKILL.md +35 -19
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { Type, type Static } from '@sinclair/typebox';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import type { CaptureReview } from './capture-review.js';
|
|
4
|
+
import {
|
|
5
|
+
proposalParameters,
|
|
6
|
+
type EvidenceReference,
|
|
7
|
+
type Proposal,
|
|
8
|
+
type ProposalSubmission,
|
|
9
|
+
} from './proposals.js';
|
|
10
|
+
import {
|
|
11
|
+
captureChangesConflict,
|
|
12
|
+
captureIsSatisfied,
|
|
13
|
+
groupCaptureMatches,
|
|
14
|
+
resolveCaptureMatches,
|
|
15
|
+
validateConsolidatedChange,
|
|
16
|
+
type ResolvedCapture,
|
|
17
|
+
} from './capture-matches.js';
|
|
18
|
+
import { findingKinds, folded, object, text, validateMaterialization } from './review-findings.js';
|
|
19
|
+
import type { TaskRecord } from './taskwarrior.js';
|
|
20
|
+
|
|
21
|
+
const intent = Type.Pick(proposalParameters, ['change', 'question']);
|
|
22
|
+
const state = Type.Object(
|
|
23
|
+
{
|
|
24
|
+
summary: Type.String({ minLength: 1 }),
|
|
25
|
+
status: Type.String({ enum: ['active', 'completed', 'refused', 'uncertain'] }),
|
|
26
|
+
draft: Type.Union([Type.Null(), intent]),
|
|
27
|
+
},
|
|
28
|
+
{ additionalProperties: false },
|
|
29
|
+
);
|
|
30
|
+
const candidate = Type.Object(
|
|
31
|
+
{
|
|
32
|
+
kind: Type.String({ enum: ['task', 'proposal'] }),
|
|
33
|
+
id: Type.String({ minLength: 1 }),
|
|
34
|
+
revision: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
35
|
+
judgment: Type.String({ enum: ['same', 'different', 'ambiguous'] }),
|
|
36
|
+
},
|
|
37
|
+
{ additionalProperties: false },
|
|
38
|
+
);
|
|
39
|
+
export const captureSubmitParameters = Type.Object(
|
|
40
|
+
{
|
|
41
|
+
records: Type.Array(
|
|
42
|
+
Type.Object(
|
|
43
|
+
{
|
|
44
|
+
key: Type.String({ minLength: 1 }),
|
|
45
|
+
observations: Type.Array(
|
|
46
|
+
Type.Object(
|
|
47
|
+
{
|
|
48
|
+
kind: Type.String({ enum: findingKinds }),
|
|
49
|
+
reference: proposalParameters.properties.references.items,
|
|
50
|
+
},
|
|
51
|
+
{ additionalProperties: false },
|
|
52
|
+
),
|
|
53
|
+
{ minItems: 1 },
|
|
54
|
+
),
|
|
55
|
+
states: Type.Array(
|
|
56
|
+
Type.Object({ branchId: Type.String(), state }, { additionalProperties: false }),
|
|
57
|
+
{ minItems: 1 },
|
|
58
|
+
),
|
|
59
|
+
ambiguous: Type.Boolean(),
|
|
60
|
+
candidates: Type.Array(candidate),
|
|
61
|
+
},
|
|
62
|
+
{ additionalProperties: false },
|
|
63
|
+
),
|
|
64
|
+
),
|
|
65
|
+
dispositions: Type.Array(
|
|
66
|
+
Type.Object(
|
|
67
|
+
{
|
|
68
|
+
records: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, uniqueItems: true }),
|
|
69
|
+
reason: Type.String({ minLength: 1 }),
|
|
70
|
+
submission: Type.Union([
|
|
71
|
+
Type.Null(),
|
|
72
|
+
Type.Pick(proposalParameters, ['change', 'question', 'explanation']),
|
|
73
|
+
]),
|
|
74
|
+
},
|
|
75
|
+
{ additionalProperties: false },
|
|
76
|
+
),
|
|
77
|
+
),
|
|
78
|
+
},
|
|
79
|
+
{ additionalProperties: false },
|
|
80
|
+
);
|
|
81
|
+
export type CaptureSubmission = Static<typeof captureSubmitParameters>;
|
|
82
|
+
|
|
83
|
+
function fields(value: unknown, allowed: string[]): Record<string, unknown> {
|
|
84
|
+
const data = object(value);
|
|
85
|
+
if (Object.keys(data).some((key) => !allowed.includes(key)))
|
|
86
|
+
throw new Error('Unknown finalized capture fields');
|
|
87
|
+
return data;
|
|
88
|
+
}
|
|
89
|
+
function array(value: unknown): unknown[] {
|
|
90
|
+
if (!Array.isArray(value)) throw new Error('Invalid finalized capture array');
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Validate declarations, never discover, regroup, or finish proposal content for the reviewer. */
|
|
95
|
+
export function validateCaptureSubmission(
|
|
96
|
+
value: unknown,
|
|
97
|
+
current: CaptureReview,
|
|
98
|
+
tasks: readonly TaskRecord[],
|
|
99
|
+
saved: readonly Proposal[],
|
|
100
|
+
): ProposalSubmission[] {
|
|
101
|
+
const payload = fields(value, ['records', 'dispositions']);
|
|
102
|
+
const records = new Map<
|
|
103
|
+
string,
|
|
104
|
+
{
|
|
105
|
+
resolved: ResolvedCapture;
|
|
106
|
+
states: ReturnType<typeof folded>[];
|
|
107
|
+
references: EvidenceReference[];
|
|
108
|
+
}
|
|
109
|
+
>();
|
|
110
|
+
for (const raw of array(payload['records'])) {
|
|
111
|
+
const data = fields(raw, ['key', 'observations', 'states', 'ambiguous', 'candidates']);
|
|
112
|
+
const key = text(data['key']);
|
|
113
|
+
if (records.has(key) || typeof data['ambiguous'] !== 'boolean')
|
|
114
|
+
throw new Error('Duplicate capture record or invalid ambiguity');
|
|
115
|
+
const observations = array(data['observations']).map((raw) => {
|
|
116
|
+
const observation = fields(raw, ['kind', 'reference']);
|
|
117
|
+
if (!findingKinds.includes(observation['kind'] as (typeof findingKinds)[number]))
|
|
118
|
+
throw new Error('Invalid capture observation kind');
|
|
119
|
+
return observation;
|
|
120
|
+
});
|
|
121
|
+
const references = observations.map((item) => item['reference'] as EvidenceReference);
|
|
122
|
+
// All records, even null dispositions, require exact eligible sources. Context is excluded.
|
|
123
|
+
current.validateReferences(references);
|
|
124
|
+
const branches = new Set(references.map((ref) => ref.branchId));
|
|
125
|
+
const states = array(data['states']).map((raw) => {
|
|
126
|
+
const branch = fields(raw, ['branchId', 'state']);
|
|
127
|
+
if (!branches.delete(text(branch['branchId'])))
|
|
128
|
+
throw new Error('State must identify exactly one observed branch');
|
|
129
|
+
const supplied = fields(branch['state'], ['summary', 'status', 'draft']);
|
|
130
|
+
if (supplied['draft'] !== null) fields(supplied['draft'], ['change', 'question']);
|
|
131
|
+
return folded(supplied);
|
|
132
|
+
});
|
|
133
|
+
if (branches.size || !states.length) throw new Error('Missing branch-specific capture state');
|
|
134
|
+
const matchedTasks: TaskRecord[] = [];
|
|
135
|
+
const matchedProposals: Proposal[] = [];
|
|
136
|
+
let ambiguous = data['ambiguous'];
|
|
137
|
+
const seenCandidates = new Set<string>();
|
|
138
|
+
for (const raw of array(data['candidates'])) {
|
|
139
|
+
const candidate = fields(raw, ['kind', 'id', 'revision', 'judgment']);
|
|
140
|
+
const id = text(candidate['id']);
|
|
141
|
+
const identity = `${candidate['kind']}:${id}`;
|
|
142
|
+
if (seenCandidates.has(identity)) throw new Error('Repeated capture candidate');
|
|
143
|
+
seenCandidates.add(identity);
|
|
144
|
+
if (!['same', 'different', 'ambiguous'].includes(candidate['judgment'] as string))
|
|
145
|
+
throw new Error('Invalid capture candidate judgment');
|
|
146
|
+
let task: TaskRecord | undefined;
|
|
147
|
+
let proposal: Proposal | undefined;
|
|
148
|
+
if (candidate['kind'] === 'task' && candidate['revision'] === undefined) {
|
|
149
|
+
task = tasks.find((item) => item['uuid'] === id);
|
|
150
|
+
if (!task) throw new Error('Unknown retained task candidate');
|
|
151
|
+
} else if (candidate['kind'] === 'proposal') {
|
|
152
|
+
proposal = saved.find((item) => item.id === id);
|
|
153
|
+
if (!proposal || proposal.revision !== candidate['revision'])
|
|
154
|
+
throw new Error('Missing or stale retained proposal candidate');
|
|
155
|
+
} else throw new Error('Invalid capture candidate identity');
|
|
156
|
+
ambiguous ||= candidate['judgment'] === 'ambiguous';
|
|
157
|
+
if (candidate['judgment'] !== 'same') continue;
|
|
158
|
+
if (task) matchedTasks.push(task);
|
|
159
|
+
if (proposal) {
|
|
160
|
+
matchedProposals.push(proposal);
|
|
161
|
+
const uuid = proposal.result?.verified?.uuid;
|
|
162
|
+
if (uuid && ['applied', 'already_satisfied'].includes(proposal.state)) {
|
|
163
|
+
const live = tasks.find((item) => item['uuid'] === uuid);
|
|
164
|
+
if (!live) throw new Error('Matched saved result has no live task; capture unresolved');
|
|
165
|
+
matchedTasks.push(live);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (
|
|
170
|
+
!observations.some((item) => item['kind'] === 'accepted') &&
|
|
171
|
+
!matchedTasks.length &&
|
|
172
|
+
!matchedProposals.length &&
|
|
173
|
+
!states.every(
|
|
174
|
+
(state) =>
|
|
175
|
+
(state.status === 'completed' &&
|
|
176
|
+
observations.some((item) => item['kind'] === 'completion')) ||
|
|
177
|
+
(state.status === 'refused' && observations.some((item) => item['kind'] === 'refusal')),
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
ambiguous = true;
|
|
181
|
+
const targets = new Set(
|
|
182
|
+
states.flatMap((state) => {
|
|
183
|
+
const change = state.draft?.change;
|
|
184
|
+
return change && change.operation !== 'add' ? [change.targetUuid] : [];
|
|
185
|
+
}),
|
|
186
|
+
);
|
|
187
|
+
ambiguous ||= targets.size > 1;
|
|
188
|
+
const matches = resolveCaptureMatches(
|
|
189
|
+
matchedTasks,
|
|
190
|
+
matchedProposals,
|
|
191
|
+
ambiguous,
|
|
192
|
+
[...targets][0],
|
|
193
|
+
);
|
|
194
|
+
records.set(key, {
|
|
195
|
+
resolved: {
|
|
196
|
+
record: { id: key, ambiguous: matches.ambiguous },
|
|
197
|
+
state: states[0]!,
|
|
198
|
+
matches,
|
|
199
|
+
},
|
|
200
|
+
states,
|
|
201
|
+
references,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
const requiredGroups = groupCaptureMatches(
|
|
205
|
+
[...records.values()].map((item) => item.resolved),
|
|
206
|
+
).map((group) => new Set(group.map((item) => item.record.id)));
|
|
207
|
+
const disposed = new Set<string>();
|
|
208
|
+
const submissions: ProposalSubmission[] = [];
|
|
209
|
+
for (const raw of array(payload['dispositions'])) {
|
|
210
|
+
const disposition = fields(raw, ['records', 'reason', 'submission']);
|
|
211
|
+
text(disposition['reason']);
|
|
212
|
+
const keys = array(disposition['records']).map(text);
|
|
213
|
+
const keySet = new Set(keys);
|
|
214
|
+
if (
|
|
215
|
+
!keys.length ||
|
|
216
|
+
keySet.size !== keys.length ||
|
|
217
|
+
keys.some((key) => !records.has(key) || disposed.has(key))
|
|
218
|
+
)
|
|
219
|
+
throw new Error('Every record requires exactly one disposition');
|
|
220
|
+
if (
|
|
221
|
+
!requiredGroups.some(
|
|
222
|
+
(group) => group.size === keySet.size && [...group].every((key) => keySet.has(key)),
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
throw new Error('Declared disposition does not match definite identities');
|
|
226
|
+
keys.forEach((key) => disposed.add(key));
|
|
227
|
+
const group = keys.map((key) => records.get(key)!);
|
|
228
|
+
const states = group.flatMap((item) => item.states);
|
|
229
|
+
const matches = resolveCaptureMatches(
|
|
230
|
+
group.flatMap((item) => item.resolved.matches.tasks),
|
|
231
|
+
group.flatMap((item) => item.resolved.matches.proposals),
|
|
232
|
+
group.some((item) => item.resolved.matches.ambiguous),
|
|
233
|
+
);
|
|
234
|
+
const conflictingChanges = captureChangesConflict(states);
|
|
235
|
+
const satisfied = states.every((state) => captureIsSatisfied(state, matches));
|
|
236
|
+
if (matches.verifyOnly && (!satisfied || disposition['submission'] !== null))
|
|
237
|
+
throw new Error('Matched saved application is verify-only; capture unresolved');
|
|
238
|
+
if (disposition['submission'] !== null)
|
|
239
|
+
fields(disposition['submission'], ['change', 'question', 'explanation']);
|
|
240
|
+
let materialized: ReturnType<typeof validateMaterialization> = null;
|
|
241
|
+
for (const state of states) {
|
|
242
|
+
const validated = validateMaterialization(
|
|
243
|
+
disposition,
|
|
244
|
+
{ id: keys[0]!, ambiguous: matches.ambiguous },
|
|
245
|
+
state,
|
|
246
|
+
{
|
|
247
|
+
expected: matches.expected,
|
|
248
|
+
conflictingChanges,
|
|
249
|
+
allowNoop: satisfied,
|
|
250
|
+
tracked: matches.tasks.length > 0 || matches.proposals.length > 0,
|
|
251
|
+
questions: [...matches.questions, ...states.map((item) => item.draft?.question)],
|
|
252
|
+
},
|
|
253
|
+
);
|
|
254
|
+
if (materialized && !isDeepStrictEqual(materialized, validated))
|
|
255
|
+
throw new Error('Inconsistent finalized capture materialization');
|
|
256
|
+
materialized = validated;
|
|
257
|
+
}
|
|
258
|
+
const pending = matches.proposal;
|
|
259
|
+
if (!materialized && pending)
|
|
260
|
+
throw new Error('Saved pending proposal requires a revision or question');
|
|
261
|
+
if (
|
|
262
|
+
!materialized &&
|
|
263
|
+
matches.proposals.some((item) => item.state === 'dismissed') &&
|
|
264
|
+
states.some((state) => state.status === 'active')
|
|
265
|
+
)
|
|
266
|
+
throw new Error('Dismissed proposal is not verified satisfaction');
|
|
267
|
+
if (!materialized) continue;
|
|
268
|
+
if (!materialized.question && group.length > 1)
|
|
269
|
+
validateConsolidatedChange(materialized.change, states);
|
|
270
|
+
if (
|
|
271
|
+
pending &&
|
|
272
|
+
(pending.draft ?? pending).change.operation !== 'add' &&
|
|
273
|
+
materialized.change.operation === 'add'
|
|
274
|
+
)
|
|
275
|
+
throw new Error('Saved existing-task proposal cannot become an addition');
|
|
276
|
+
if (matches.proposals.some((item) => item.state === 'dismissed') && !materialized.question)
|
|
277
|
+
throw new Error('Reopening a dismissed obligation requires a question');
|
|
278
|
+
submissions.push({
|
|
279
|
+
...materialized,
|
|
280
|
+
references: group.flatMap((item) => item.references),
|
|
281
|
+
...(pending ? { id: pending.id, expectedRevision: pending.revision } : {}),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
if (disposed.size !== records.size)
|
|
285
|
+
throw new Error('Every record requires exactly one disposition');
|
|
286
|
+
// Recheck permissions, exact citations and trusted snapshots using the publication validator.
|
|
287
|
+
current.completion(submissions);
|
|
288
|
+
return structuredClone(submissions);
|
|
289
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Only the originating Node Pi installation supplies jiti and the public SDK.
|
|
2
|
+
// No local dependency search, extension discovery, or fallback loader.
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { appendFileSync, realpathSync } from 'node:fs';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const [piEntry, database, inbox] = process.argv.slice(2);
|
|
10
|
+
let owner;
|
|
11
|
+
try {
|
|
12
|
+
const entry = realpathSync(piEntry);
|
|
13
|
+
const host = createRequire(entry);
|
|
14
|
+
const { createJiti } = host('jiti');
|
|
15
|
+
const jiti = createJiti(import.meta.url, {
|
|
16
|
+
interopDefault: true,
|
|
17
|
+
alias: {
|
|
18
|
+
'@earendil-works/pi-coding-agent': join(dirname(entry), 'index.js'),
|
|
19
|
+
'@earendil-works/pi-ai': fileURLToPath(createJiti(entry).esmResolve('@earendil-works/pi-ai')),
|
|
20
|
+
'@sinclair/typebox': host.resolve('typebox'),
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
const { CaptureWorkerOwnership } = await jiti.import('./capture-jobs.ts');
|
|
24
|
+
try {
|
|
25
|
+
owner = CaptureWorkerOwnership.claim(database);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error.errcode === 5 || error.message.startsWith('A capture worker already owns'))
|
|
28
|
+
process.exit(0);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
// Singleton is acquired before loading the SDK or importing handoffs.
|
|
32
|
+
const { runCaptureWorker } = await jiti.import('./capture-worker.ts');
|
|
33
|
+
await runCaptureWorker({ database, inbox, owner });
|
|
34
|
+
owner = undefined;
|
|
35
|
+
process.exit(0);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
owner?.release();
|
|
38
|
+
// Deliberately omit provider responses, which can contain credentials.
|
|
39
|
+
try {
|
|
40
|
+
appendFileSync(
|
|
41
|
+
database + '.capture.log',
|
|
42
|
+
`${new Date().toISOString()} Worker bootstrap failed${
|
|
43
|
+
['EACCES', 'EPERM', 'ENOSPC', 'EIO', 'ENOENT', 'ENOTDIR', 'EROFS'].includes(error?.code)
|
|
44
|
+
? ` (${error.code})`
|
|
45
|
+
: ''
|
|
46
|
+
}\n`,
|
|
47
|
+
{ mode: 0o600 },
|
|
48
|
+
);
|
|
49
|
+
} catch {
|
|
50
|
+
/* evidence remains for recovery */
|
|
51
|
+
}
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { appendFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { CheckpointStore } from './checkpoints.js';
|
|
6
|
+
import {
|
|
7
|
+
CaptureWorkerOwnership,
|
|
8
|
+
CapturePreparationError,
|
|
9
|
+
CaptureRetryableError,
|
|
10
|
+
CAPTURE_BUDGET_MS,
|
|
11
|
+
type CaptureAttempt,
|
|
12
|
+
} from './capture-jobs.js';
|
|
13
|
+
import {
|
|
14
|
+
cleanupCompletedSnapshot,
|
|
15
|
+
CaptureHandoffError,
|
|
16
|
+
importReadyHandoff,
|
|
17
|
+
type HandoffInput,
|
|
18
|
+
} from './capture-handoff.js';
|
|
19
|
+
import type { reviewPreparedCapture } from './capture.js';
|
|
20
|
+
import type { ProposalSubmission } from './proposals.js';
|
|
21
|
+
import { publishProposalNotice } from './capture-notices.js';
|
|
22
|
+
|
|
23
|
+
const CLEANUP_GRACE_MS = 5_000;
|
|
24
|
+
|
|
25
|
+
/** A launch acknowledgement means spawned, not imported or completed. Recovery retries later. */
|
|
26
|
+
export function launchCaptureWorker(
|
|
27
|
+
database: string,
|
|
28
|
+
inbox: string,
|
|
29
|
+
host: NonNullable<HandoffInput['execution']['host']>,
|
|
30
|
+
): Promise<number> {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const child = spawn(
|
|
33
|
+
host.nodeExecutable,
|
|
34
|
+
[
|
|
35
|
+
fileURLToPath(new URL('./capture-worker-bootstrap.mjs', import.meta.url)),
|
|
36
|
+
host.piEntry,
|
|
37
|
+
database,
|
|
38
|
+
inbox,
|
|
39
|
+
],
|
|
40
|
+
{ detached: true, stdio: 'ignore', shell: false },
|
|
41
|
+
);
|
|
42
|
+
child.once('error', reject);
|
|
43
|
+
child.once('spawn', () => {
|
|
44
|
+
child.unref();
|
|
45
|
+
resolve(child.pid!);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type WorkerOptions = {
|
|
51
|
+
database: string;
|
|
52
|
+
inbox: string;
|
|
53
|
+
owner?: CaptureWorkerOwnership;
|
|
54
|
+
// Deterministic process/interleaving tests, not user configuration.
|
|
55
|
+
budgetMs?: number;
|
|
56
|
+
graceMs?: number;
|
|
57
|
+
afterRelease?: () => Promise<void>;
|
|
58
|
+
review?: typeof reviewPreparedCapture;
|
|
59
|
+
terminate?: () => never;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function busy(error: unknown): boolean {
|
|
63
|
+
return (
|
|
64
|
+
(error as { errcode?: number })?.errcode === 5 ||
|
|
65
|
+
(error instanceof Error &&
|
|
66
|
+
[
|
|
67
|
+
'A capture worker already owns this database',
|
|
68
|
+
'A remembrancer review is already open',
|
|
69
|
+
'A remembrancer review is already open in another Pi process',
|
|
70
|
+
].includes(error.message))
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** One on-demand drain. No archive discovery and no capture-setting check after admission. */
|
|
75
|
+
export async function runCaptureWorker(options: WorkerOptions): Promise<void> {
|
|
76
|
+
const { database, inbox } = options;
|
|
77
|
+
let owner: CaptureWorkerOwnership | undefined = options.owner;
|
|
78
|
+
let store: CheckpointStore | undefined;
|
|
79
|
+
const seenSignals = new Set<string>();
|
|
80
|
+
const blockedSignals = new Set<string>();
|
|
81
|
+
const attemptedCleanup = new Set<string>();
|
|
82
|
+
const diagnose = async (message: string) => {
|
|
83
|
+
try {
|
|
84
|
+
await appendFile(database + '.capture.log', `${new Date().toISOString()} ${message}\n`, {
|
|
85
|
+
mode: 0o600,
|
|
86
|
+
});
|
|
87
|
+
} catch {
|
|
88
|
+
/* Failed diagnostics cannot reject committed work. Durable evidence remains. */
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const localFailure = (phase: string, id: string, error: unknown) =>
|
|
92
|
+
diagnose(new CaptureHandoffError(phase, 'local-failure', id, error).message);
|
|
93
|
+
const repairCompleted = async () => {
|
|
94
|
+
try {
|
|
95
|
+
await publishProposalNotice(store!);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
await localFailure('notice-publication', 'store', error);
|
|
98
|
+
}
|
|
99
|
+
for (const id of store!.pendingSnapshotCleanupIds(owner!)) {
|
|
100
|
+
if (attemptedCleanup.has(id)) continue;
|
|
101
|
+
attemptedCleanup.add(id);
|
|
102
|
+
try {
|
|
103
|
+
if (await cleanupCompletedSnapshot(store!, owner!, id)) attemptedCleanup.delete(id);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
await localFailure('snapshot-cleanup', id, error);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
const readyFiles = async () => {
|
|
110
|
+
try {
|
|
111
|
+
return (await readdir(inbox)).filter((name) => name.endsWith('.ready.json')).sort();
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
if (!owner) {
|
|
119
|
+
try {
|
|
120
|
+
owner = CaptureWorkerOwnership.claim(database);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (busy(error)) return;
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
store = new CheckpointStore(database);
|
|
127
|
+
owner.assertStore(store.file);
|
|
128
|
+
store.recoverInterruptedCaptureAttempts(owner);
|
|
129
|
+
for (;;) {
|
|
130
|
+
for (const name of await readyFiles()) {
|
|
131
|
+
if (seenSignals.has(name)) continue;
|
|
132
|
+
seenSignals.add(name);
|
|
133
|
+
const id = /^[\w-]{1,128}\.ready\.json$/.test(name)
|
|
134
|
+
? name.slice(0, -'.ready.json'.length)
|
|
135
|
+
: 'retained-artifact';
|
|
136
|
+
try {
|
|
137
|
+
const imported = await importReadyHandoff(store, owner, join(inbox, name));
|
|
138
|
+
if (imported.signalCleanupPending)
|
|
139
|
+
await diagnose(imported.cleanupDiagnostic ?? `Capture signal-cleanup pending [${id}]`);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
// Retain unknown evidence. Storage still fences every unimported signal.
|
|
142
|
+
blockedSignals.add(name);
|
|
143
|
+
if (error instanceof CaptureHandoffError) await diagnose(error.message);
|
|
144
|
+
else await localFailure('ready-import', id, error);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
// Completed rows, not ready files or model replay, authorize repair on every wake.
|
|
148
|
+
await repairCompleted();
|
|
149
|
+
const job = store.nextRunnableCaptureJob(owner);
|
|
150
|
+
if (!job) {
|
|
151
|
+
// Repair commits arriving during the preceding asynchronous sidecar write.
|
|
152
|
+
await repairCompleted();
|
|
153
|
+
// Invalidate BEFORE release. A new owner object is required on reacquisition.
|
|
154
|
+
owner.release();
|
|
155
|
+
owner = undefined;
|
|
156
|
+
await options.afterRelease?.();
|
|
157
|
+
if (
|
|
158
|
+
!(await readyFiles()).some((name) => !seenSignals.has(name)) &&
|
|
159
|
+
(blockedSignals.size > 0 || !store.captureRecoveryPending())
|
|
160
|
+
)
|
|
161
|
+
break;
|
|
162
|
+
try {
|
|
163
|
+
owner = CaptureWorkerOwnership.claim(database);
|
|
164
|
+
store.recoverInterruptedCaptureAttempts(owner);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (busy(error)) break;
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const id = job.manifest.id;
|
|
172
|
+
let attempt: CaptureAttempt | undefined;
|
|
173
|
+
try {
|
|
174
|
+
attempt = store.claimCaptureAttempt(owner, id);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
// Initial coordination contention is uncounted. Defer this drain, not a spin.
|
|
177
|
+
if (busy(error)) break;
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
if (!attempt) continue;
|
|
181
|
+
const currentOwner = owner;
|
|
182
|
+
const controller = new AbortController();
|
|
183
|
+
const expiresAt = performance.now() + (options.budgetMs ?? CAPTURE_BUDGET_MS);
|
|
184
|
+
const previousCwd = process.cwd();
|
|
185
|
+
let fatalTimer: ReturnType<typeof setTimeout> | undefined;
|
|
186
|
+
let executionFinished = false;
|
|
187
|
+
const admitted = attempt;
|
|
188
|
+
const revoke = (error: unknown) => {
|
|
189
|
+
if (executionFinished || controller.signal.aborted) return;
|
|
190
|
+
controller.abort(error);
|
|
191
|
+
// Keep ownership through cooperative cleanup, but never wait forever.
|
|
192
|
+
fatalTimer = setTimeout(() => {
|
|
193
|
+
currentOwner.release();
|
|
194
|
+
(options.terminate ?? (() => process.exit(1)))();
|
|
195
|
+
}, options.graceMs ?? CLEANUP_GRACE_MS);
|
|
196
|
+
try {
|
|
197
|
+
store!.failCaptureJob(
|
|
198
|
+
currentOwner,
|
|
199
|
+
admitted,
|
|
200
|
+
error instanceof CaptureRetryableError ? error.message : 'Capture authority revoked',
|
|
201
|
+
error instanceof CaptureRetryableError,
|
|
202
|
+
);
|
|
203
|
+
} catch {
|
|
204
|
+
/* Store failures still abort execution. Durable recovery handles any leftover claim. */
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const check = () => {
|
|
208
|
+
try {
|
|
209
|
+
controller.signal.throwIfAborted();
|
|
210
|
+
store!.assertCaptureAttempt(currentOwner, admitted);
|
|
211
|
+
if (performance.now() >= expiresAt)
|
|
212
|
+
throw new CaptureRetryableError('Capture review timed out');
|
|
213
|
+
} catch (error) {
|
|
214
|
+
revoke(error);
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
const timer = setTimeout(
|
|
219
|
+
() => revoke(new CaptureRetryableError('Capture review timed out')),
|
|
220
|
+
options.budgetMs ?? CAPTURE_BUDGET_MS,
|
|
221
|
+
);
|
|
222
|
+
const authorityPoll = setInterval(() => {
|
|
223
|
+
try {
|
|
224
|
+
check();
|
|
225
|
+
} catch {
|
|
226
|
+
// check() has aborted the controller and started the cleanup grace.
|
|
227
|
+
}
|
|
228
|
+
}, 250);
|
|
229
|
+
const stopPolling = () => {
|
|
230
|
+
executionFinished = true;
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
clearInterval(authorityPoll);
|
|
233
|
+
if (fatalTimer) clearTimeout(fatalTimer);
|
|
234
|
+
};
|
|
235
|
+
let phase = 'evidence-preparation';
|
|
236
|
+
try {
|
|
237
|
+
check();
|
|
238
|
+
process.chdir(job.manifest.execution.cwd);
|
|
239
|
+
const current = store.prepareCaptureJob(owner, attempt);
|
|
240
|
+
let submissions: ProposalSubmission[] = [];
|
|
241
|
+
if (current.hasEvidence) {
|
|
242
|
+
const { execution, source } = job.manifest;
|
|
243
|
+
const { runtime } = execution;
|
|
244
|
+
phase = 'reviewer-setup-prompt-cleanup';
|
|
245
|
+
const { getPackageDir, ModelRuntime, SettingsManager } =
|
|
246
|
+
await import('@earendil-works/pi-coding-agent');
|
|
247
|
+
check();
|
|
248
|
+
// The SDK caches stored-auth command output process-wide. Clear the
|
|
249
|
+
// selected host's own cache before resolving another project's auth.
|
|
250
|
+
const { clearApiKeyCache } = await import(
|
|
251
|
+
pathToFileURL(join(getPackageDir(), 'dist/core/model-registry.js')).href
|
|
252
|
+
);
|
|
253
|
+
clearApiKeyCache();
|
|
254
|
+
check();
|
|
255
|
+
const settingsManager = SettingsManager.create(execution.cwd, execution.agentDir, {
|
|
256
|
+
projectTrusted: runtime.projectTrusted,
|
|
257
|
+
});
|
|
258
|
+
// Raw model headers can be credentials. Re-resolve their originating
|
|
259
|
+
// configuration references, without a catalog lookup or storing values.
|
|
260
|
+
let modelRuntime;
|
|
261
|
+
if (runtime.headerNames?.length) {
|
|
262
|
+
modelRuntime = await ModelRuntime.create({
|
|
263
|
+
authPath: join(execution.agentDir, 'auth.json'),
|
|
264
|
+
modelsPath: join(execution.agentDir, 'models.json'),
|
|
265
|
+
refreshOnCreate: false,
|
|
266
|
+
signal: controller.signal,
|
|
267
|
+
});
|
|
268
|
+
check();
|
|
269
|
+
const auth = await modelRuntime.getAuth(runtime.model, { signal: controller.signal });
|
|
270
|
+
check();
|
|
271
|
+
const available = new Set(
|
|
272
|
+
Object.keys(auth?.auth.headers ?? {}).map((name) => name.toLowerCase()),
|
|
273
|
+
);
|
|
274
|
+
if (runtime.headerNames.some((name) => !available.has(name.toLowerCase())))
|
|
275
|
+
throw Error('Originating model headers are unavailable from Pi configuration');
|
|
276
|
+
}
|
|
277
|
+
check();
|
|
278
|
+
const review = options.review ?? (await import('./capture.js')).reviewPreparedCapture;
|
|
279
|
+
check();
|
|
280
|
+
submissions = await review(
|
|
281
|
+
current,
|
|
282
|
+
store,
|
|
283
|
+
{
|
|
284
|
+
cwd: execution.cwd,
|
|
285
|
+
agentDir: execution.agentDir,
|
|
286
|
+
model: runtime.model,
|
|
287
|
+
thinkingLevel: runtime.thinkingLevel,
|
|
288
|
+
settingsManager,
|
|
289
|
+
...(modelRuntime ? { modelRuntime } : {}),
|
|
290
|
+
sessionId: source.sessionId,
|
|
291
|
+
signal: controller.signal,
|
|
292
|
+
},
|
|
293
|
+
check,
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
check();
|
|
297
|
+
phase = 'atomic-publication';
|
|
298
|
+
store.finishCaptureJob(owner, attempt, submissions);
|
|
299
|
+
// Completion revokes the UUID. Sidecar repair is not attempt execution.
|
|
300
|
+
stopPolling();
|
|
301
|
+
await repairCompleted();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
const contended =
|
|
304
|
+
(phase === 'evidence-preparation' || phase === 'atomic-publication') && busy(error);
|
|
305
|
+
// Classified preparation failures have already persisted and abandoned.
|
|
306
|
+
const diagnostic =
|
|
307
|
+
error instanceof CapturePreparationError
|
|
308
|
+
? new CaptureHandoffError(phase, error.category, id).message
|
|
309
|
+
: new CaptureHandoffError(phase, 'execution-failure', id, error).message;
|
|
310
|
+
if (isActive(currentOwner, attempt)) {
|
|
311
|
+
store.failCaptureJob(
|
|
312
|
+
currentOwner,
|
|
313
|
+
attempt,
|
|
314
|
+
contended ? 'Manual review contention; deferred' : diagnostic,
|
|
315
|
+
contended || error instanceof CaptureRetryableError,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
if (!contended) await diagnose(diagnostic);
|
|
319
|
+
} finally {
|
|
320
|
+
stopPolling();
|
|
321
|
+
if (isActive(currentOwner, attempt)) currentOwner.abandon(attempt);
|
|
322
|
+
process.chdir(previousCwd);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
} catch (error) {
|
|
326
|
+
await localFailure('worker', 'store', error);
|
|
327
|
+
throw error;
|
|
328
|
+
} finally {
|
|
329
|
+
owner?.release();
|
|
330
|
+
store?.close();
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function isActive(owner: CaptureWorkerOwnership, attempt: CaptureAttempt): boolean {
|
|
335
|
+
try {
|
|
336
|
+
owner.assertAttempt(attempt);
|
|
337
|
+
return true;
|
|
338
|
+
} catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
}
|