@evomap/evolver-cli 2.0.42 → 2.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/autoRecall.d.ts +24 -5
  2. package/dist/autoRecall.js +233 -12
  3. package/dist/autoexec.d.ts +69 -10
  4. package/dist/autoexec.js +847 -137
  5. package/dist/cli.d.ts +1 -1
  6. package/dist/cli.js +71 -26
  7. package/dist/cliContracts.js +29 -7
  8. package/dist/cliEntry.d.ts +3 -0
  9. package/dist/cliEntry.js +63 -0
  10. package/dist/commandCatalog.d.ts +1 -0
  11. package/dist/commandCatalog.js +1 -0
  12. package/dist/contextDelivery.d.ts +12 -0
  13. package/dist/contextDelivery.js +139 -0
  14. package/dist/cycleConsumer.js +9 -1
  15. package/dist/dispatch.js +6 -0
  16. package/dist/feedbackOutbox.d.ts +96 -0
  17. package/dist/feedbackOutbox.js +510 -0
  18. package/dist/feedbackOutboxCli.d.ts +7 -0
  19. package/dist/feedbackOutboxCli.js +208 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.js +286 -69
  22. package/dist/lifecycle.d.ts +18 -0
  23. package/dist/lifecycle.js +130 -3
  24. package/dist/lifecycleBootstrapTransaction.js +1 -6
  25. package/dist/liveStatus.d.ts +27 -0
  26. package/dist/liveStatus.js +197 -0
  27. package/dist/outboxLock.d.ts +7 -0
  28. package/dist/outboxLock.js +141 -0
  29. package/dist/promptRecallHook.d.ts +7 -22
  30. package/dist/promptRecallHook.js +20 -489
  31. package/dist/promptRecallRuntime.d.ts +24 -0
  32. package/dist/promptRecallRuntime.js +678 -0
  33. package/dist/promptRecallShared.d.ts +18 -0
  34. package/dist/promptRecallShared.js +119 -0
  35. package/dist/recall.js +27 -6
  36. package/dist/runtimeTelemetry.d.ts +9 -0
  37. package/dist/runtimeTelemetry.js +16 -0
  38. package/dist/sessionIngest.d.ts +25 -2
  39. package/dist/sessionIngest.js +196 -32
  40. package/dist/setupHooks.js +63 -13
  41. package/dist/setupHooksLifecycle.js +39 -17
  42. package/dist/skill2gep.d.ts +11 -0
  43. package/dist/skill2gep.js +23 -3
  44. package/dist/solo/mode.js +4 -0
  45. package/dist/taskCommitments.d.ts +4 -2
  46. package/dist/taskCommitments.js +208 -114
  47. package/dist/taskOutcomeOutbox.d.ts +83 -0
  48. package/dist/taskOutcomeOutbox.js +553 -0
  49. package/dist/workflowRuntime.js +12 -0
  50. package/package.json +11 -7
@@ -1,25 +1,44 @@
1
1
  import { events, ops, assetstore } from '@evomap/evolver-core';
2
2
  export interface AutoRecallDeps {
3
- /** Read root_events (to find the session's value.inject + the idempotency marker). Default: live root log. */
3
+ /** Native session identity, when it is explicitly supplied by a runtime adapter. */
4
+ sessionId?: string;
5
+ /** Newly connected runtime sources must not opt into legacy lexical reward feedback. */
6
+ contextOnly?: boolean;
7
+ /** A single bounded root-log scan shared by every session in the production ingest tick. */
8
+ contextIndex?: ops.GeneContextObservationIndex;
9
+ /** Isolated event root for direct callers; production derives it from the ingestor. */
10
+ eventsPath?: string;
11
+ /** Read root_events. Default: live root log; observation writes require a matching durable sink path. */
4
12
  readEvents?: (eventsPath?: string) => events.ReportEvent[];
5
13
  /** Resolve injected geneIds to Gene records. Default: live local store. */
6
14
  store?: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>;
7
15
  /** Sink for the emitted `value.recall` events. */
8
16
  ingestor: {
9
- ingest(raw: {
17
+ readonly path?: string;
18
+ /** Versioned terminal operation. Legacy callbacks are refused before dispatch. */
19
+ beginContextObservationV1?(raw: {
10
20
  type: string;
11
21
  human: {
12
22
  title: string;
13
23
  detail?: string;
14
24
  };
15
25
  payload?: Record<string, unknown>;
16
- }): Promise<unknown>;
26
+ }, attempt: ops.ContextObservationAttempt): ops.ContextObservationOperationV1;
27
+ ingest?(raw: {
28
+ type: string;
29
+ human: {
30
+ title: string;
31
+ detail?: string;
32
+ };
33
+ payload?: Record<string, unknown>;
34
+ }, attempt?: ops.ContextObservationAttempt): unknown;
17
35
  };
36
+ observationWait?: ops.ContextObservationWait;
18
37
  }
19
38
  /**
20
39
  * Derive + emit `value.recall` for ONE session transcript. Returns the number of verdicts emitted (0 when there is
21
40
  * no matching inject, no resolvable gene, or the session was already recalled). Idempotent: a session whose
22
- * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: any failure → 0, never
23
- * throws (session ingest must not break on a recall side-effect).
41
+ * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: failures retain the
42
+ * acknowledged prefix count (0 if none); an unconfirmed append is never counted as successful.
24
43
  */
25
44
  export declare function emitSessionRecall(transcriptPath: string, turns: readonly ops.RecallTurn[], deps: AutoRecallDeps): Promise<number>;
@@ -3,23 +3,235 @@
3
3
  // the recallVerifier over the transcript turns and emit one `value.recall` per injected gene (used/unused/unknown).
4
4
  // This feeds the experience loop with OBSERVED data, turning the inert manual `evolver recall` into the loop's
5
5
  // real, unbiased input. PURE-ish + injectable; best-effort + never throws (it must never break session ingest).
6
- import { events, ops, assetstore } from '@evomap/evolver-core';
6
+ import { events, ops, assetstore, util } from '@evomap/evolver-core';
7
+ import { createHash } from 'node:crypto';
7
8
  import { sessionIdFromTranscript, pickInjectEvent, geneIdsOf, geneFromRecallSelection, resolveGene } from './recall.js';
9
+ const builtInObservationSink = events.Ingestor.isBuiltInObservationSink;
10
+ // Prefer the persistence target over callback identity. In-memory embedders share their sink.
11
+ // A busy session is retried by a later tick, never queued behind a possibly hung backend.
12
+ // Bounded waiting retains an independent intent for an unknown append before releasing these leases.
13
+ const injectedPathLeases = new Map();
14
+ const injectedSinkLeases = new WeakMap();
15
+ // Failed SQLite close or lease release still owns a resource. Keep one active/
16
+ // pending resource per canonical log path instead of replacing it on retry.
17
+ // Admission is bounded: never evict an owner to make room for a new allocation.
18
+ const MAX_OWNED_RECALL_RESOURCES = 64;
19
+ const ownedRecallResources = new Map();
20
+ function observationDispatch(ingestor, expectedPath) {
21
+ if (!expectedPath || !builtInObservationSink(ingestor))
22
+ throw new Error('unsupported_unsupervised_context_observation_sink_v1');
23
+ return raw => ops.builtInContextObservationDispatch(ingestor, raw, expectedPath);
24
+ }
25
+ function finishOwnedRecallCleanup(path) {
26
+ const owned = ownedRecallResources.get(path);
27
+ if (!owned)
28
+ return true;
29
+ if (owned.active)
30
+ return false;
31
+ try {
32
+ owned.cleanup();
33
+ ownedRecallResources.delete(path);
34
+ return true;
35
+ }
36
+ catch {
37
+ // Retry only cleanup on the next call. An already acknowledged append must
38
+ // never be replayed to recover a database handle or its tick lease.
39
+ return false;
40
+ }
41
+ }
42
+ function hasOwnedRecallCapacity() {
43
+ if (ownedRecallResources.size < MAX_OWNED_RECALL_RESOURCES)
44
+ return true;
45
+ // Recover abandoned logs without revisiting their business operation. Active
46
+ // owners and failed cleanup stay retained; at most 64 owners are examined.
47
+ for (const path of [...ownedRecallResources.keys()]) {
48
+ finishOwnedRecallCleanup(path);
49
+ if (ownedRecallResources.size < MAX_OWNED_RECALL_RESOURCES)
50
+ return true;
51
+ }
52
+ return false;
53
+ }
8
54
  /**
9
55
  * Derive + emit `value.recall` for ONE session transcript. Returns the number of verdicts emitted (0 when there is
10
56
  * no matching inject, no resolvable gene, or the session was already recalled). Idempotent: a session whose
11
- * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: any failure → 0, never
12
- * throws (session ingest must not break on a recall side-effect).
57
+ * `value.recall` already exists is skipped, so a polling daemon never re-emits. Best-effort: failures retain the
58
+ * acknowledged prefix count (0 if none); an unconfirmed append is never counted as successful.
13
59
  */
14
60
  export async function emitSessionRecall(transcriptPath, turns, deps) {
61
+ // A structural V1 method is only a promise supplied by the adapter: a hung or
62
+ // dishonest same-process callback cannot be stopped and joined by its caller.
63
+ // Product recall therefore admits only the built-in writer, whose owned I/O
64
+ // and durable receipt can be recovered after cancellation or process restart.
65
+ // Check the constructor brand before reading ANY property from the injected
66
+ // value: a Proxy getter itself can dispatch unsupervised work.
67
+ if (!builtInObservationSink(deps.ingestor))
68
+ throw new Error('unsupported_unsupervised_context_observation_sink_v1');
69
+ // A pathless injected sink cannot bind its terminal receipt to durable history.
70
+ // Its in-memory intent disappears on restart, so the same observation could be
71
+ // dispatched again even after a successful append to an unknown destination.
72
+ // Reject before reading or reserving; a caller-supplied readEvents callback is
73
+ // not proof that the sink writes to that reader's source.
74
+ let sinkPath;
75
+ try {
76
+ sinkPath = deps.ingestor.path;
77
+ }
78
+ catch {
79
+ throw new Error('unsupported_unbound_context_observation_sink_v1');
80
+ }
81
+ if (typeof sinkPath !== 'string' || !sinkPath.trim())
82
+ throw new Error('unsupported_unbound_context_observation_sink_v1');
83
+ if (deps.contextIndex && !deps.contextIndex.observationReady)
84
+ return 0;
85
+ const session = deps.sessionId ?? sessionIdFromTranscript(transcriptPath);
86
+ if (!session)
87
+ return 0;
88
+ let path;
15
89
  try {
16
- if (turns.length === 0)
90
+ const declared = [deps.contextIndex?.eventsPath, deps.eventsPath, sinkPath]
91
+ .filter((value) => value !== undefined).map(util.canonicalEventPath);
92
+ path = declared[0];
93
+ // A receipt checked/indexed in one log cannot be acknowledged by writing to
94
+ // another. Validate every declared identity before any read, allocation or
95
+ // retained cleanup; rejecting a bad composition must not replace its owner.
96
+ if (declared.some(value => value !== path))
97
+ return 0;
98
+ }
99
+ catch {
100
+ return 0;
101
+ }
102
+ if (!path)
103
+ return 0;
104
+ if (path && !finishOwnedRecallCleanup(path))
105
+ return 0;
106
+ const sinkLeases = injectedSinkLeases.get(deps.ingestor) ?? new Set();
107
+ const pathLeases = path ? (injectedPathLeases.get(path) ?? new Set()) : undefined;
108
+ // Hold BOTH identities. Explicit/implicit paths and wrappers of the same sink must
109
+ // overlap, while the public Ingestor.path unifies distinct writers of the same log.
110
+ if (sinkLeases.has(session) || pathLeases?.has(session))
111
+ return 0;
112
+ let readerLease;
113
+ if (path && deps.readEvents && !deps.contextIndex) {
114
+ if (!hasOwnedRecallCapacity())
115
+ return 0;
116
+ const lockPath = `${path}.context-index.sqlite.lock`;
117
+ let owner;
118
+ try {
119
+ owner = util.acquireLock(lockPath, { maxTries: 1, waitMs: 0 });
120
+ }
121
+ catch {
17
122
  return 0;
18
- const sessionId = sessionIdFromTranscript(transcriptPath);
123
+ }
124
+ // Trusted readers must take a fresh snapshot of this declared path AFTER
125
+ // acquiring the same lease used by the durable production index.
126
+ readerLease = { active: true, cleanup: () => {
127
+ const result = util.releaseLock(lockPath, owner);
128
+ if (!result.released)
129
+ throw new util.LockReleaseError(result.reason);
130
+ } };
131
+ ownedRecallResources.set(path, readerLease);
132
+ }
133
+ injectedSinkLeases.set(deps.ingestor, sinkLeases);
134
+ sinkLeases.add(session);
135
+ if (path && pathLeases) {
136
+ injectedPathLeases.set(path, pathLeases);
137
+ pathLeases.add(session);
138
+ }
139
+ try {
140
+ return await emitSessionRecallUnderLease(transcriptPath, turns, { ...deps, eventsPath: path });
141
+ }
142
+ finally {
143
+ sinkLeases.delete(session);
144
+ if (sinkLeases.size === 0)
145
+ injectedSinkLeases.delete(deps.ingestor);
146
+ pathLeases?.delete(session);
147
+ if (path && pathLeases?.size === 0)
148
+ injectedPathLeases.delete(path);
149
+ if (path && readerLease) {
150
+ readerLease.active = false;
151
+ finishOwnedRecallCleanup(path);
152
+ }
153
+ }
154
+ }
155
+ async function emitSessionRecallUnderLease(transcriptPath, turns, deps) {
156
+ let ownedPath;
157
+ let ownedIndex;
158
+ let emitted = 0;
159
+ let wait;
160
+ // The default sink budget starts after durable reservation. An explicit absolute
161
+ // caller deadline still includes preparation and is never extended.
162
+ const waiting = () => wait ??= { ...deps.observationWait };
163
+ const sharedWait = {};
164
+ const intents = () => ops.durableObservationIntents(deps.eventsPath);
165
+ const dispatch = observationDispatch(deps.ingestor, deps.eventsPath);
166
+ const stillBound = () => {
167
+ try {
168
+ const current = deps.ingestor.path;
169
+ return typeof current === 'string' && util.canonicalEventPath(current) === deps.eventsPath;
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ };
175
+ try {
176
+ const sessionId = deps.sessionId ?? sessionIdFromTranscript(transcriptPath);
19
177
  if (!sessionId)
20
178
  return 0; // no stable session key → cannot dedup safely → skip (never risk re-emitting)
179
+ let index = deps.contextIndex;
180
+ if (!index && !deps.readEvents && deps.eventsPath) {
181
+ if (!hasOwnedRecallCapacity())
182
+ return 0;
183
+ ownedPath = deps.eventsPath;
184
+ const created = new ops.GeneContextObservationIndex(ownedPath);
185
+ index = created;
186
+ ownedIndex = { cleanup: () => created.close(), active: true };
187
+ ownedRecallResources.set(ownedPath, ownedIndex);
188
+ index.beginTick();
189
+ }
190
+ if (index) {
191
+ const observation = await index.observeSession(sessionId, deps.ingestor, 64, waiting());
192
+ emitted += observation.emitted;
193
+ if (observation.hasDelivery || !observation.historyComplete || deps.contextOnly)
194
+ return observation.emitted;
195
+ }
21
196
  const read = deps.readEvents ?? events.readEvents;
22
- const evts = read();
197
+ const evts = read(deps.eventsPath);
198
+ // A static reader may rebind an injected sink. Refuse before reserving a
199
+ // durable intent; a factory that throws after reservation is ambiguous.
200
+ if (!stillBound())
201
+ return emitted;
202
+ const deliveries = evts.filter((event) => event.type === ops.GENE_CONTEXT_DELIVERY_EVENT
203
+ && event.payload?.['sessionId'] === sessionId && event.payload['transport'] === 'stdout_written'
204
+ && ops.readGeneContextDeliveryReceipt(event.payload['receipt']));
205
+ if (deliveries.length > 0) {
206
+ const observed = new Set(evts.filter((event) => event.type === ops.GENE_CONTEXT_OBSERVATION_EVENT
207
+ && event.payload?.['sessionId'] === sessionId).map((event) => `${String(event.payload['deliverySeq'])}:${String(event.payload['digest'])}:${String(event.payload['deliveryIdentity'] ?? '')}`));
208
+ for (const delivery of deliveries) {
209
+ if (!stillBound())
210
+ return emitted;
211
+ const receipt = ops.readGeneContextDeliveryReceipt(delivery.payload['receipt']);
212
+ const identity = ops.geneContextDeliveryIdentity(delivery, sessionId, receipt.digest);
213
+ const legacyKey = `${delivery.seq}:${receipt.digest}:`;
214
+ const key = `${legacyKey}${identity}`;
215
+ if (observed.has(key) || observed.has(legacyKey))
216
+ continue;
217
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
218
+ const session = hash(sessionId);
219
+ const result = await ops.settleContextObservation(intents(), JSON.stringify([deps.eventsPath ?? null, session, identity]), dispatch({ type: ops.GENE_CONTEXT_OBSERVATION_EVENT,
220
+ human: { title: 'Context delivery attribution unavailable' },
221
+ payload: { sessionId, deliverySeq: delivery.seq, digest: receipt.digest, deliveryIdentity: identity,
222
+ observedUse: 'unknown', reason: 'no_trusted_turn_boundary',
223
+ geneCount: receipt.geneAssetIds.length, caseCount: receipt.capsuleAssetIds.length,
224
+ receiptTruncated: receipt.truncated } }), waiting(), sharedWait);
225
+ if (result === 'pending')
226
+ continue;
227
+ observed.add(key);
228
+ if (result === 'committed')
229
+ emitted++;
230
+ }
231
+ return emitted;
232
+ }
233
+ if (deps.contextOnly || turns.length === 0)
234
+ return 0;
23
235
  const inject = pickInjectEvent(evts, sessionId);
24
236
  // Only auto-recall when the inject is PROVABLY this session's (#205 stamped match). Without a stamped match we
25
237
  // would be guessing which inject produced this transcript — too weak a basis to emit observed verdicts.
@@ -58,27 +270,36 @@ export async function emitSessionRecall(transcriptPath, turns, deps) {
58
270
  if (genes.length === 0)
59
271
  return 0;
60
272
  const results = ops.verifyInjectedGenes(genes, turns);
61
- let emitted = 0;
62
273
  for (const r of results) {
274
+ if (!stillBound())
275
+ return emitted;
63
276
  if (usedGenes.has(r.geneId))
64
277
  continue; // terminal: already used
65
278
  if (seenGenes.has(r.geneId) && r.recalled !== 'used')
66
279
  continue; // provisional already recorded; only an upgrade to `used` is new
67
280
  const payload = { geneId: r.geneId, recalled: r.recalled, score: r.score, sessionId };
68
281
  try {
69
- await deps.ingestor.ingest({
282
+ const result = await ops.settleContextObservation(intents(), JSON.stringify([deps.eventsPath ?? null, sessionId,
283
+ inject.eventId, inject.seq, inject.ts, r.geneId, r.recalled]), dispatch({
70
284
  type: ops.VALUE_RECALL_EVENT,
71
285
  // 展示标题遵守既有 80 字符上限;payload 中的完整版本身份不能截断。
72
286
  human: { title: `recall ${r.recalled}: ${r.geneId}`.slice(0, 80), detail: `session ${sessionId}` },
73
287
  payload: payload,
74
- });
75
- emitted += 1;
288
+ }), waiting(), sharedWait);
289
+ if (result === 'committed')
290
+ emitted += 1;
76
291
  }
77
292
  catch { /* per-gene best-effort; keep going */ }
78
293
  }
79
294
  return emitted;
80
295
  }
81
- catch {
82
- return 0;
296
+ catch (error) {
297
+ return error instanceof ops.ContextObservationFailure ? Math.max(emitted, error.emitted) : emitted;
298
+ }
299
+ finally {
300
+ if (ownedIndex && ownedPath) {
301
+ ownedIndex.active = false;
302
+ finishOwnedRecallCleanup(ownedPath);
303
+ }
83
304
  }
84
305
  }
@@ -10,6 +10,8 @@ import { type AutoDistillAntiGeneMode, type AutoDistillAntiGeneResult } from './
10
10
  import { type AutoDistillTranscriptMode, type TranscriptDistillTickResult } from './autoDistillTranscript.js';
11
11
  import { type SessionIngestTickResult } from './sessionIngest.js';
12
12
  import { AtpAutoBuyer, type AtpAutoBuyerClient, type AtpAutoBuyerRequest } from './atpAutoBuyer.js';
13
+ import { FeedbackOutbox, type FeedbackOutboxRecord, type FeedbackSender } from './feedbackOutbox.js';
14
+ import { TaskOutcomeOutbox, type PrepareTaskOutcomeInput, type TaskOutcomeSender } from './taskOutcomeOutbox.js';
13
15
  import { type ConfiguredSelectionGuard } from './selectionPolicyConfig.js';
14
16
  export { readAutoExecConfig, type AutoExecConfig } from './autoexecConfig.js';
15
17
  export { semanticIdfEnabled } from './semanticIdfConfig.js';
@@ -32,6 +34,13 @@ export interface AutoExecDirs {
32
34
  /** Create the queue layout under <home>/autoexec/{tasks,inflight,done,refused}. */
33
35
  export declare function ensureAutoExecDirs(base: string): AutoExecDirs;
34
36
  export declare function summarizeSandboxedValidation(result: verify.SandboxedValidationResult): string | null;
37
+ interface AutoExecPassOptions {
38
+ executePendingTasks?: boolean;
39
+ captureFeedbackDestination?: (task: exec.AutoExecTask) => string | null | undefined;
40
+ taskOutcomeEnabled?: boolean;
41
+ prepareFeedback?: (claimRoot: string, task: exec.AutoExecTask, verdict: exec.AutoExecVerdict, executionDestinationId?: string | null, taskOutcomeEnabled?: boolean) => void;
42
+ afterCommit?: (task: exec.AutoExecTask, verdict: exec.AutoExecVerdict) => void;
43
+ }
35
44
  /**
36
45
  * Whether a claim for this queue id is already checked out to the exec pass. The name has
37
46
  * to match on both ends — `--hub-1` is a prefix of `--hub-10`, and treating one task as
@@ -44,9 +53,7 @@ export declare function hasInflightClaim(dirs: AutoExecDirs, queueTaskId: string
44
53
  * after a crash, started and legacy claims are ambiguous and fail closed instead of repeating side effects.
45
54
  * Unreadable or incomplete claimed tasks stay pending because the drop-directory has no atomic publish marker.
46
55
  */
47
- export declare function autoExecPass(dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>, options?: {
48
- executePendingTasks?: boolean;
49
- }): Promise<exec.AutoExecVerdict[]>;
56
+ export declare function autoExecPass(dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>, options?: AutoExecPassOptions): Promise<exec.AutoExecVerdict[]>;
50
57
  /**
51
58
  * Which repo Hub tasks land in. A Hub task does not say which one it belongs to, so a
52
59
  * multi-repo allowlist cannot be spread across — one receiver serves one repo. Silently
@@ -57,7 +64,7 @@ export declare function taskReceiverRepo(env: NodeJS.ProcessEnv, allowedRoots: r
57
64
  /** Runners cleared to take work off the queue, rather than only keeping the daemon alive. */
58
65
  export declare function canExecuteQueue(runner: exec.RunnerName): boolean;
59
66
  /** Keep unsupported built-in runners away from the execution queue without stopping the resident daemon. */
60
- export declare function runnerBoundAutoExecPass(runner: exec.RunnerName, dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>): () => Promise<exec.AutoExecVerdict[]>;
67
+ export declare function runnerBoundAutoExecPass(runner: exec.RunnerName, dirs: AutoExecDirs, runOne: (task: exec.AutoExecTask) => Promise<exec.AutoExecVerdict>, options?: Omit<AutoExecPassOptions, 'executePendingTasks'>): () => Promise<exec.AutoExecVerdict[]>;
61
68
  /**
62
69
  * Build the reuse-before-solve seam (#110) — THE real injection point. This is the public-repo composition
63
70
  * layer that owns BOTH core's autoexec kernel and the adapter's hub capability, so it is where the adapter's
@@ -102,13 +109,23 @@ export declare function atpCapabilityGapRequest(signals: readonly string[]): Atp
102
109
  export declare function scheduleAtpAutoBuyForVerifiedMiss(miss: VerifiedHubSearchMiss, buyer: Pick<AtpAutoBuyer, 'consider'>): void;
103
110
  /** Resolve an autonomous buyer only after an explicit env/ack consent check; the buyer checks consent again. */
104
111
  export declare function resolveAtpAutoBuyer(env?: NodeJS.ProcessEnv, createClient?: (resolvedEnv: NodeJS.ProcessEnv) => AtpAutoBuyerClient): AtpAutoBuyer | undefined;
105
- export declare function makeHubReuseSeam(cap: hubNs.HubCapability, cache: ReuseCache, ingestor?: events.Ingestor, onAssetReused?: (assetId: string) => void, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, audit?: HubReuseAuditOptions): exec.HubReuseSeam;
112
+ export declare function makeHubReuseSeam(cap: hubNs.HubCapability, cache: ReuseCache, _ingestor?: events.Ingestor, onAssetReused?: (assetId: string) => void, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, audit?: HubReuseAuditOptions): exec.HubReuseSeam;
106
113
  /**
107
114
  * Free search-only seam used by ATP auto-buy when reuse injection is disabled. It proves a capability miss with
108
115
  * the same dual-leg search and score threshold as reuse, but never performs the paid fetch or contributes a Hub
109
116
  * candidate.
110
117
  */
111
118
  export declare function makeHubSearchMissProbe(cap: hubNs.HubCapability, cache: ReuseCache, onVerifiedSearchMiss: VerifiedHubSearchMissHandler, enabled: () => boolean, env?: NodeJS.ProcessEnv, assetLog?: AssetCallLogger): exec.HubReuseSeam;
119
+ /** Project only a committed, exact selected/executed use, never a fetched candidate. */
120
+ export declare function committedFeedbackEvent(row: Readonly<FeedbackOutboxRecord>): events.RawEvent;
121
+ /** Local projection is owed before network delivery; ambiguous sends are never replayed automatically. */
122
+ export declare function flushAutoExecFeedback(outbox: FeedbackOutbox, ingestor: events.Ingestor, sender?: FeedbackSender, destinationId?: string): Promise<{
123
+ projected: number;
124
+ delivered: number;
125
+ ambiguous: number;
126
+ }>;
127
+ /** A slow durable outbox drain must neither block Hub-task completion nor overlap the next beat. */
128
+ export declare function makeDeferredAutoExecFeedbackDrain(drain: () => Promise<void>, onFailure: () => void): () => void;
112
129
  /** Build the same event for byte-budget admission and durable emission. */
113
130
  export declare function injectEvent(info: hooks.InjectInfo): events.RawEvent;
114
131
  export declare function emitInject(ingestor: events.Ingestor, info: hooks.InjectInfo): Promise<void>;
@@ -133,9 +150,16 @@ export type OutcomeReportingHub = hubNs.HubCapability & {
133
150
  /** The composed hub wiring: the reuse seam plus the matching outcome reporter that closes the loop. */
134
151
  export interface HubLink {
135
152
  seam: exec.HubReuseSeam;
153
+ /** Destination captured when the public reporting capability was bound to an exact credential. */
154
+ feedbackDestinationId?: string;
136
155
  /** Report a finished task's outcome (with the used-asset attribution claim) to the hub. Never throws. */
137
156
  reportOutcome: (task: exec.AutoExecTask, verdict: exec.AutoExecVerdict) => Promise<void>;
157
+ /** Strict receipt-bearing delivery of a committed, exact applied-use fact. */
158
+ sendAppliedUse?: FeedbackSender;
159
+ /** Durable task-wide memory attribution; separate from exact per-asset reuse feedback. */
160
+ sendTaskOutcome?: TaskOutcomeSender;
138
161
  }
162
+ export declare function makeAppliedUseFeedbackSender(cap: OutcomeReportingHub, expectedDestinationId: string, reportEnabled?: boolean): FeedbackSender;
139
163
  export interface HubQuestionLink {
140
164
  /** Submit optional proactive questions for a finished task. Never throws. */
141
165
  submitForTask: (task: exec.AutoExecTask) => Promise<HubQuestionSubmitResult>;
@@ -221,12 +245,45 @@ export declare function scheduleAutoExecHubSideEffects(task: exec.AutoExecTask,
221
245
  outcome?: HubLink;
222
246
  }): void;
223
247
  /**
224
- * Compose the reuse seam and the outcome reporter. Reuse HITs still emit value-ledger observability, but the
225
- * Hub outcome `used_asset_ids` claim comes only from the finished verdict's selected/executed asset. A fetched
226
- * candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
227
- * Reporting never throws and never blocks the verdict.
248
+ * Compose the reuse seam and the outcome reporters. A fetched candidate is neutral.
249
+ * Exact applied-use delivery is owned by sendAppliedUse and the durable outbox;
250
+ * the legacy task-wide outcome path cannot send a duplicate reuse-result claim.
228
251
  */
229
- export declare function makeHubLink(cap: OutcomeReportingHub, ingestor?: events.Ingestor, reportEnabled?: boolean, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, assetLog?: AssetCallLogger, env?: NodeJS.ProcessEnv): HubLink;
252
+ export declare function makeHubLink(cap: OutcomeReportingHub, ingestor?: events.Ingestor, reportEnabled?: boolean, onVerifiedSearchMiss?: VerifiedHubSearchMissHandler, assetLog?: AssetCallLogger, env?: NodeJS.ProcessEnv, appliedUseSender?: FeedbackSender, reportingCap?: OutcomeReportingHub, reportingDestinationId?: string): HubLink;
253
+ /** Opaque nonsecret binding to the effective Hub principal and route, never a credential. */
254
+ export declare function feedbackDestinationIdentity(mode: 'public' | 'private', endpoint: string, principal: string, namespace?: string): string;
255
+ /** The proxy attests the final identity it also checks on the feedback POST. */
256
+ export declare function privateFeedbackDestinationIdFromStatus(value: unknown): string | undefined;
257
+ /** A private proxy must attest its effective Hub destination, not merely its local node. */
258
+ export declare function resolveFeedbackDestinationId(env: NodeJS.ProcessEnv): Promise<string | undefined>;
259
+ export declare function makeAutoExecFeedbackBinding(candidate: HubLink | undefined, mode: 'public' | 'private' | undefined, probe: () => Promise<string | undefined>): {
260
+ refresh: () => Promise<{
261
+ link: HubLink;
262
+ destinationId: string;
263
+ } | undefined>;
264
+ bound: () => {
265
+ link: HubLink;
266
+ destinationId: string;
267
+ } | undefined;
268
+ current: () => {
269
+ link: HubLink;
270
+ destinationId: string;
271
+ } | undefined;
272
+ };
273
+ /** One task may only create Hub debt if its execution and completion saw the same binding. */
274
+ export declare function confirmedTaskFeedbackDestination(started: {
275
+ link: HubLink;
276
+ destinationId: string;
277
+ } | undefined, completed: {
278
+ link: HubLink;
279
+ destinationId: string;
280
+ } | undefined): string | undefined;
281
+ /** A recovered claim has no verified execution-time Hub binding; never adopt today's endpoint. */
282
+ export declare function committedTaskFeedbackDestination(taskDestination: string | null | undefined, current: {
283
+ destinationId: string;
284
+ } | undefined): string | undefined;
285
+ /** A committed claim can finish recovering an existing row even while its Hub is unavailable. */
286
+ export declare function prepareCommittedTaskOutcomeFeedback(outbox: TaskOutcomeOutbox, claimRoot: string, task: PrepareTaskOutcomeInput['task'], verdict: PrepareTaskOutcomeInput['verdict'], destinationId?: string): void;
230
287
  /**
231
288
  * Resolve public/private reuse wiring. Reuse remains default-off. When a public ATP miss handler is supplied,
232
289
  * a consent-gated free search-only seam may still be composed so auto-buy can prove a miss independently of
@@ -261,6 +318,8 @@ export interface DistillProducerOptions {
261
318
  /** The daemon's bus Ingestor — REQUIRED, so the producer's `material.batch_ready` reaches the same ObserverBus
262
319
  * the distillObserver is registered on. */
263
320
  ingestor: events.Ingestor;
321
+ /** Separate built-in context writer bound to ingestor's exact event target. */
322
+ contextIngestor?: events.Ingestor;
264
323
  store?: assetstore.AssetStoreProvider;
265
324
  review?: assetstore.ReviewLedger;
266
325
  materialStore?: materialNs.MaterialStore;