@evomap/evolver-cli 2.0.42 → 2.0.44
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/autoRecall.d.ts +24 -5
- package/dist/autoRecall.js +233 -12
- package/dist/autoexec.d.ts +69 -10
- package/dist/autoexec.js +847 -137
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +71 -26
- package/dist/cliContracts.js +29 -7
- package/dist/cliEntry.d.ts +3 -0
- package/dist/cliEntry.js +63 -0
- package/dist/commandCatalog.d.ts +1 -0
- package/dist/commandCatalog.js +1 -0
- package/dist/contextDelivery.d.ts +12 -0
- package/dist/contextDelivery.js +139 -0
- package/dist/cycleConsumer.js +9 -1
- package/dist/dispatch.js +6 -0
- package/dist/feedbackOutbox.d.ts +96 -0
- package/dist/feedbackOutbox.js +510 -0
- package/dist/feedbackOutboxCli.d.ts +7 -0
- package/dist/feedbackOutboxCli.js +208 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +286 -69
- package/dist/lifecycle.d.ts +18 -0
- package/dist/lifecycle.js +130 -3
- package/dist/lifecycleBootstrapTransaction.js +1 -6
- package/dist/liveStatus.d.ts +27 -0
- package/dist/liveStatus.js +197 -0
- package/dist/outboxLock.d.ts +7 -0
- package/dist/outboxLock.js +141 -0
- package/dist/promptRecallHook.d.ts +7 -22
- package/dist/promptRecallHook.js +20 -489
- package/dist/promptRecallRuntime.d.ts +24 -0
- package/dist/promptRecallRuntime.js +678 -0
- package/dist/promptRecallShared.d.ts +18 -0
- package/dist/promptRecallShared.js +119 -0
- package/dist/recall.js +27 -6
- package/dist/runtimeTelemetry.d.ts +9 -0
- package/dist/runtimeTelemetry.js +16 -0
- package/dist/sessionIngest.d.ts +25 -2
- package/dist/sessionIngest.js +196 -32
- package/dist/setupHooks.js +63 -13
- package/dist/setupHooksLifecycle.js +39 -17
- package/dist/skill2gep.d.ts +11 -0
- package/dist/skill2gep.js +23 -3
- package/dist/solo/mode.js +4 -0
- package/dist/taskCommitments.d.ts +4 -2
- package/dist/taskCommitments.js +208 -114
- package/dist/taskOutcomeOutbox.d.ts +83 -0
- package/dist/taskOutcomeOutbox.js +553 -0
- package/dist/workflowRuntime.js +12 -0
- package/package.json +11 -7
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable autoexec applied-use feedback. The local event and the optional Hub
|
|
3
|
+
* reuse-result have separate acknowledgements: local projection must complete
|
|
4
|
+
* before the first network dispatch, and a started dispatch is never replayed
|
|
5
|
+
* without independent reconciliation evidence.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
8
|
+
import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
9
|
+
import { basename, dirname, join } from 'node:path';
|
|
10
|
+
import { hub } from '@evomap/evolver-core';
|
|
11
|
+
import { prepareOutboxDirectory, withOutboxLock } from './outboxLock.js';
|
|
12
|
+
const SCHEMA_VERSION = 'autoexec-feedback-outbox.v1';
|
|
13
|
+
const OPERATION_PREFIX = 'autoexec-feedback:';
|
|
14
|
+
const EVENT_PREFIX = 'autoexec-applied-use:';
|
|
15
|
+
const SHA256_ID = /^sha256:[a-f0-9]{64}$/;
|
|
16
|
+
const OPERATION_ID = /^autoexec-feedback:[a-f0-9]{64}$/;
|
|
17
|
+
const ROW_NAME = /^[a-f0-9]{64}\.json$/;
|
|
18
|
+
const MAX_ROW_BYTES = 64 * 1024;
|
|
19
|
+
const MAX_SIGNALS = 32;
|
|
20
|
+
const MAX_SIGNAL_CHARS = 160;
|
|
21
|
+
const TERMINAL_DISPOSITIONS = new Set([
|
|
22
|
+
'completed', 'denied', 'invalid_target', 'deadline_exceeded', 'budget_exceeded',
|
|
23
|
+
'resource_denied', 'consent_denied', 'timed_out', 'cancelled', 'crashed',
|
|
24
|
+
'rejected', 'unsafe_to_replay',
|
|
25
|
+
]);
|
|
26
|
+
export class FeedbackOutboxError extends Error {
|
|
27
|
+
constructor(message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = 'FeedbackOutboxError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Only a sender that proves no Hub request began may permit a later retry. */
|
|
33
|
+
export class FeedbackNotDispatchedError extends Error {
|
|
34
|
+
constructor(message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'FeedbackNotDispatchedError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function digest(value) {
|
|
40
|
+
return createHash('sha256').update(value, 'utf8').digest('hex');
|
|
41
|
+
}
|
|
42
|
+
function hasControlCharacter(value) {
|
|
43
|
+
return [...value].some((character) => {
|
|
44
|
+
const code = character.charCodeAt(0);
|
|
45
|
+
return code < 32 || code === 127;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function stripControlCharacters(value) {
|
|
49
|
+
return [...value].map((character) => {
|
|
50
|
+
const code = character.charCodeAt(0);
|
|
51
|
+
return code < 32 || code === 127 ? ' ' : character;
|
|
52
|
+
}).join('');
|
|
53
|
+
}
|
|
54
|
+
function exactString(value, label, maxLength = 256) {
|
|
55
|
+
if (typeof value !== 'string' || !value || value.length > maxLength || hasControlCharacter(value)) {
|
|
56
|
+
throw new FeedbackOutboxError(`invalid ${label}`);
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
function safeReason(value, label) {
|
|
61
|
+
const raw = exactString(value, label, 256);
|
|
62
|
+
const cleaned = stripControlCharacters(hub.redactString(raw)).trim();
|
|
63
|
+
if (!cleaned)
|
|
64
|
+
throw new FeedbackOutboxError(`invalid ${label}`);
|
|
65
|
+
return cleaned.slice(0, 256);
|
|
66
|
+
}
|
|
67
|
+
function safeSignals(signals) {
|
|
68
|
+
if (!Array.isArray(signals))
|
|
69
|
+
throw new FeedbackOutboxError('invalid task signals');
|
|
70
|
+
const out = [];
|
|
71
|
+
const seen = new Set();
|
|
72
|
+
for (const item of signals) {
|
|
73
|
+
if (out.length >= MAX_SIGNALS)
|
|
74
|
+
break;
|
|
75
|
+
if (typeof item !== 'string')
|
|
76
|
+
continue;
|
|
77
|
+
const text = stripControlCharacters(hub.redactString(item)).trim().slice(0, MAX_SIGNAL_CHARS);
|
|
78
|
+
if (!text || seen.has(text))
|
|
79
|
+
continue;
|
|
80
|
+
seen.add(text);
|
|
81
|
+
out.push(text);
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/** One operation per claim root and exact asset, even if the task id is later reused. */
|
|
86
|
+
export function feedbackIdentity(claimRoot, assetId) {
|
|
87
|
+
const root = exactString(claimRoot, 'claim root', 1024);
|
|
88
|
+
if (!SHA256_ID.test(assetId))
|
|
89
|
+
throw new FeedbackOutboxError('invalid applied asset id');
|
|
90
|
+
const claimRootDigest = digest(root);
|
|
91
|
+
const operationDigest = digest(`${claimRootDigest}\u0000${assetId}`);
|
|
92
|
+
return {
|
|
93
|
+
operationId: `${OPERATION_PREFIX}${operationDigest}`,
|
|
94
|
+
sourceEventId: `${EVENT_PREFIX}${operationDigest}`,
|
|
95
|
+
claimRootDigest,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function copyAppliedUse(use) {
|
|
99
|
+
if (use.schemaVersion !== 'applied-use.v1'
|
|
100
|
+
|| !SHA256_ID.test(use.assetId)
|
|
101
|
+
|| !exactString(use.geneId, 'gene id')
|
|
102
|
+
|| !exactString(use.cycleId, 'cycle id')
|
|
103
|
+
|| !['hub', 'local', 'migrated', 'unknown'].includes(use.source)
|
|
104
|
+
|| !['success', 'failed', 'inert', 'inconclusive'].includes(use.outcome)
|
|
105
|
+
|| (use.producedValue !== null && typeof use.producedValue !== 'boolean')
|
|
106
|
+
|| use.applicationBinding !== 'selected_execution'
|
|
107
|
+
|| use.verification !== 'unverified') {
|
|
108
|
+
throw new FeedbackOutboxError('invalid applied-use evidence');
|
|
109
|
+
}
|
|
110
|
+
if (use.outcome === 'success' && use.producedValue !== true)
|
|
111
|
+
throw new FeedbackOutboxError('success lacks produced value');
|
|
112
|
+
if (use.outcome === 'inert' && use.producedValue !== false)
|
|
113
|
+
throw new FeedbackOutboxError('inert outcome has produced value');
|
|
114
|
+
if (use.capsuleId !== undefined && !SHA256_ID.test(use.capsuleId))
|
|
115
|
+
throw new FeedbackOutboxError('invalid capsule id');
|
|
116
|
+
if (use.eventId !== undefined && !SHA256_ID.test(use.eventId))
|
|
117
|
+
throw new FeedbackOutboxError('invalid event id');
|
|
118
|
+
if (use.hubOriginDestinationId !== undefined) {
|
|
119
|
+
if (!SHA256_ID.test(use.hubOriginDestinationId))
|
|
120
|
+
throw new FeedbackOutboxError('invalid Hub origin destination id');
|
|
121
|
+
if (use.source !== 'hub')
|
|
122
|
+
throw new FeedbackOutboxError('non-Hub use has Hub origin');
|
|
123
|
+
}
|
|
124
|
+
if (use.terminalDisposition !== undefined && !TERMINAL_DISPOSITIONS.has(use.terminalDisposition)) {
|
|
125
|
+
throw new FeedbackOutboxError('invalid terminal disposition');
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
schemaVersion: 'applied-use.v1', assetId: use.assetId, geneId: use.geneId,
|
|
129
|
+
cycleId: use.cycleId, source: use.source, outcome: use.outcome,
|
|
130
|
+
producedValue: use.producedValue, applicationBinding: 'selected_execution',
|
|
131
|
+
verification: 'unverified',
|
|
132
|
+
...(use.capsuleId ? { capsuleId: use.capsuleId } : {}),
|
|
133
|
+
...(use.eventId ? { eventId: use.eventId } : {}),
|
|
134
|
+
...(use.hubOriginDestinationId ? { hubOriginDestinationId: use.hubOriginDestinationId } : {}),
|
|
135
|
+
...(use.terminalDisposition ? { terminalDisposition: use.terminalDisposition } : {}),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function unboundHubReason(use, destinationId) {
|
|
139
|
+
if (!use.hubOriginDestinationId)
|
|
140
|
+
return 'hub_origin_unbound';
|
|
141
|
+
if (!destinationId)
|
|
142
|
+
return 'hub_destination_unbound';
|
|
143
|
+
return 'hub_origin_mismatch';
|
|
144
|
+
}
|
|
145
|
+
function immutablePayload(record) {
|
|
146
|
+
return {
|
|
147
|
+
...immutableAppliedUseEvidence(record),
|
|
148
|
+
...(record.report ? { report: record.report } : {}),
|
|
149
|
+
...(record.destinationId ? { destinationId: record.destinationId } : {}),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function immutableAppliedUseEvidence(record) {
|
|
153
|
+
return {
|
|
154
|
+
schemaVersion: record.schemaVersion, operationId: record.operationId,
|
|
155
|
+
sourceEventId: record.sourceEventId, claimRootDigest: record.claimRootDigest,
|
|
156
|
+
taskId: record.taskId, signals: record.signals, appliedUse: record.appliedUse,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function payloadDigest(record) {
|
|
160
|
+
return digest(JSON.stringify(immutablePayload(record)));
|
|
161
|
+
}
|
|
162
|
+
function frozen(value) {
|
|
163
|
+
if (value && typeof value === 'object') {
|
|
164
|
+
for (const child of Object.values(value))
|
|
165
|
+
frozen(child);
|
|
166
|
+
Object.freeze(value);
|
|
167
|
+
}
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
function validateRecord(value, expectedOperationId) {
|
|
171
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
172
|
+
throw new FeedbackOutboxError('invalid feedback outbox record');
|
|
173
|
+
const row = value;
|
|
174
|
+
if (row.schemaVersion !== SCHEMA_VERSION || row.operationId !== expectedOperationId
|
|
175
|
+
|| !OPERATION_ID.test(row.operationId)
|
|
176
|
+
|| row.sourceEventId !== `${EVENT_PREFIX}${row.operationId.slice(OPERATION_PREFIX.length)}`
|
|
177
|
+
|| !/^[a-f0-9]{64}$/.test(row.claimRootDigest)
|
|
178
|
+
|| !Number.isSafeInteger(row.revision) || row.revision < 1
|
|
179
|
+
|| !['pending', 'acknowledged'].includes(row.localStatus)
|
|
180
|
+
|| !['not_applicable', 'pending', 'ambiguous', 'acknowledged', 'terminal'].includes(row.networkStatus)
|
|
181
|
+
|| !Array.isArray(row.signals) || row.signals.length > MAX_SIGNALS
|
|
182
|
+
|| row.signals.some((signal) => typeof signal !== 'string' || signal.length > MAX_SIGNAL_CHARS)
|
|
183
|
+
|| typeof row.preparedAt !== 'string') {
|
|
184
|
+
throw new FeedbackOutboxError('invalid feedback outbox record');
|
|
185
|
+
}
|
|
186
|
+
exactString(row.taskId, 'task id');
|
|
187
|
+
const use = copyAppliedUse(row.appliedUse);
|
|
188
|
+
const expectedDigest = digest(`${row.claimRootDigest}\u0000${use.assetId}`);
|
|
189
|
+
if (row.operationId !== `${OPERATION_PREFIX}${expectedDigest}`)
|
|
190
|
+
throw new FeedbackOutboxError('feedback operation identity mismatch');
|
|
191
|
+
const reportable = use.source === 'hub' && (use.outcome === 'success' || use.outcome === 'failed');
|
|
192
|
+
const bound = Boolean(row.report);
|
|
193
|
+
if (row.destinationId !== undefined && !SHA256_ID.test(row.destinationId)) {
|
|
194
|
+
throw new FeedbackOutboxError('feedback destination binding mismatch');
|
|
195
|
+
}
|
|
196
|
+
if (bound && (!reportable || !row.destinationId
|
|
197
|
+
|| use.hubOriginDestinationId !== row.destinationId)) {
|
|
198
|
+
throw new FeedbackOutboxError('feedback report/evidence mismatch');
|
|
199
|
+
}
|
|
200
|
+
if (!reportable && row.destinationId !== undefined) {
|
|
201
|
+
throw new FeedbackOutboxError('feedback destination binding mismatch');
|
|
202
|
+
}
|
|
203
|
+
if (row.report) {
|
|
204
|
+
if (use.source !== 'hub' || (use.outcome !== 'success' && use.outcome !== 'failed')
|
|
205
|
+
|| row.report.assetId !== use.assetId || row.report.outcome !== use.outcome
|
|
206
|
+
|| row.report.taskId !== row.taskId || row.report.traceId !== use.cycleId) {
|
|
207
|
+
throw new FeedbackOutboxError('feedback report/evidence mismatch');
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (reportable && !bound && (row.networkStatus !== 'terminal'
|
|
211
|
+
|| row.terminalReason !== unboundHubReason(use, row.destinationId) || !row.settledAt
|
|
212
|
+
|| row.dispatchStartedAt || row.receiptId || row.reconciliationEvidence)) {
|
|
213
|
+
throw new FeedbackOutboxError('unbound Hub feedback must be terminal before dispatch');
|
|
214
|
+
}
|
|
215
|
+
if (reportable && !bound && row.destinationId
|
|
216
|
+
&& use.hubOriginDestinationId === row.destinationId) {
|
|
217
|
+
throw new FeedbackOutboxError('matching Hub origin lacks feedback report');
|
|
218
|
+
}
|
|
219
|
+
if (reportable && bound && row.networkStatus === 'not_applicable')
|
|
220
|
+
throw new FeedbackOutboxError('Hub feedback cannot be not applicable');
|
|
221
|
+
if (!reportable && row.networkStatus !== (use.source === 'hub' ? 'terminal' : 'not_applicable')) {
|
|
222
|
+
throw new FeedbackOutboxError('invalid non-reportable network state');
|
|
223
|
+
}
|
|
224
|
+
if ((row.networkStatus === 'ambiguous' || row.networkStatus === 'acknowledged'
|
|
225
|
+
|| (row.networkStatus === 'terminal' && bound && !row.reconciliationEvidence))
|
|
226
|
+
&& (!row.dispatchStartedAt || row.localStatus !== 'acknowledged')) {
|
|
227
|
+
throw new FeedbackOutboxError('invalid ambiguous dispatch state');
|
|
228
|
+
}
|
|
229
|
+
if (row.networkStatus === 'terminal' && bound && !row.dispatchStartedAt
|
|
230
|
+
&& (!row.reconciliationEvidence || !row.terminalReason || row.localStatus !== 'acknowledged')) {
|
|
231
|
+
throw new FeedbackOutboxError('invalid terminal reconciliation state');
|
|
232
|
+
}
|
|
233
|
+
if ((row.networkStatus === 'acknowledged' || row.networkStatus === 'terminal') && !row.settledAt) {
|
|
234
|
+
throw new FeedbackOutboxError('settled feedback has no timestamp');
|
|
235
|
+
}
|
|
236
|
+
if (row.payloadDigest !== payloadDigest(row))
|
|
237
|
+
throw new FeedbackOutboxError('feedback payload digest mismatch');
|
|
238
|
+
return row;
|
|
239
|
+
}
|
|
240
|
+
function fsyncDirectory(path) {
|
|
241
|
+
if (process.platform === 'win32')
|
|
242
|
+
return;
|
|
243
|
+
const fd = openSync(path, constants.O_RDONLY);
|
|
244
|
+
try {
|
|
245
|
+
fsyncSync(fd);
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
closeSync(fd);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function writeAtomic(path, record) {
|
|
252
|
+
const dir = dirname(path);
|
|
253
|
+
const temp = join(dir, `.${basename(path)}.${randomUUID()}.tmp`);
|
|
254
|
+
let fd;
|
|
255
|
+
try {
|
|
256
|
+
fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
|
|
257
|
+
writeFileSync(fd, `${JSON.stringify(record)}\n`, 'utf8');
|
|
258
|
+
fsyncSync(fd);
|
|
259
|
+
closeSync(fd);
|
|
260
|
+
fd = undefined;
|
|
261
|
+
renameSync(temp, path);
|
|
262
|
+
fsyncDirectory(dir);
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
if (fd !== undefined)
|
|
266
|
+
closeSync(fd);
|
|
267
|
+
try {
|
|
268
|
+
unlinkSync(temp);
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
// A failed cleanup leaves only an ignored temp file; preserve the write error, if any.
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
export class FeedbackOutbox {
|
|
276
|
+
dir;
|
|
277
|
+
directory;
|
|
278
|
+
reportedUnreadable = new Set();
|
|
279
|
+
constructor(dir) {
|
|
280
|
+
try {
|
|
281
|
+
this.directory = prepareOutboxDirectory(dir);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
throw new FeedbackOutboxError('unsafe feedback outbox directory');
|
|
285
|
+
}
|
|
286
|
+
this.dir = this.directory.path;
|
|
287
|
+
}
|
|
288
|
+
path(operationId) {
|
|
289
|
+
if (!OPERATION_ID.test(operationId))
|
|
290
|
+
throw new FeedbackOutboxError('invalid feedback operation id');
|
|
291
|
+
return join(this.dir, `${operationId.slice(OPERATION_PREFIX.length)}.json`);
|
|
292
|
+
}
|
|
293
|
+
get(operationId) {
|
|
294
|
+
this.directory.assertTrusted();
|
|
295
|
+
const path = this.path(operationId);
|
|
296
|
+
if (!existsSync(path)) {
|
|
297
|
+
this.directory.assertTrusted();
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
const stat = lstatSync(path);
|
|
301
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ROW_BYTES)
|
|
302
|
+
throw new FeedbackOutboxError('unsafe feedback outbox record');
|
|
303
|
+
let parsed;
|
|
304
|
+
try {
|
|
305
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
throw new FeedbackOutboxError('corrupt feedback outbox record');
|
|
309
|
+
}
|
|
310
|
+
const row = frozen(validateRecord(parsed, operationId));
|
|
311
|
+
this.directory.assertTrusted();
|
|
312
|
+
return row;
|
|
313
|
+
}
|
|
314
|
+
save(record) {
|
|
315
|
+
record.payloadDigest = payloadDigest(record);
|
|
316
|
+
writeAtomic(this.path(record.operationId), record);
|
|
317
|
+
return frozen(record);
|
|
318
|
+
}
|
|
319
|
+
/** Persist exact applied-use evidence before any local projection or Hub call. */
|
|
320
|
+
prepare(input) {
|
|
321
|
+
const use = input.verdict.appliedUse;
|
|
322
|
+
if (!use)
|
|
323
|
+
return null;
|
|
324
|
+
if (input.task.id !== input.verdict.taskId
|
|
325
|
+
|| input.task.generation !== input.verdict.generation) {
|
|
326
|
+
throw new FeedbackOutboxError('task/verdict claim mismatch');
|
|
327
|
+
}
|
|
328
|
+
const taskId = exactString(input.task.id, 'task id');
|
|
329
|
+
const appliedUse = copyAppliedUse(use);
|
|
330
|
+
if (appliedUse.outcome === 'success' && input.verdict.status !== 'solidified')
|
|
331
|
+
throw new FeedbackOutboxError('success verdict mismatch');
|
|
332
|
+
if (appliedUse.outcome === 'inert' && input.verdict.status !== 'solidified')
|
|
333
|
+
throw new FeedbackOutboxError('inert verdict mismatch');
|
|
334
|
+
if (appliedUse.outcome === 'failed' && input.verdict.status !== 'failed')
|
|
335
|
+
throw new FeedbackOutboxError('failure verdict mismatch');
|
|
336
|
+
const identity = feedbackIdentity(input.claimRoot, appliedUse.assetId);
|
|
337
|
+
if (input.operationId && input.operationId !== identity.operationId)
|
|
338
|
+
throw new FeedbackOutboxError('feedback operation id mismatch');
|
|
339
|
+
const reportable = appliedUse.source === 'hub'
|
|
340
|
+
&& (appliedUse.outcome === 'success' || appliedUse.outcome === 'failed');
|
|
341
|
+
if (reportable && input.destinationId !== undefined && !SHA256_ID.test(input.destinationId)) {
|
|
342
|
+
throw new FeedbackOutboxError('invalid Hub feedback destination id');
|
|
343
|
+
}
|
|
344
|
+
const report = appliedUse.source === 'hub'
|
|
345
|
+
&& (appliedUse.outcome === 'success' || appliedUse.outcome === 'failed')
|
|
346
|
+
&& input.destinationId
|
|
347
|
+
&& appliedUse.hubOriginDestinationId === input.destinationId
|
|
348
|
+
? { assetId: appliedUse.assetId, outcome: appliedUse.outcome, taskId, traceId: appliedUse.cycleId }
|
|
349
|
+
: undefined;
|
|
350
|
+
const networkStatus = report
|
|
351
|
+
? 'pending' : appliedUse.source === 'hub' ? 'terminal' : 'not_applicable';
|
|
352
|
+
const candidate = {
|
|
353
|
+
schemaVersion: SCHEMA_VERSION, ...identity, taskId,
|
|
354
|
+
signals: safeSignals(input.task.signals), appliedUse,
|
|
355
|
+
...(report ? { report } : {}),
|
|
356
|
+
...(reportable && input.destinationId ? { destinationId: input.destinationId } : {}),
|
|
357
|
+
payloadDigest: '',
|
|
358
|
+
localStatus: 'pending', networkStatus, revision: 1,
|
|
359
|
+
preparedAt: new Date().toISOString(),
|
|
360
|
+
...(networkStatus === 'terminal' ? {
|
|
361
|
+
settledAt: new Date().toISOString(),
|
|
362
|
+
terminalReason: reportable ? unboundHubReason(appliedUse, input.destinationId)
|
|
363
|
+
: `unrepresentable_hub_outcome:${appliedUse.outcome}`,
|
|
364
|
+
} : {}),
|
|
365
|
+
};
|
|
366
|
+
candidate.payloadDigest = payloadDigest(candidate);
|
|
367
|
+
return withOutboxLock(this.directory, () => {
|
|
368
|
+
const existing = this.get(identity.operationId);
|
|
369
|
+
if (existing) {
|
|
370
|
+
if (existing.payloadDigest !== candidate.payloadDigest
|
|
371
|
+
&& !(reportable
|
|
372
|
+
&& digest(JSON.stringify(immutableAppliedUseEvidence(existing)))
|
|
373
|
+
=== digest(JSON.stringify(immutableAppliedUseEvidence(candidate))))) {
|
|
374
|
+
throw new FeedbackOutboxError('feedback operation payload conflict');
|
|
375
|
+
}
|
|
376
|
+
// A committed claim may be recovered after Hub credentials or routing change.
|
|
377
|
+
// Its original destination owns the debt; the current destination cannot inherit it.
|
|
378
|
+
return existing;
|
|
379
|
+
}
|
|
380
|
+
return this.save(candidate);
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
rows() {
|
|
384
|
+
this.directory.assertTrusted();
|
|
385
|
+
const rows = [];
|
|
386
|
+
for (const name of readdirSync(this.dir).filter((item) => ROW_NAME.test(item)).sort()) {
|
|
387
|
+
const operationId = `${OPERATION_PREFIX}${name.slice(0, -5)}`;
|
|
388
|
+
try {
|
|
389
|
+
const row = this.get(operationId);
|
|
390
|
+
if (row)
|
|
391
|
+
rows.push(row);
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
if (!(error instanceof FeedbackOutboxError))
|
|
395
|
+
throw error;
|
|
396
|
+
// An invalid row must remain untouched for repair, but it cannot hold
|
|
397
|
+
// unrelated committed feedback hostage. The digest is safe to log.
|
|
398
|
+
if (!this.reportedUnreadable.has(operationId)) {
|
|
399
|
+
this.reportedUnreadable.add(operationId);
|
|
400
|
+
try {
|
|
401
|
+
process.stderr.write(`[autoexec] feedback_outbox_record_unreadable operation=${operationId}\n`);
|
|
402
|
+
}
|
|
403
|
+
catch { /* A closed diagnostic stream cannot block healthy feedback. */ }
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
this.directory.assertTrusted();
|
|
408
|
+
return rows;
|
|
409
|
+
}
|
|
410
|
+
localPending() {
|
|
411
|
+
return this.rows().filter((row) => row.localStatus === 'pending');
|
|
412
|
+
}
|
|
413
|
+
/** This acknowledgement follows idempotent ingestion under sourceEventId. */
|
|
414
|
+
acknowledgeLocal(operationId) {
|
|
415
|
+
return withOutboxLock(this.directory, () => {
|
|
416
|
+
const row = this.get(operationId);
|
|
417
|
+
if (!row)
|
|
418
|
+
throw new FeedbackOutboxError('feedback operation not found');
|
|
419
|
+
if (row.localStatus === 'acknowledged')
|
|
420
|
+
return row;
|
|
421
|
+
return this.save({ ...row, localStatus: 'acknowledged', localAcknowledgedAt: new Date().toISOString(), revision: row.revision + 1 });
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
/** Never dispatched Hub rows; ambiguous rows are intentionally excluded. */
|
|
425
|
+
pending() {
|
|
426
|
+
return this.rows().filter((row) => row.localStatus === 'acknowledged' && row.networkStatus === 'pending');
|
|
427
|
+
}
|
|
428
|
+
/** Mark ambiguous durably before first send. No replay from ambiguous state. */
|
|
429
|
+
async deliver(operationId, destinationId, sender) {
|
|
430
|
+
const started = withOutboxLock(this.directory, () => {
|
|
431
|
+
const row = this.get(operationId);
|
|
432
|
+
if (!row)
|
|
433
|
+
throw new FeedbackOutboxError('feedback operation not found');
|
|
434
|
+
if (row.localStatus !== 'acknowledged')
|
|
435
|
+
throw new FeedbackOutboxError('local feedback event is pending');
|
|
436
|
+
if (row.networkStatus !== 'pending' || !row.report)
|
|
437
|
+
throw new FeedbackOutboxError('feedback dispatch is not pending');
|
|
438
|
+
if (!SHA256_ID.test(destinationId) || destinationId !== row.destinationId) {
|
|
439
|
+
throw new FeedbackOutboxError('feedback destination mismatch');
|
|
440
|
+
}
|
|
441
|
+
return this.save({ ...row, networkStatus: 'ambiguous', dispatchStartedAt: new Date().toISOString(), revision: row.revision + 1 });
|
|
442
|
+
});
|
|
443
|
+
let result;
|
|
444
|
+
let notDispatched = false;
|
|
445
|
+
try {
|
|
446
|
+
result = await sender(started);
|
|
447
|
+
}
|
|
448
|
+
catch (error) {
|
|
449
|
+
if (error instanceof FeedbackNotDispatchedError)
|
|
450
|
+
notDispatched = true;
|
|
451
|
+
else
|
|
452
|
+
result = { status: 'ambiguous', reason: 'sender_threw' };
|
|
453
|
+
}
|
|
454
|
+
return withOutboxLock(this.directory, () => {
|
|
455
|
+
const current = this.get(operationId);
|
|
456
|
+
if (!current || current.payloadDigest !== started.payloadDigest) {
|
|
457
|
+
throw new FeedbackOutboxError('feedback dispatch owner changed');
|
|
458
|
+
}
|
|
459
|
+
// An operator may have reconciled the ambiguous send while its callback
|
|
460
|
+
// was still pending. Never overwrite that independent evidence.
|
|
461
|
+
if (current.revision !== started.revision || current.networkStatus !== 'ambiguous')
|
|
462
|
+
return current;
|
|
463
|
+
if (notDispatched) {
|
|
464
|
+
// The typed refusal is raised before the adapter begins HTTP. If the process
|
|
465
|
+
// crashed before this transition, the durable ambiguous state would remain.
|
|
466
|
+
const pending = { ...current, networkStatus: 'pending', revision: current.revision + 1 };
|
|
467
|
+
delete pending.dispatchStartedAt;
|
|
468
|
+
delete pending.ambiguousReason;
|
|
469
|
+
return this.save(pending);
|
|
470
|
+
}
|
|
471
|
+
if (result?.status === 'acknowledged') {
|
|
472
|
+
return this.save({ ...current, networkStatus: 'acknowledged', settledAt: new Date().toISOString(),
|
|
473
|
+
...(result.receiptId ? { receiptId: safeReason(result.receiptId, 'receipt id') } : {}), revision: current.revision + 1 });
|
|
474
|
+
}
|
|
475
|
+
if (result?.status === 'terminal' && typeof result.reason === 'string' && result.reason) {
|
|
476
|
+
return this.save({ ...current, networkStatus: 'terminal', settledAt: new Date().toISOString(),
|
|
477
|
+
terminalReason: safeReason(result.reason, 'terminal reason'), revision: current.revision + 1 });
|
|
478
|
+
}
|
|
479
|
+
const reason = result?.status === 'ambiguous' && result.reason ? safeReason(result.reason, 'ambiguous reason') : 'indeterminate_response';
|
|
480
|
+
return this.save({ ...current, ambiguousReason: reason, revision: current.revision + 1 });
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
/** External receipt or operator evidence can settle ambiguity without resending. */
|
|
484
|
+
reconcile(operationId, resolution) {
|
|
485
|
+
return withOutboxLock(this.directory, () => {
|
|
486
|
+
const row = this.get(operationId);
|
|
487
|
+
if (!row)
|
|
488
|
+
throw new FeedbackOutboxError('feedback operation not found');
|
|
489
|
+
if (row.networkStatus === 'pending') {
|
|
490
|
+
if (resolution.status !== 'terminal')
|
|
491
|
+
throw new FeedbackOutboxError('feedback operation is not ambiguous');
|
|
492
|
+
if (row.localStatus !== 'acknowledged')
|
|
493
|
+
throw new FeedbackOutboxError('local feedback event is pending');
|
|
494
|
+
}
|
|
495
|
+
else if (row.networkStatus !== 'ambiguous') {
|
|
496
|
+
throw new FeedbackOutboxError('feedback operation is not ambiguous');
|
|
497
|
+
}
|
|
498
|
+
const evidence = safeReason(resolution.evidence, 'reconciliation evidence');
|
|
499
|
+
if (resolution.status === 'acknowledged') {
|
|
500
|
+
return this.save({ ...row, networkStatus: 'acknowledged', settledAt: new Date().toISOString(),
|
|
501
|
+
reconciliationEvidence: evidence,
|
|
502
|
+
...(resolution.receiptId ? { receiptId: safeReason(resolution.receiptId, 'receipt id') } : {}),
|
|
503
|
+
revision: row.revision + 1 });
|
|
504
|
+
}
|
|
505
|
+
return this.save({ ...row, networkStatus: 'terminal', settledAt: new Date().toISOString(),
|
|
506
|
+
reconciliationEvidence: evidence, terminalReason: safeReason(resolution.reason, 'terminal reason'),
|
|
507
|
+
revision: row.revision + 1 });
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface FeedbackOutboxCliDeps {
|
|
2
|
+
env?: Record<string, string | undefined>;
|
|
3
|
+
stdout?: (text: string) => void;
|
|
4
|
+
stderr?: (text: string) => void;
|
|
5
|
+
}
|
|
6
|
+
/** Read-only visibility plus explicit reconciliation. No sender or replay path is reachable here. */
|
|
7
|
+
export declare function runAutoExecFeedbackCommand(argv: readonly string[], deps?: FeedbackOutboxCliDeps): Promise<number>;
|