piroboros 0.0.0-stage → 0.2.0
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/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/NOTICE +39 -0
- package/README.md +140 -2
- package/agents/astrelia.md +31 -0
- package/agents/avaritia.md +31 -0
- package/agents/elaria.md +31 -0
- package/agents/nytheria.md +32 -0
- package/agents/raskreia.md +32 -0
- package/agents/samaela.md +40 -0
- package/agents/vaelia.md +35 -0
- package/agents/vesperia.md +45 -0
- package/bin/piroboros.mjs +17 -0
- package/dist/auth.js +105 -0
- package/dist/base.js +19 -0
- package/dist/chat/budget.js +87 -0
- package/dist/chat/compactloop.js +63 -0
- package/dist/chat/compactor.js +530 -0
- package/dist/chat/extension.js +36 -0
- package/dist/chat/hook.js +40 -0
- package/dist/chat/log.js +317 -0
- package/dist/chat/outbound.js +114 -0
- package/dist/chat/plan.js +64 -0
- package/dist/chat/prompt.js +115 -0
- package/dist/chat/status.js +37 -0
- package/dist/chat/stuck.js +83 -0
- package/dist/chat/tools.js +163 -0
- package/dist/chat/tree.js +73 -0
- package/dist/chat/turn.js +305 -0
- package/dist/chat/view.js +163 -0
- package/dist/conclave/agents.js +113 -0
- package/dist/conclave/pipeline.js +715 -0
- package/dist/conclave/report.js +43 -0
- package/dist/config.js +614 -0
- package/dist/durable.js +177 -0
- package/dist/guard.js +346 -0
- package/dist/lock.js +56 -0
- package/dist/main.js +348 -0
- package/dist/memory/akashic/api.js +121 -0
- package/dist/memory/akashic/confusables.js +41 -0
- package/dist/memory/akashic/scanner.js +67 -0
- package/dist/memory/akashic/snapshot.js +31 -0
- package/dist/memory/akashic/store.js +1254 -0
- package/dist/memory/akashic/tools.js +168 -0
- package/dist/memory/akashic/vault.js +984 -0
- package/dist/memory/host.js +124 -0
- package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
- package/dist/memory/mnemosia/adapters/contract.js +219 -0
- package/dist/memory/mnemosia/agents.js +387 -0
- package/dist/memory/mnemosia/brief.js +890 -0
- package/dist/memory/mnemosia/claims.js +609 -0
- package/dist/memory/mnemosia/conflicts.js +769 -0
- package/dist/memory/mnemosia/escalation.js +257 -0
- package/dist/memory/mnemosia/feedback.js +108 -0
- package/dist/memory/mnemosia/filters.js +248 -0
- package/dist/memory/mnemosia/intent.js +221 -0
- package/dist/memory/mnemosia/open.js +34 -0
- package/dist/memory/mnemosia/orchestrator.js +926 -0
- package/dist/memory/mnemosia/plan.js +266 -0
- package/dist/memory/mnemosia/policy.js +426 -0
- package/dist/memory/mnemosia/progressive.js +550 -0
- package/dist/memory/mnemosia/provenance.js +458 -0
- package/dist/memory/mnemosia/qualifiers.js +428 -0
- package/dist/memory/mnemosia/rank.js +525 -0
- package/dist/memory/mnemosia/relations.js +156 -0
- package/dist/memory/mnemosia/requirements.js +138 -0
- package/dist/memory/mnemosia/rerank.js +253 -0
- package/dist/memory/mnemosia/retention.js +174 -0
- package/dist/memory/mnemosia/rollback.js +337 -0
- package/dist/memory/mnemosia/select.js +607 -0
- package/dist/memory/mnemosia/similarity.js +164 -0
- package/dist/memory/mnemosia/situation.js +251 -0
- package/dist/memory/mnemosia/task.js +418 -0
- package/dist/memory/mnemosia/temporal.js +136 -0
- package/dist/memory/mnemosia/tokens.js +66 -0
- package/dist/memory/mnemosia/tools.js +160 -0
- package/dist/memory/mnemosia/trace.js +306 -0
- package/dist/memory/mnemosia/types.js +298 -0
- package/dist/models.js +360 -0
- package/dist/paths.js +103 -0
- package/dist/redact.js +79 -0
- package/dist/runtime.js +378 -0
- package/dist/search-format.js +102 -0
- package/dist/search.js +351 -0
- package/dist/setup.js +366 -0
- package/dist/shell.js +110 -0
- package/dist/skills.js +311 -0
- package/dist/telemetry.js +84 -0
- package/dist/tui/app.js +1011 -0
- package/dist/tui/commands.js +121 -0
- package/dist/tui/keys.js +83 -0
- package/dist/tui/pane.js +387 -0
- package/dist/tui/panel.js +60 -0
- package/dist/tui/picker.js +25 -0
- package/dist/tui/sanitize.js +59 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/setup.js +256 -0
- package/dist/tui/theme.js +26 -0
- package/dist/tui/thinking/parse.js +1094 -0
- package/dist/tui/thinking/select.js +86 -0
- package/dist/tui/thinking/state.js +137 -0
- package/dist/tui/thinking/types.js +3 -0
- package/dist/tui/thinking/view.js +74 -0
- package/dist/tui/viewport.js +208 -0
- package/dist/undo.js +258 -0
- package/dist/web.js +933 -0
- package/docs/conclave.md +21 -0
- package/docs/configuration.md +48 -0
- package/docs/development.md +25 -0
- package/docs/interface.md +33 -0
- package/docs/memory.md +11 -0
- package/docs/privacy.md +13 -0
- package/docs/tools.md +20 -0
- package/docs/web.md +38 -0
- package/models.json.example +34 -0
- package/package.json +76 -4
- package/settings.json.example +29 -0
- package/skills/conclave/SKILL.md +76 -0
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
// Ported from mnemosia/orchestrator.ts @ f0a8ad4 (MIT; see NOTICE)
|
|
2
|
+
/**
|
|
3
|
+
* The retrieval state machine (spec §7, design §6 and §13, build-order step 15).
|
|
4
|
+
*
|
|
5
|
+
* Chunks A–C built eleven modules that each do one thing correctly. This is the one that owns the
|
|
6
|
+
* *order* between them, and therefore the one that owns every property that is not local to a single
|
|
7
|
+
* module: the transitions, the six early exits, the audit trail, the deadlines, the circuit breaker,
|
|
8
|
+
* and graceful degradation.
|
|
9
|
+
*
|
|
10
|
+
* ```
|
|
11
|
+
* RECEIVE_REQUEST → ANALYZE_TASK → AUTHORIZE_SCOPE → PLAN_RETRIEVAL → EXECUTE_SOURCE_QUERIES
|
|
12
|
+
* → NORMALIZE_ARTIFACTS → EXTRACT_OR_RESOLVE_CLAIMS → DEDUPLICATE → APPLY_HARD_FILTERS
|
|
13
|
+
* → SCORE_CANDIDATES → DETECT_CONFLICTS → RESOLVE_OR_ESCALATE → SELECT_CONTEXT_SET
|
|
14
|
+
* → REQUEST_COMPRESSION → ASSEMBLE_BRIEFING → VALIDATE_BRIEFING → DELIVER → COLLECT_FEEDBACK
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* **One failing source never fails the run.** Design §20 and §23 both require it, and it is the
|
|
18
|
+
* property most easily claimed and least often true. Here it is structural: every adapter call is
|
|
19
|
+
* wrapped, every failure becomes a named `RetrievalGap` with the source's own id and a standard error
|
|
20
|
+
* code, and the pipeline continues with whatever came back. The run only ends as
|
|
21
|
+
* `RETRIEVAL_UNAVAILABLE` when *every* selected source failed — i.e. when there is genuinely nothing
|
|
22
|
+
* to brief from, as opposed to less than expected.
|
|
23
|
+
*
|
|
24
|
+
* **The term ladder is the recall half of spec §9's retry policy.** `plan.ts:42-66` explains why a
|
|
25
|
+
* query carries at most three terms — FTS5 ANDs them, so a fourth term the corpus does not contain
|
|
26
|
+
* zeroes the result set — and explicitly leaves the recall-preserving answer to this module. An empty
|
|
27
|
+
* lexical result is retried with a shorter term prefix, down to one term, and every rung is recorded.
|
|
28
|
+
* The ladder never widens to an unbounded recency scan: `plan.ts`'s `no_retrievable_signal` rule
|
|
29
|
+
* exists precisely to stop that, and re-introducing it here through the back door would retrieve
|
|
30
|
+
* volume in exactly the case where relevance already failed.
|
|
31
|
+
*
|
|
32
|
+
* **Nothing here writes.** The orchestrator's only side effects are the JSONL trace under
|
|
33
|
+
* the caller-supplied trace root and, on `submitFeedback`, one line of `feedback.jsonl`. Both are
|
|
34
|
+
* derived, rebuildable data (design §3). `writes.ts` produces recommendations; no code path in this
|
|
35
|
+
* file reaches `mutateMemory`, and the dependency it takes cannot express one.
|
|
36
|
+
*/
|
|
37
|
+
import { isStandardAdapterError } from "./adapters/contract.js";
|
|
38
|
+
import { assembleBriefing, renderMarkdown, validateBriefing } from "./brief.js";
|
|
39
|
+
import { dedupeClaims, extractClaims } from "./claims.js";
|
|
40
|
+
import { applyConflictPresentation, detectConflicts } from "./conflicts.js";
|
|
41
|
+
import { applyHardFilters, scanArtifacts } from "./filters.js";
|
|
42
|
+
import { planRetrieval } from "./plan.js";
|
|
43
|
+
import { effectiveAddendumReserve, profileFor, resolveAgent } from "./agents.js";
|
|
44
|
+
import { applyEscalationOutcomes, routeEscalations } from "./escalation.js";
|
|
45
|
+
import { FEEDBACK_SCHEMA_VERSION, validateFeedback } from "./feedback.js";
|
|
46
|
+
import { MODE_CONFIGS, resolvePolicy, withAgentSelection } from "./policy.js";
|
|
47
|
+
import { BRIEFING_SCAFFOLDING_TOKENS, minimumConformingBudgetForSeat } from "./select.js";
|
|
48
|
+
import { buildProvenanceGraph } from "./provenance.js";
|
|
49
|
+
import { QUALIFIER_RANKING } from "./qualifiers.js";
|
|
50
|
+
import { rankCandidates } from "./rank.js";
|
|
51
|
+
import { applyReranking } from "./rerank.js";
|
|
52
|
+
import { appliesAgentSelection, resolvePolicyAt } from "./rollback.js";
|
|
53
|
+
import { selectContext } from "./select.js";
|
|
54
|
+
import { analyzeTask, authorizeScope } from "./task.js";
|
|
55
|
+
import { analyseSituation, validateSituationContext } from "./situation.js";
|
|
56
|
+
import { inferIntentHypotheses, leadingQueryTerms } from "./intent.js";
|
|
57
|
+
import { deriveKnowledgeRequirements } from "./requirements.js";
|
|
58
|
+
import { openTrace, readTrace, buildAgentLineage } from "./trace.js";
|
|
59
|
+
import { runProgressiveRetrieval } from "./progressive.js";
|
|
60
|
+
import { EARLY_EXITS, SCHEMA_VERSION } from "./types.js";
|
|
61
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
62
|
+
import { basename, dirname, join } from "node:path";
|
|
63
|
+
import { redactSensitive } from "../../redact.js";
|
|
64
|
+
/** Design §13's threshold, named so a change is a diff to a constant rather than to a condition. */
|
|
65
|
+
export const CIRCUIT_FAILURE_THRESHOLD = 2;
|
|
66
|
+
export function newSession(now = Date.now()) {
|
|
67
|
+
return { failures: new Map(), openedAt: new Map(), startedAt: now, runs: 0 };
|
|
68
|
+
}
|
|
69
|
+
export function circuitOpenSources(session) {
|
|
70
|
+
return [...session.openedAt.keys()].sort();
|
|
71
|
+
}
|
|
72
|
+
function recordSourceFailure(session, sourceId, now) {
|
|
73
|
+
const count = (session.failures.get(sourceId) ?? 0) + 1;
|
|
74
|
+
session.failures.set(sourceId, count);
|
|
75
|
+
if (count >= CIRCUIT_FAILURE_THRESHOLD && !session.openedAt.has(sourceId)) {
|
|
76
|
+
session.openedAt.set(sourceId, now);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
/* ------------------------------------------------------------------------------------------------
|
|
82
|
+
* Result
|
|
83
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
84
|
+
/**
|
|
85
|
+
* `DELIVERED` plus spec §7's six early terminations. Every run ends as exactly one of these.
|
|
86
|
+
*
|
|
87
|
+
* Built from `EARLY_EXITS` rather than retyped, so a seventh termination added to the domain model
|
|
88
|
+
* becomes a compile error here instead of an outcome the orchestrator can never produce.
|
|
89
|
+
*/
|
|
90
|
+
export const RUN_OUTCOMES = ["DELIVERED", ...EARLY_EXITS];
|
|
91
|
+
/* ------------------------------------------------------------------------------------------------
|
|
92
|
+
* Deadlines
|
|
93
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
94
|
+
/**
|
|
95
|
+
* The whole-run safety valve, derived from the mode table rather than invented.
|
|
96
|
+
*
|
|
97
|
+
* `deadlineMsPerSource × (maxSources + 1)`: every selected source may take its full deadline, plus
|
|
98
|
+
* one source's worth of headroom for everything Mnemosia does between them. Fast → 1,500 ms,
|
|
99
|
+
* Standard → 8,000 ms, Deep → 40,000 ms.
|
|
100
|
+
*
|
|
101
|
+
* This is **not** design §16's latency gate (Fast p95 ≤ 500 ms, Standard ≤ 2 s, Deep ≤ 10 s). The
|
|
102
|
+
* gate is a *measurement* the eval harness reports; this is a *bound* that stops a pathological read
|
|
103
|
+
* running forever. Setting the bound equal to the gate would have made the gate self-fulfilling —
|
|
104
|
+
* every run would come in under it by truncating its own work — which is precisely the kind of
|
|
105
|
+
* measurement that passes while meaning nothing.
|
|
106
|
+
*/
|
|
107
|
+
export function runDeadlineFor(mode, startedAt) {
|
|
108
|
+
const config = MODE_CONFIGS[mode];
|
|
109
|
+
return startedAt + config.deadlineMsPerSource * (config.maxSources + 1);
|
|
110
|
+
}
|
|
111
|
+
/* ------------------------------------------------------------------------------------------------
|
|
112
|
+
* The term ladder (spec §9 retry policy)
|
|
113
|
+
* ---------------------------------------------------------------------------------------------- */
|
|
114
|
+
/**
|
|
115
|
+
* The sequence of term sets to try for one query, longest first.
|
|
116
|
+
*
|
|
117
|
+
* `["store", "adapter", "paging"]` → `[["store","adapter","paging"], ["store","adapter"], ["store"]]`.
|
|
118
|
+
* Each rung drops the *lowest-priority* term, i.e. the last one `plan.ts:selectQueryTerms` ranked, so
|
|
119
|
+
* what survives longest is the entity-derived vocabulary the author typed deliberately.
|
|
120
|
+
*
|
|
121
|
+
* It stops at one term and never reaches zero. A zero-term query is a recency scan, and `plan.ts`
|
|
122
|
+
* rejects a source outright when there is no term and no temporal bound (`no_retrievable_signal`)
|
|
123
|
+
* because an unbounded scan returns the most recent rows rather than an answer. The ladder must not smuggle that back in.
|
|
124
|
+
*/
|
|
125
|
+
export function termLadder(terms) {
|
|
126
|
+
if (terms.length === 0)
|
|
127
|
+
return [[]];
|
|
128
|
+
const rungs = [];
|
|
129
|
+
for (let width = terms.length; width >= 1; width -= 1)
|
|
130
|
+
rungs.push(terms.slice(0, width));
|
|
131
|
+
return rungs;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The curated any-match set's width bound. Eight terms over a disjunctive query cost nothing on the
|
|
135
|
+
* ten-row curated corpus (see PLAN_RETRIEVAL below); a ninth would exceed what the cap was set for.
|
|
136
|
+
*/
|
|
137
|
+
export const CURATED_TERM_CAP = 8;
|
|
138
|
+
/**
|
|
139
|
+
* Merges the three sources of curated any-match vocabulary, in fixed priority order:
|
|
140
|
+
*
|
|
141
|
+
* 1. Phase B's own high-priority requirement hints and leading intent terms (`phaseBTerms`);
|
|
142
|
+
* 2. a progressive round's derived gap terms (`gapTerms`), exact-deduplicated against 1;
|
|
143
|
+
* 3. Phase D's graph-traversal terms (`traversalTerms`), appended **after** the derived terms and
|
|
144
|
+
* deduplicated case-insensitively against everything already in the list, filling only the slots
|
|
145
|
+
* the first two sources left open — never exceeding `CURATED_TERM_CAP`.
|
|
146
|
+
*
|
|
147
|
+
* Without traversal terms this is exactly the pre-Phase-D formula
|
|
148
|
+
* (`[...new Set([...phaseB, ...gap])].slice(0, CAP)`), so single-pass runs and rounds whose walk
|
|
149
|
+
* found nothing are byte-identical to the earlier build.
|
|
150
|
+
*/
|
|
151
|
+
export function mergeCuratedTerms(phaseBTerms, gapTerms, traversalTerms) {
|
|
152
|
+
const merged = [...new Set([...phaseBTerms, ...gapTerms])];
|
|
153
|
+
if (traversalTerms === undefined || traversalTerms.length === 0)
|
|
154
|
+
return merged.slice(0, CURATED_TERM_CAP);
|
|
155
|
+
const seen = new Set(merged.map((term) => term.toLowerCase()));
|
|
156
|
+
for (const term of traversalTerms) {
|
|
157
|
+
if (merged.length >= CURATED_TERM_CAP)
|
|
158
|
+
break;
|
|
159
|
+
const key = term.toLowerCase();
|
|
160
|
+
if (seen.has(key))
|
|
161
|
+
continue;
|
|
162
|
+
seen.add(key);
|
|
163
|
+
merged.push(term);
|
|
164
|
+
}
|
|
165
|
+
return merged.slice(0, CURATED_TERM_CAP);
|
|
166
|
+
}
|
|
167
|
+
function requireTraceRoot(root) {
|
|
168
|
+
if (!root)
|
|
169
|
+
throw new Error("traceRoot is required unless persistTrace is false");
|
|
170
|
+
return root;
|
|
171
|
+
}
|
|
172
|
+
function noopTrace(runId) {
|
|
173
|
+
let seq = 0;
|
|
174
|
+
return {
|
|
175
|
+
runId,
|
|
176
|
+
path: "(not persisted)",
|
|
177
|
+
get seq() {
|
|
178
|
+
return seq;
|
|
179
|
+
},
|
|
180
|
+
append(input) {
|
|
181
|
+
const event = { schemaVersion: SCHEMA_VERSION.traceEvent, runId, seq, at: input.at ?? 0, state: input.state, event: input.event, policyId: input.policyId ?? null, policyVersion: input.policyVersion ?? null, payload: input.payload ?? {} };
|
|
182
|
+
seq += 1;
|
|
183
|
+
return event;
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* One standard pass of the state machine — what `runBriefing` did before Phase C gave it a second
|
|
189
|
+
* mode. `runBriefing` is this function plus, when the caller asked for it, the bounded multi-round
|
|
190
|
+
* loop around it; keeping the pass as its own function is what makes the two modes share one
|
|
191
|
+
* implementation instead of measuring a copy.
|
|
192
|
+
*
|
|
193
|
+
* `extraCuratedTerms` carries a progressive round's gap terms into PLAN_RETRIEVAL's curated
|
|
194
|
+
* any-match set, alongside Phase B's own vocabulary; the narrow ANDed terms are untouched for the
|
|
195
|
+
* same reason `plan.ts` gives. `runId` names a non-zero round's own trace file — every round is a
|
|
196
|
+
* full auditable run, not an unlogged side query. Both parameters are absent in production's
|
|
197
|
+
* single-pass mode, where the behavior is byte-identical to the pre-Phase-C build.
|
|
198
|
+
*
|
|
199
|
+
* Never throws for a data reason. Every condition that would end a run early is one of spec §7's six
|
|
200
|
+
* terminations, each carrying the briefing shell it managed to build and the gaps that explain it —
|
|
201
|
+
* because design §20 requires that "failure must produce an explicit status and uncertainty report",
|
|
202
|
+
* and an exception is neither.
|
|
203
|
+
*/
|
|
204
|
+
function runSinglePass(request, deps, extraCuratedTerms, extraTraversalTerms, runId) {
|
|
205
|
+
const effectiveRunId = runId ?? request.runId;
|
|
206
|
+
const clock = deps.now ?? Date.now;
|
|
207
|
+
const wall = deps.wallNow ?? Date.now;
|
|
208
|
+
const startedAt = wall();
|
|
209
|
+
const now = request.now ?? clock();
|
|
210
|
+
const session = deps.session ?? newSession(now);
|
|
211
|
+
session.runs += 1;
|
|
212
|
+
const trace = deps.persistTrace === false ? noopTrace(effectiveRunId) : openTrace(effectiveRunId, { root: requireTraceRoot(deps.traceRoot), now: () => clock() });
|
|
213
|
+
const ctx = {
|
|
214
|
+
trace,
|
|
215
|
+
transition(state, payload) {
|
|
216
|
+
trace.append({ state, event: "transition", payload, at: clock() });
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
const gaps = [];
|
|
220
|
+
const sources = [];
|
|
221
|
+
const reasons = [];
|
|
222
|
+
let retrievalMs = 0;
|
|
223
|
+
// Phase B outputs. Declared here because `finish` closes over them; assigned right after
|
|
224
|
+
// ANALYZE_TASK's outcome gates, so every exit past that point carries them.
|
|
225
|
+
let situation = null;
|
|
226
|
+
let intent = null;
|
|
227
|
+
let requirements = [];
|
|
228
|
+
/* --- RECEIVE_REQUEST ------------------------------------------------------------------------ */
|
|
229
|
+
ctx.transition("RECEIVE_REQUEST", { requestingAgent: request.requestingAgent, project: request.project, mode: request.mode ?? "standard", contextBudget: request.contextBudget, taskChars: request.task.length, requestedProjects: request.requestedProjects ?? [], session: { runs: session.runs, circuitOpen: circuitOpenSources(session) } });
|
|
230
|
+
/* --- ANALYZE_TASK --------------------------------------------------------------------------- */
|
|
231
|
+
// Traces keep terms and entity text from the task, so the analysis and situation stages read the redacted text.
|
|
232
|
+
const safeTask = deps.redact(request.task);
|
|
233
|
+
const analysis = analyzeTask({ ...request, task: safeTask }, { tokenize: deps.tokenize });
|
|
234
|
+
// **PHASE 4 — the requesting seat is resolved here, once, and everything downstream reads it.**
|
|
235
|
+
//
|
|
236
|
+
// Two things come out of it and they are deliberately separate. `resolution` decides the *ranking
|
|
237
|
+
// policy* through `policy.ts`'s new agent link; `profile` decides the *composition* — section
|
|
238
|
+
// shares, lead order, conflict presentation, the addendum and its token reserve. Keeping them
|
|
239
|
+
// apart is what lets six of the eight seats share a ranking policy while still receiving visibly
|
|
240
|
+
// different briefings, and it is why a change to one is reviewable without re-reading the other.
|
|
241
|
+
const agent = resolveAgent(analysis.requestingAgent);
|
|
242
|
+
const profile = profileFor(agent.agent);
|
|
243
|
+
// **PHASE 5 — the pin, when a caller supplied one.** Production supplies none, so this is
|
|
244
|
+
// `resolvePolicy` exactly as Phases 1–4 ran it. A pinned run resolves through the chain that was
|
|
245
|
+
// in force at the pinned registry version, which for `@2` is the four-link chain without the
|
|
246
|
+
// agent binding — the very difference design §21.4 item 1 records Phase 4 as having introduced.
|
|
247
|
+
const pin = deps.policyPin;
|
|
248
|
+
const resolution = pin === undefined ? resolvePolicy(analysis.requestingAgent, analysis.taskType.value, analysis.mode.value) : resolvePolicyAt(pin.registryVersion, analysis.requestingAgent, analysis.taskType.value, analysis.mode.value);
|
|
249
|
+
// `withAgentSelection` returns the identical object when this seat uses design §10's shares, so
|
|
250
|
+
// three of the eight (Avaritia, Vaelia, and any unrecognised caller) are scored and selected
|
|
251
|
+
// against the byte-identical policy object Phases 1–3 measured.
|
|
252
|
+
//
|
|
253
|
+
// Per-seat section shares are themselves a `@3` registry change (design §19 item 3's `@2 → @3`
|
|
254
|
+
// packet lists them), so a pin below `@3` puts design §10's shares back for every seat. The rest
|
|
255
|
+
// of the briefing profile is the `agents.ts` layer and a *policy*-registry pin does not move it —
|
|
256
|
+
// see `rollback.ts`'s header for why rolling both back under one request would be two changes.
|
|
257
|
+
const policy = pin !== undefined && !appliesAgentSelection(pin.registryVersion) ? resolution.policy : withAgentSelection(resolution.policy, profile);
|
|
258
|
+
trace.append({
|
|
259
|
+
state: "ANALYZE_TASK",
|
|
260
|
+
event: "transition",
|
|
261
|
+
policyId: policy.policyId,
|
|
262
|
+
policyVersion: policy.version,
|
|
263
|
+
at: clock(),
|
|
264
|
+
payload: {
|
|
265
|
+
outcome: analysis.outcome,
|
|
266
|
+
taskType: analysis.taskType,
|
|
267
|
+
terms: analysis.terms.value,
|
|
268
|
+
entities: analysis.entities.value,
|
|
269
|
+
temporalNeed: analysis.temporalNeed,
|
|
270
|
+
since: analysis.since,
|
|
271
|
+
reasons: analysis.reasons,
|
|
272
|
+
agent: { requested: agent.requested, resolved: agent.agent, how: agent.how, detail: agent.detail },
|
|
273
|
+
policyResolution: { policyId: resolution.policy.policyId, matchedBy: resolution.matchedBy, attempted: resolution.attempted },
|
|
274
|
+
policyPin: pin === undefined ? null : { registryVersion: pin.registryVersion, pinnedBy: pin.pinnedBy, reason: pin.reason, agentSelection: pin.agentSelection },
|
|
275
|
+
profile: { leadSections: profile.leadSections, conflictPresentation: profile.conflictPresentation, blocks: profile.blocks, addendumCeiling: profile.addendumReserve, sharesAreDefault: policy.selection.sectionShares === resolution.policy.selection.sectionShares },
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
const finish = (outcome, finalState, extra = {}) => {
|
|
279
|
+
const elapsedMs = Date.now() - startedAt;
|
|
280
|
+
trace.append({ state: finalState, event: "outcome", at: clock(), payload: { outcome, elapsedMs, reasons, gaps } });
|
|
281
|
+
return {
|
|
282
|
+
runId: request.runId,
|
|
283
|
+
outcome,
|
|
284
|
+
finalState,
|
|
285
|
+
delivered: false,
|
|
286
|
+
briefing: null,
|
|
287
|
+
markdown: null,
|
|
288
|
+
validation: null,
|
|
289
|
+
analysis,
|
|
290
|
+
authorization: null,
|
|
291
|
+
plan: null,
|
|
292
|
+
policy,
|
|
293
|
+
gaps,
|
|
294
|
+
sources,
|
|
295
|
+
claims: [],
|
|
296
|
+
envelopes: [],
|
|
297
|
+
candidates: [],
|
|
298
|
+
graph: null,
|
|
299
|
+
conflicts: null,
|
|
300
|
+
selection: null,
|
|
301
|
+
filters: null,
|
|
302
|
+
stats: { envelopes: 0, uniqueEnvelopes: 0, claimsExtracted: 0, claimsDeduped: 0, claimsAccepted: 0, candidatesScored: 0, candidatesCapped: 0, itemsSelected: 0, conflicts: 0, quarantined: 0, unknownHeadingRate: 0, extraction: extractClaims([]).stats, elapsedMs, retrievalMs },
|
|
303
|
+
tracePath: trace.path,
|
|
304
|
+
reasons,
|
|
305
|
+
situation,
|
|
306
|
+
intent,
|
|
307
|
+
requirements,
|
|
308
|
+
...extra,
|
|
309
|
+
};
|
|
310
|
+
};
|
|
311
|
+
if (analysis.outcome === "NO_MEMORY_REQUIRED") {
|
|
312
|
+
reasons.push(...analysis.reasons);
|
|
313
|
+
return finish("NO_MEMORY_REQUIRED", "ANALYZE_TASK");
|
|
314
|
+
}
|
|
315
|
+
if (analysis.outcome === "CLARIFICATION_REQUIRED") {
|
|
316
|
+
reasons.push(...analysis.reasons);
|
|
317
|
+
return finish("CLARIFICATION_REQUIRED", "ANALYZE_TASK");
|
|
318
|
+
}
|
|
319
|
+
/* --- PHASE B: SITUATION AND INTENT ---------------------------------------------------------- */
|
|
320
|
+
// Three stages between task analysis and retrieval planning (build spec Phase B). Deterministic,
|
|
321
|
+
// bounded and non-gating: a clarification *recommendation* is recorded and traced but never ends
|
|
322
|
+
// the run here — ending runs on inferred ambiguity would let a heuristic override the caller, the
|
|
323
|
+
// exact failure the spec's guardrail against redefining the user's task warns about.
|
|
324
|
+
situation = validateSituationContext(analyseSituation(safeTask, request.requestingAgent, { project: request.project, requestedProjects: request.requestedProjects }));
|
|
325
|
+
intent = inferIntentHypotheses(safeTask, situation);
|
|
326
|
+
requirements = deriveKnowledgeRequirements(safeTask, situation, intent, request.requestingAgent);
|
|
327
|
+
// The planning feed: high-priority requirement vocabulary plus the leading hypothesis's terms,
|
|
328
|
+
// appended to the curated any-match set only (see `plan.ts` for why not the narrow conjunction).
|
|
329
|
+
const phaseBExtraTerms = [...new Set([...requirements.filter((requirement) => requirement.priority === "high").flatMap((requirement) => requirement.queryHints ?? []), ...leadingQueryTerms(intent)])].slice(0, 4);
|
|
330
|
+
// A progressive round's gap terms join the same curated set. They are appended *after* Phase B's
|
|
331
|
+
// vocabulary so round 0's set is unchanged, and capped at eight because the set feeds a
|
|
332
|
+
// disjunctive query over a ten-row curated corpus — width costs nothing there, unlike the
|
|
333
|
+
// narrow conjunction (`plan.ts:MAX_QUERY_TERMS`). Undefined parameters ⇒ byte-identical set.
|
|
334
|
+
// Phase D adds traversal vocabulary as the lowest-priority source (see mergeCuratedTerms).
|
|
335
|
+
const plannedExtraCuratedTerms = mergeCuratedTerms(phaseBExtraTerms, extraCuratedTerms ?? [], extraTraversalTerms);
|
|
336
|
+
trace.append({ state: "ANALYZE_TASK", event: "situation_analysis", at: clock(), payload: { schemaVersion: situation.schemaVersion, counts: situation.counts, items: situation.items.map((item) => ({ id: item.id, tier: item.tier, confidence: item.confidence, signals: item.supportingSignals.length })) } });
|
|
337
|
+
trace.append({ state: "ANALYZE_TASK", event: "intent_hypotheses", at: clock(), payload: { schemaVersion: intent.schemaVersion, calibrated: intent.calibrated, probabilitiesSum: intent.probabilitiesSum, hypotheses: intent.hypotheses.map((hypothesis) => ({ id: hypothesis.hypothesisId, probability: hypothesis.probability, status: hypothesis.status })), recommendation: intent.recommendation } });
|
|
338
|
+
trace.append({ state: "ANALYZE_TASK", event: "knowledge_requirements", at: clock(), payload: { count: requirements.length, requirements: requirements.map((requirement) => ({ id: requirement.requirementId, priority: requirement.priority, sourcePreference: requirement.sourcePreference })) } });
|
|
339
|
+
// Chunk C's leftover, now a decision rather than a validator failure. See
|
|
340
|
+
// `select.ts:minimumConformingBudget` for the arithmetic. Checked here, before AUTHORIZE_SCOPE,
|
|
341
|
+
// because the answer does not depend on anything a query could return.
|
|
342
|
+
//
|
|
343
|
+
// **PHASE 4 — the seat's addendum reserve is part of the frame, so it is part of the floor.**
|
|
344
|
+
// `select.ts` step 0 charges `scaffolding + reserve` before a claim is placed, so a seat whose
|
|
345
|
+
// addendum needs 380 tokens genuinely cannot produce a conforming briefing at the budget that
|
|
346
|
+
// suffices for a seat whose addendum needs none. Computing the floor from the shared constant and
|
|
347
|
+
// then charging the larger overhead would put the whole reserve on the wrong side of the check,
|
|
348
|
+
// and the run would exit `PARTIAL_BRIEFING` for a budget it should have refused up front.
|
|
349
|
+
const addendumReserve = effectiveAddendumReserve(profile, analysis.contextBudget.value);
|
|
350
|
+
const scaffolding = BRIEFING_SCAFFOLDING_TOKENS + addendumReserve;
|
|
351
|
+
const floor = minimumConformingBudgetForSeat(analysis.objective, policy, BRIEFING_SCAFFOLDING_TOKENS, profile.addendumReserve);
|
|
352
|
+
if (analysis.contextBudget.value < floor) {
|
|
353
|
+
reasons.push(`the ${analysis.contextBudget.value}-token budget is below the ${floor}-token floor for a conforming briefing (a ${policy.selection.reserveRatio * 100}% reserve plus the objective echo plus the briefing frame${addendumReserve === 0 ? "" : ` plus this seat's ${addendumReserve}-token agent addendum`}); no selection of evidence can fix that, so the request needs a larger budget`);
|
|
354
|
+
ctx.transition("ANALYZE_TASK", { earlyExit: "CLARIFICATION_REQUIRED", minimumConformingBudget: floor, contextBudget: analysis.contextBudget.value, scaffolding, addendumReserve });
|
|
355
|
+
gaps.push({ sourceId: "mnemosia/selection", reason: "budget", detail: `contextBudget ${analysis.contextBudget.value} < ${floor}, the minimum that holds the objective echo and the briefing frame`, code: null });
|
|
356
|
+
return finish("CLARIFICATION_REQUIRED", "ANALYZE_TASK");
|
|
357
|
+
}
|
|
358
|
+
/* --- AUTHORIZE_SCOPE ------------------------------------------------------------------------ */
|
|
359
|
+
const authorization = authorizeScope(analysis);
|
|
360
|
+
ctx.transition("AUTHORIZE_SCOPE", { outcome: authorization.outcome, granted: authorization.granted.map((grant) => ({ scope: `${grant.scope.level}:${grant.scope.project ?? "-"}`, ruleId: grant.ruleId })), refused: authorization.refused.map((refusal) => ({ scope: `${refusal.scope.level}:${refusal.scope.project ?? "-"}`, ruleId: refusal.ruleId })), reasons: authorization.reasons });
|
|
361
|
+
if (authorization.outcome === "INSUFFICIENT_AUTHORIZATION") {
|
|
362
|
+
reasons.push(...authorization.reasons);
|
|
363
|
+
for (const refusal of authorization.refused)
|
|
364
|
+
gaps.push({ sourceId: "mnemosia/authorization", reason: "not_planned", detail: refusal.detail, code: null });
|
|
365
|
+
return finish("INSUFFICIENT_AUTHORIZATION", "AUTHORIZE_SCOPE", { authorization });
|
|
366
|
+
}
|
|
367
|
+
/* --- PLAN_RETRIEVAL ------------------------------------------------------------------------- */
|
|
368
|
+
const probes = deps.adapters.map((adapter) => {
|
|
369
|
+
const probe = adapter.probe();
|
|
370
|
+
trace.append({ state: "PLAN_RETRIEVAL", event: "adapter_result", at: clock(), payload: { phase: "probe", ...probe } });
|
|
371
|
+
// A probe that reports unavailable is a failure for breaker purposes: two of them in a session
|
|
372
|
+
// is exactly the "failing twice" design §13 opens the circuit on.
|
|
373
|
+
if (!probe.available)
|
|
374
|
+
recordSourceFailure(session, probe.sourceId, clock());
|
|
375
|
+
return probe;
|
|
376
|
+
});
|
|
377
|
+
const plan = planRetrieval({ analysis, authorization, probes, circuitOpen: circuitOpenSources(session), now, extraCuratedTerms: plannedExtraCuratedTerms });
|
|
378
|
+
gaps.push(...plan.gaps);
|
|
379
|
+
trace.append({ state: "PLAN_RETRIEVAL", event: "transition", policyId: policy.policyId, policyVersion: policy.version, at: clock(), payload: { selected: plan.selected, rejected: plan.rejected, decisions: plan.decisions.map((decision) => ({ sourceId: decision.sourceId, selected: decision.selected, ruleId: decision.ruleId, justification: decision.justification })), queries: plan.queries.length, tokenBudget: plan.tokenBudget, maxCandidates: plan.maxCandidates, deadlines: plan.deadlines, retryPolicy: plan.retryPolicy, stopConditions: plan.stopConditions } });
|
|
380
|
+
const everyProbeDown = probes.length > 0 && probes.every((probe) => !probe.available);
|
|
381
|
+
const everySourceUnreachable = plan.decisions.length > 0 && plan.decisions.every((decision) => !decision.selected && (decision.ruleId === "probe_unavailable" || decision.ruleId === "circuit_open" || decision.ruleId === "not_registered"));
|
|
382
|
+
if (everyProbeDown || everySourceUnreachable) {
|
|
383
|
+
reasons.push(`every registered source is unavailable: ${plan.decisions.map((decision) => `${decision.sourceId} (${decision.ruleId})`).join(", ")}`);
|
|
384
|
+
return finish("RETRIEVAL_UNAVAILABLE", "PLAN_RETRIEVAL", { authorization, plan });
|
|
385
|
+
}
|
|
386
|
+
if (plan.selected.length === 0) {
|
|
387
|
+
// Every source was rejected *on its merits* — a healthy corpus the planner declined to read.
|
|
388
|
+
// That is not an availability failure and reporting it as one would make an honest planning
|
|
389
|
+
// decision look like an outage.
|
|
390
|
+
reasons.push(`the planner selected no source: ${plan.decisions.map((decision) => `${decision.sourceId} (${decision.ruleId})`).join(", ")}`);
|
|
391
|
+
return finish("INSUFFICIENT_INFORMATION", "PLAN_RETRIEVAL", { authorization, plan });
|
|
392
|
+
}
|
|
393
|
+
/* --- EXECUTE_SOURCE_QUERIES ----------------------------------------------------------------- */
|
|
394
|
+
const runDeadline = runDeadlineFor(analysis.mode.value, startedAt);
|
|
395
|
+
const rawEnvelopes = [];
|
|
396
|
+
const outcomeBySource = new Map();
|
|
397
|
+
const adapterIndex = new Map(deps.adapters.map((adapter) => [adapter.sourceId, adapter]));
|
|
398
|
+
// The run's excerpt-window anchor (claims.ts:402-420) is taken from a **conjunctive** query only.
|
|
399
|
+
// An `any`-match query carries the wide term set precisely because it is not trying to be precise,
|
|
400
|
+
// so anchoring raw-event excerpts on it would centre them on whichever task word happened to occur
|
|
401
|
+
// first rather than on the subject the narrow query actually matched.
|
|
402
|
+
let queryTerms = plan.queries.find((query) => query.matchMode === "all" && query.terms.length > 0)?.terms ?? [];
|
|
403
|
+
for (const query of plan.queries) {
|
|
404
|
+
const adapter = adapterIndex.get(query.sourceId);
|
|
405
|
+
let outcome = outcomeBySource.get(query.sourceId);
|
|
406
|
+
if (outcome === undefined) {
|
|
407
|
+
outcome = { sourceId: query.sourceId, attempts: [], envelopes: 0, failed: false, circuitOpened: false };
|
|
408
|
+
outcomeBySource.set(query.sourceId, outcome);
|
|
409
|
+
sources.push(outcome);
|
|
410
|
+
}
|
|
411
|
+
if (adapter === undefined) {
|
|
412
|
+
gaps.push({ sourceId: query.sourceId, reason: "not_planned", detail: "the plan selected this source but no adapter with that id is registered", code: null });
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
if (wall() >= runDeadline) {
|
|
416
|
+
gaps.push({ sourceId: query.sourceId, reason: "deadline", detail: `the ${runDeadline - startedAt} ms run deadline elapsed before ${query.sourceId} was queried`, code: null });
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
// **CORRECTED IN PHASE 4 — the per-source deadline was read off the wrong clock.**
|
|
420
|
+
// **CORRECTED 2026-10-05 — the window was anchored at the wrong instant.**
|
|
421
|
+
//
|
|
422
|
+
// Deadlines remain wall-clock quantities (the Phase 4 rule below still holds), but anchoring
|
|
423
|
+
// every source's window at the RUN's start made the per-source window a shared resource:
|
|
424
|
+
// sources execute sequentially, so the pre-EXECUTE preamble (source probes) plus the first
|
|
425
|
+
// source's work routinely consumed later sources' windows before their first query ran. On
|
|
426
|
+
// the live corpus, 60 recorded runs show every source breaking at rung 0 with zero adapter
|
|
427
|
+
// queries — paired "deadline ... after 0 term-ladder rung(s)" + "empty_result after 0
|
|
428
|
+
// term-ladder rung(s)" gaps and INSUFFICIENT_INFORMATION over sources that were healthy.
|
|
429
|
+
// The documented intent — "every selected source may take its full deadline" — is restored by
|
|
430
|
+
// anchoring the window at THIS source's arrival (wall clock), still clamped by the run
|
|
431
|
+
// ceiling: the ceiling, not source ordering, is what bounds total retrieval time.
|
|
432
|
+
//
|
|
433
|
+
// (Phase 4, preserved:) `plan.ts` computes `deadlines[sourceId]` from the *logical* clock —
|
|
434
|
+
// `deps.now()` — while the checks here are wall-clock. In production the two coincide; a
|
|
435
|
+
// caller pinning the logical clock (scripts/phase4-live.ts, the eval harness's fixed NOW)
|
|
436
|
+
// must not have that pin interpreted as elapsed time. The window is therefore derived from
|
|
437
|
+
// `deps.wallNow` — never `deps.now`. `plan.deadlines` stays on the plan for the trace, as the
|
|
438
|
+
// budget the plan declared.
|
|
439
|
+
const perSourceMs = MODE_CONFIGS[analysis.mode.value].deadlineMsPerSource;
|
|
440
|
+
const deadline = Math.min(wall() + perSourceMs, runDeadline);
|
|
441
|
+
// The ladder. A query that carries no term has exactly one rung and no retry: there is nothing
|
|
442
|
+
// to broaden, and `plan.ts` already justified reading that source without one.
|
|
443
|
+
//
|
|
444
|
+
// An `any`-match query has one rung for a different reason: its rungs would be *subsets* of a
|
|
445
|
+
// disjunction, so every retry can only return fewer rows than the one that just came back
|
|
446
|
+
// empty. The ladder broadens a conjunction; there is nothing for it to broaden here, and
|
|
447
|
+
// running it anyway would spend a query per rung to re-derive the same empty answer.
|
|
448
|
+
const rungs = query.matchMode === "any" ? [query.terms] : termLadder(query.terms);
|
|
449
|
+
let produced = 0;
|
|
450
|
+
for (const [index, terms] of rungs.entries()) {
|
|
451
|
+
if (wall() >= deadline) {
|
|
452
|
+
gaps.push({ sourceId: query.sourceId, reason: "deadline", detail: `the per-source deadline elapsed after ${index} term-ladder rung(s)`, code: null });
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
455
|
+
const attempt = terms.length === query.terms.length ? query : { ...query, terms, justification: `${query.justification} — term-ladder rung ${index + 1}: retried with ${terms.length} of ${query.terms.length} term(s) after an empty result` };
|
|
456
|
+
const startedQuery = Date.now();
|
|
457
|
+
let result = null;
|
|
458
|
+
let errorMessage = null;
|
|
459
|
+
let errorCode = null;
|
|
460
|
+
try {
|
|
461
|
+
result = adapter.query(attempt, deadline);
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
errorMessage = error instanceof Error ? error.message : String(error);
|
|
465
|
+
errorCode = isStandardAdapterError(error) ? error.code : null;
|
|
466
|
+
}
|
|
467
|
+
const elapsed = Date.now() - startedQuery;
|
|
468
|
+
retrievalMs += elapsed;
|
|
469
|
+
outcome.attempts.push({ terms: [...terms], envelopes: result?.envelopes.length ?? 0, elapsedMs: elapsed, pagesRead: result?.pagesRead ?? 0, truncated: result?.truncated ?? false, error: errorMessage, code: errorCode });
|
|
470
|
+
trace.append({ state: "EXECUTE_SOURCE_QUERIES", event: "adapter_result", at: clock(), payload: { sourceId: query.sourceId, scope: `${query.scope.level}:${query.scope.project ?? "-"}`, rung: index + 1, terms, envelopes: result?.envelopes.length ?? 0, pagesRead: result?.pagesRead ?? 0, truncated: result?.truncated ?? false, elapsedMs: elapsed, error: errorMessage, code: errorCode } });
|
|
471
|
+
if (errorMessage !== null) {
|
|
472
|
+
// Design §13: adapter isolation. The failure is named, the breaker is told, and the loop
|
|
473
|
+
// moves on — the run continues with whatever the other sources returned.
|
|
474
|
+
outcome.failed = true;
|
|
475
|
+
gaps.push({ sourceId: query.sourceId, reason: "adapter_error", detail: errorMessage, code: errorCode ?? "internal" });
|
|
476
|
+
if (recordSourceFailure(session, query.sourceId, clock())) {
|
|
477
|
+
outcome.circuitOpened = true;
|
|
478
|
+
trace.append({ state: "EXECUTE_SOURCE_QUERIES", event: "adapter_result", at: clock(), payload: { sourceId: query.sourceId, circuit: "opened", threshold: CIRCUIT_FAILURE_THRESHOLD, detail: "the breaker stays open until session_start (design §13)" } });
|
|
479
|
+
}
|
|
480
|
+
break;
|
|
481
|
+
}
|
|
482
|
+
if (result !== null && result.envelopes.length > 0) {
|
|
483
|
+
rawEnvelopes.push(...result.envelopes);
|
|
484
|
+
produced = result.envelopes.length;
|
|
485
|
+
outcome.envelopes += result.envelopes.length;
|
|
486
|
+
// The rung that succeeded becomes the run's query terms, so claim extraction anchors
|
|
487
|
+
// its excerpt windows on the terms that actually matched (claims.ts:402-420). Rung 0
|
|
488
|
+
// included — otherwise a later source's envelopes are excerpt-anchored on an earlier
|
|
489
|
+
// source's reduced terms.
|
|
490
|
+
queryTerms = [...terms];
|
|
491
|
+
if (index > 0) {
|
|
492
|
+
trace.append({ state: "EXECUTE_SOURCE_QUERIES", event: "transition", at: clock(), payload: { sourceId: query.sourceId, termLadder: "recovered", rung: index + 1, from: query.terms, to: terms, envelopes: result.envelopes.length } });
|
|
493
|
+
}
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (produced === 0 && !outcome.failed) {
|
|
498
|
+
gaps.push({ sourceId: query.sourceId, reason: "empty_result", detail: `the query returned no artifacts after ${outcome.attempts.length} term-ladder rung(s) (${rungs.map((rung) => `[${rung.join(" ")}]`).join(" → ")})`, code: null });
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const queriedSources = [...outcomeBySource.values()];
|
|
502
|
+
if (queriedSources.length > 0 && queriedSources.every((entry) => entry.failed)) {
|
|
503
|
+
reasons.push(`every selected source failed: ${queriedSources.map((entry) => entry.sourceId).join(", ")}`);
|
|
504
|
+
ctx.transition("EXECUTE_SOURCE_QUERIES", { earlyExit: "RETRIEVAL_UNAVAILABLE", failed: queriedSources.map((entry) => entry.sourceId) });
|
|
505
|
+
return finish("RETRIEVAL_UNAVAILABLE", "EXECUTE_SOURCE_QUERIES", { authorization, plan });
|
|
506
|
+
}
|
|
507
|
+
ctx.transition("EXECUTE_SOURCE_QUERIES", { envelopes: rawEnvelopes.length, bySource: Object.fromEntries(queriedSources.map((entry) => [entry.sourceId, entry.envelopes])), failed: queriedSources.filter((entry) => entry.failed).map((entry) => entry.sourceId), retrievalMs });
|
|
508
|
+
/* --- NORMALIZE_ARTIFACTS -------------------------------------------------------------------- */
|
|
509
|
+
//
|
|
510
|
+
// The trust boundary (design §5). Content is hashed and channel-tagged by the adapters on the way
|
|
511
|
+
// out of the provider; here it is deduplicated by identity and safety-scanned, and after this
|
|
512
|
+
// point it is only ever data.
|
|
513
|
+
//
|
|
514
|
+
// Deduplication is not cosmetic: `queryScopes` issues one query per authorized project scope and
|
|
515
|
+
// AkashicForge reads a project filter as "global ∪ this project" (store.ts:661), so a global row
|
|
516
|
+
// legitimately comes back from every scope query. Counting it twice would double its weight in
|
|
517
|
+
// `evidence_strength`, which prices *distinct artifacts* (rank.ts:338).
|
|
518
|
+
const envelopeIndex = new Map();
|
|
519
|
+
for (const envelope of rawEnvelopes)
|
|
520
|
+
if (!envelopeIndex.has(envelope.artifactId))
|
|
521
|
+
envelopeIndex.set(envelope.artifactId, envelope);
|
|
522
|
+
const envelopes = [...envelopeIndex.values()];
|
|
523
|
+
const artifactScan = scanArtifacts(envelopes, deps.scan);
|
|
524
|
+
ctx.transition("NORMALIZE_ARTIFACTS", { received: rawEnvelopes.length, unique: envelopes.length, duplicatesDropped: rawEnvelopes.length - envelopes.length, scanned: artifactScan.scanned, quarantined: artifactScan.quarantined.size, unscannable: artifactScan.unscannable, bySourceType: tally(envelopes.map((envelope) => envelope.sourceType)), byIntegrity: tally(envelopes.map((envelope) => envelope.integrityStatus)) });
|
|
525
|
+
for (const entry of artifactScan.quarantined.values())
|
|
526
|
+
trace.append({ state: "NORMALIZE_ARTIFACTS", event: "filter_reject", at: clock(), payload: { rule: "quarantine", ...entry } });
|
|
527
|
+
/* --- EXTRACT_OR_RESOLVE_CLAIMS -------------------------------------------------------------- */
|
|
528
|
+
const extraction = extractClaims(envelopes, { terms: queryTerms });
|
|
529
|
+
const knownSections = extraction.stats.knownSections + extraction.stats.unknownSections;
|
|
530
|
+
const unknownHeadingRate = knownSections === 0 ? 0 : extraction.stats.unknownSections / knownSections;
|
|
531
|
+
ctx.transition("EXTRACT_OR_RESOLVE_CLAIMS", { claims: extraction.stats.claims, byPath: extraction.stats.byPath, knownSections: extraction.stats.knownSections, unknownSections: extraction.stats.unknownSections, unknownHeadingRate, unknownHeadings: extraction.stats.unknownHeadings, droppedTrailingBlocks: extraction.stats.droppedTrailingBlocks, unhandledEnvelopes: extraction.stats.unhandledEnvelopes });
|
|
532
|
+
if (unknownHeadingRate > SUMMARY_DRIFT_WARNING) {
|
|
533
|
+
// Design §18 risk 3. Recorded, not raised: a grammar that drifted still extracts whole-section
|
|
534
|
+
// OBSERVATIONs, so the run is degraded rather than broken, and `/mnemosia status` is where an
|
|
535
|
+
// operator is told.
|
|
536
|
+
trace.append({ state: "EXTRACT_OR_RESOLVE_CLAIMS", event: "validation", at: clock(), payload: { warning: "summary_grammar_drift", rate: unknownHeadingRate, threshold: SUMMARY_DRIFT_WARNING, headings: extraction.stats.unknownHeadings } });
|
|
537
|
+
}
|
|
538
|
+
/* --- DEDUPLICATE ---------------------------------------------------------------------------- */
|
|
539
|
+
const deduped = dedupeClaims(extraction.claims);
|
|
540
|
+
ctx.transition("DEDUPLICATE", { before: deduped.before, after: deduped.after, merged: deduped.merged, multiSourced: deduped.multiSourced });
|
|
541
|
+
/* --- APPLY_HARD_FILTERS --------------------------------------------------------------------- */
|
|
542
|
+
const filters = applyHardFilters({ claims: deduped.claims, envelopes, authorization, scan: deps.scan, artifactScan, now, failClosedOnUnverified: plan.failClosedOnUnverified });
|
|
543
|
+
for (const rejection of filters.rejections)
|
|
544
|
+
trace.append({ state: "APPLY_HARD_FILTERS", event: "filter_reject", at: clock(), payload: { ...rejection } });
|
|
545
|
+
ctx.transition("APPLY_HARD_FILTERS", { in: filters.stats.claimsIn, out: filters.stats.claimsOut, rejected: filters.stats.rejected, byRule: filters.stats.byRule, quarantined: filters.stats.artifactsQuarantined, evidencePruned: filters.stats.evidencePruned, failClosedOnUnverified: plan.failClosedOnUnverified });
|
|
546
|
+
const partialStats = () => ({
|
|
547
|
+
envelopes: rawEnvelopes.length,
|
|
548
|
+
uniqueEnvelopes: envelopes.length,
|
|
549
|
+
claimsExtracted: extraction.stats.claims,
|
|
550
|
+
claimsDeduped: deduped.after,
|
|
551
|
+
claimsAccepted: filters.stats.claimsOut,
|
|
552
|
+
candidatesScored: 0,
|
|
553
|
+
candidatesCapped: 0,
|
|
554
|
+
itemsSelected: 0,
|
|
555
|
+
conflicts: 0,
|
|
556
|
+
quarantined: filters.stats.artifactsQuarantined,
|
|
557
|
+
unknownHeadingRate,
|
|
558
|
+
extraction: extraction.stats,
|
|
559
|
+
elapsedMs: Date.now() - startedAt,
|
|
560
|
+
retrievalMs,
|
|
561
|
+
});
|
|
562
|
+
if (filters.accepted.length === 0) {
|
|
563
|
+
reasons.push(`no claim survived hard filtering: ${extraction.stats.claims} extracted, ${deduped.after} after deduplication, ${filters.stats.rejected} rejected (${Object.entries(filters.stats.byRule).filter(([, count]) => count > 0).map(([rule, count]) => `${rule}=${count}`).join(", ") || "none"})`);
|
|
564
|
+
gaps.push({ sourceId: "mnemosia/filters", reason: "empty_result", detail: reasons[reasons.length - 1] ?? "nothing survived hard filtering", code: null });
|
|
565
|
+
return finish("INSUFFICIENT_INFORMATION", "APPLY_HARD_FILTERS", { authorization, plan, envelopes, claims: deduped.claims, filters, stats: partialStats() });
|
|
566
|
+
}
|
|
567
|
+
/* --- SCORE_CANDIDATES ----------------------------------------------------------------------- */
|
|
568
|
+
// **PHASE 2 — the provenance graph.**
|
|
569
|
+
//
|
|
570
|
+
// Built here, between hard filtering and scoring, because both of the states that follow read it:
|
|
571
|
+
// `SCORE_CANDIDATES` prices evidence strength off graph distance, corroboration and contradiction,
|
|
572
|
+
// and `DETECT_CONFLICTS` classifies the very edges that were priced. Building it twice would let
|
|
573
|
+
// the number a reader sees and the conflict they are shown disagree about what the run holds. It
|
|
574
|
+
// covers the **accepted** claims only — a rejected claim must not appear in the graph any more
|
|
575
|
+
// than it may appear in the briefing.
|
|
576
|
+
const graph = buildProvenanceGraph({ claims: filters.accepted, envelopes, now, shingleSize: policy.selection.shingleSize, neighbourhoodThreshold: policy.conflict.neighbourhoodThreshold });
|
|
577
|
+
trace.append({
|
|
578
|
+
state: "APPLY_HARD_FILTERS",
|
|
579
|
+
event: "provenance",
|
|
580
|
+
at: clock(),
|
|
581
|
+
policyId: policy.policyId,
|
|
582
|
+
policyVersion: policy.version,
|
|
583
|
+
payload: { ...graph.stats, qualifierRanking: QUALIFIER_RANKING },
|
|
584
|
+
});
|
|
585
|
+
// **PHASE D — cross-agent lineage over the accepted claim set.** One event per run, recorded after
|
|
586
|
+
// hard filtering fixed what "accepted" means and never read by anything downstream of it: which
|
|
587
|
+
// seat produced each accepted claim (via `specialist-finding:<seat>` tags on its evidence) and
|
|
588
|
+
// which seat requested the run. `joinCoverage` is always numeric; consumers apply
|
|
589
|
+
// MIN_LINEAGE_COVERAGE themselves so the shortfall stays observable even where lineage is absent.
|
|
590
|
+
const lineage = buildAgentLineage({ claims: filters.accepted, envelopes, requestingAgent: analysis.requestingAgent, effectiveRunId, requestRunId: request.runId });
|
|
591
|
+
trace.append({ state: "APPLY_HARD_FILTERS", event: "agent_lineage", at: clock(), payload: { ...lineage } });
|
|
592
|
+
const ranked = rankCandidates({ claims: filters.accepted, envelopes, analysis, tokenize: deps.tokenize, policy, graph, now, trace });
|
|
593
|
+
let candidates = ranked.candidates;
|
|
594
|
+
let candidatesCapped = 0;
|
|
595
|
+
if (candidates.length > plan.maxCandidates) {
|
|
596
|
+
// The mode's candidate cap, applied after ranking so what survives is the highest-utility
|
|
597
|
+
// prefix rather than whatever the adapters happened to return first. Disclosed as a gap: the
|
|
598
|
+
// reader is told the corpus held more than the mode was willing to weigh.
|
|
599
|
+
candidatesCapped = candidates.length - plan.maxCandidates;
|
|
600
|
+
candidates = candidates.slice(0, plan.maxCandidates);
|
|
601
|
+
gaps.push({ sourceId: "mnemosia/ranking", reason: "budget", detail: `${analysis.mode.value} mode weighs at most ${plan.maxCandidates} candidates; ${candidatesCapped} lower-utility claim(s) were not considered for selection`, code: null });
|
|
602
|
+
}
|
|
603
|
+
// **PHASE 5 — model-assisted reranking, and it is off (spec §12, design §3).**
|
|
604
|
+
//
|
|
605
|
+
// Placed *here*, after the mode's candidate cap, and the position is the argument. §12 admits
|
|
606
|
+
// LLM-assisted reranking "only after deterministic filtering"; the cap is the last deterministic
|
|
607
|
+
// narrowing a candidate faces, so a reranker in front of it would be deciding what gets weighed
|
|
608
|
+
// rather than reordering what already was. Behind it, the reranker's whole reachable universe is
|
|
609
|
+
// the set the deterministic pipeline already admitted — which is why `rerank.ts` can guarantee
|
|
610
|
+
// structurally that no hard-filtered claim is ever resurrected.
|
|
611
|
+
//
|
|
612
|
+
// It is called with no gate and no model, so the `rerank` trace event exists on every run and a replay
|
|
613
|
+
// can tell "the gate was closed" from "the stage was never wired". The default gate returns `candidates`
|
|
614
|
+
// **by identity**. There is no option to open it: selectContext re-sorts by utility, so a reranked
|
|
615
|
+
// order would be ignored, and reranking stays off until that selection part is built.
|
|
616
|
+
const reranked = applyReranking(candidates, { runId: effectiveRunId, objective: analysis.objective, policyId: policy.policyId, trace, now: clock });
|
|
617
|
+
candidates = reranked.candidates;
|
|
618
|
+
ctx.transition("SCORE_CANDIDATES", { scored: ranked.stats.scored, capped: candidatesCapped, meanUtility: ranked.stats.meanUtility, maxUtility: ranked.stats.maxUtility, minUtility: ranked.stats.minUtility, byAuthorityClass: ranked.stats.byAuthorityClass, policyResolvedBy: ranked.resolution.matchedBy, rerank: { status: reranked.status, rerankerVersion: reranked.rerankerVersion, moved: reranked.moved, dropped: reranked.dropped.length } });
|
|
619
|
+
/* --- DETECT_CONFLICTS / RESOLVE_OR_ESCALATE ------------------------------------------------- */
|
|
620
|
+
const conflictsEnabled = deps.conflictDetection !== "off";
|
|
621
|
+
// Authority for `AUTHORITY_DISAGREEMENT` comes from the scores that were just computed, so the
|
|
622
|
+
// classifier and the ranker cannot disagree about a source's standing. A claim that was capped out
|
|
623
|
+
// of the candidate set has no score and therefore no authority — the class simply does not fire
|
|
624
|
+
// for it, which is correct: it is not in the briefing to disagree with anything.
|
|
625
|
+
const authorityByClaim = new Map(candidates.map((candidate) => [candidate.claim.claimId, candidate.score.authority]));
|
|
626
|
+
let conflicts = conflictsEnabled
|
|
627
|
+
? detectConflicts({ claims: candidates.map((candidate) => candidate.claim), graph, policy, authorityOf: (claimId) => authorityByClaim.get(claimId), now, trace })
|
|
628
|
+
: detectConflicts({ claims: [], graph, policy, now });
|
|
629
|
+
ctx.transition("DETECT_CONFLICTS", { enabled: conflictsEnabled, conflicts: conflicts.stats.conflicts, byClass: conflicts.stats.byClass, byDetector: conflicts.stats.byDetector, dangling: conflicts.stats.danglingReferences, unresolved: conflicts.stats.unresolved, pairsExamined: conflicts.stats.pairsExamined, pairsUnexplained: conflicts.stats.pairsUnexplained, ungroundedSummaries: conflicts.stats.ungroundedSummaries, ...(conflictsEnabled ? {} : { ablation: "conflictDetection=off (design §16 / spec §24 comparison system); no conflict was looked for, which is not the same as none existing" }) });
|
|
630
|
+
/* --- RESOLVE_OR_ESCALATE -------------------------------------------------------------------- */
|
|
631
|
+
//
|
|
632
|
+
// **PHASE 4 — the state finally does the second half of its own name.** Through Phases 1–3 it
|
|
633
|
+
// recorded resolution and reported `escalated: 0`, because `detectConflicts` does not know who is
|
|
634
|
+
// asking and a routing label whose recipient might be its own author is not a routing decision.
|
|
635
|
+
// `routeEscalations` is handed the requesting seat and the authorization, and produces an
|
|
636
|
+
// addressed `EscalationRequest` for every label it writes — `escalation.ts` has the two rules and
|
|
637
|
+
// why they divide the way they do.
|
|
638
|
+
//
|
|
639
|
+
// Integrity comes from the envelopes behind each claim rather than from a second read: the
|
|
640
|
+
// `authority_over_unverified` rule compares the standing table's pick against what the *content
|
|
641
|
+
// hash check* concluded, and the two must be looking at the same artifact for the comparison to
|
|
642
|
+
// mean anything.
|
|
643
|
+
const envelopeIntegrity = new Map(envelopes.map((envelope) => [envelope.artifactId, envelope.integrityStatus]));
|
|
644
|
+
const integrityOf = (claimId) => {
|
|
645
|
+
const claim = filters.accepted.find((entry) => entry.claimId === claimId);
|
|
646
|
+
if (claim === undefined)
|
|
647
|
+
return undefined;
|
|
648
|
+
const states = claim.evidence.map((entry) => envelopeIntegrity.get(entry.artifactId)).filter((state) => state !== undefined);
|
|
649
|
+
if (states.length === 0)
|
|
650
|
+
return undefined;
|
|
651
|
+
// The weakest link, not the best: a claim standing on one verified and one unverified artifact
|
|
652
|
+
// is a claim part of whose support was never checked, and reporting it as verified would let a
|
|
653
|
+
// single unchecked co-citation ride in on a verified one.
|
|
654
|
+
return states.includes("failed") ? "failed" : states.includes("unverified") ? "unverified" : "verified";
|
|
655
|
+
};
|
|
656
|
+
const routed = routeEscalations({ conflicts, authorization, requestingAgent: analysis.requestingAgent, integrityOf, now, trace });
|
|
657
|
+
const escalations = routed.escalations;
|
|
658
|
+
// The outcome rewrite is applied to a *copy*; the `conflict` trace events already recorded what the
|
|
659
|
+
// detector concluded, and both facts stay in the log (see `applyEscalationOutcomes`).
|
|
660
|
+
//
|
|
661
|
+
// Order matters and is not arbitrary: escalation runs **before** presentation, so that a conflict
|
|
662
|
+
// routed to a seat keeps its routing label rather than having it overwritten by
|
|
663
|
+
// `INCLUDE_BOTH_WITH_QUALIFICATION` — and `applyConflictPresentation` skips escalated records for
|
|
664
|
+
// the same reason from the other side. Reversing the two would silently un-route every escalation
|
|
665
|
+
// raised in an Elaria or Nytheria run, i.e. in exactly the two runs most likely to raise one.
|
|
666
|
+
conflicts = applyConflictPresentation(applyEscalationOutcomes(conflicts, routed.outcomeOverrides), profile.conflictPresentation);
|
|
667
|
+
ctx.transition("RESOLVE_OR_ESCALATE", {
|
|
668
|
+
byOutcome: conflicts.stats.byOutcome,
|
|
669
|
+
demoted: conflicts.stats.demoted,
|
|
670
|
+
unresolved: conflicts.stats.unresolved,
|
|
671
|
+
mandatory: conflicts.mandatory.size,
|
|
672
|
+
escalated: routed.stats.total,
|
|
673
|
+
byTarget: routed.stats.byTarget,
|
|
674
|
+
byRule: routed.stats.byRule,
|
|
675
|
+
selfDelivered: routed.stats.selfDelivered,
|
|
676
|
+
note: "conflict outcomes remain briefing-level: no resolution and no escalation mutates a store (design §11). ESCALATE_TO_ELARIA and ESCALATE_TO_RASKREIA are written by escalation.ts, which routes; detectConflicts still emits only DETERMINISTIC_CONFLICT_OUTCOMES. REQUEST_HUMAN_APPROVAL stays with approvals.ts, where a named human actually decides.",
|
|
677
|
+
});
|
|
678
|
+
/* --- SELECT_CONTEXT_SET --------------------------------------------------------------------- */
|
|
679
|
+
// `selection.gaps` are not appended here: `assembleBriefing` merges them itself (brief.ts:278), and
|
|
680
|
+
// adding them twice would double every budget gap in the delivered briefing.
|
|
681
|
+
const selection = selectContext({ candidates, conflicts, budget: plan.tokenBudget, policy, objective: analysis.objective, scaffoldingTokens: scaffolding, trace });
|
|
682
|
+
ctx.transition("SELECT_CONTEXT_SET", { selected: selection.stats.selected, excluded: selection.stats.excluded, byReason: selection.stats.byReason, budget: selection.budget, partial: selection.partial, stopReason: selection.stats.stopReason, iterations: selection.stats.iterations });
|
|
683
|
+
/* --- REQUEST_COMPRESSION -------------------------------------------------------------------- */
|
|
684
|
+
//
|
|
685
|
+
// Design §6 records this state as a no-op and spec §7 marks it "when needed". It is not needed and
|
|
686
|
+
// could not be honoured: §15's compression path is "request compression for eligible
|
|
687
|
+
// material", and no compaction source exists here, so there is no compressor to ask.
|
|
688
|
+
// Recording the state with the reason keeps the trace a faithful copy of the machine rather than a
|
|
689
|
+
// log of the states that happened to do work.
|
|
690
|
+
ctx.transition("REQUEST_COMPRESSION", { requested: false, reason: selection.partial ? "the briefing is partial, but no compaction source exists, so there is no compressor to request material from (design §1); the shortfall is disclosed as a retrieval gap instead" : "the selected context set fits the budget; no compression is needed", eligibleItems: 0 });
|
|
691
|
+
/* --- ASSEMBLE_BRIEFING ---------------------------------------------------------------------- */
|
|
692
|
+
const briefing = assembleBriefing({ runId: effectiveRunId, analysis, authorization, selection, conflicts, claims: deduped.claims, envelopes, graph, gaps, filterStats: filters.stats, quarantined: filters.quarantined, policy, redact: deps.redact, now, profile, policyMatchedBy: resolution.matchedBy, escalations });
|
|
693
|
+
const markdown = renderMarkdown(briefing, { selection });
|
|
694
|
+
ctx.transition("ASSEMBLE_BRIEFING", { status: briefing.status, items: selection.items.length, provenanceEntries: briefing.provenance.length, tokenUsage: briefing.token_usage, gaps: briefing.retrieval_gaps.length, renderedTokens: Math.ceil(markdown.length / 4) });
|
|
695
|
+
/* --- VALIDATE_BRIEFING ---------------------------------------------------------------------- */
|
|
696
|
+
const validation = validateBriefing(briefing, { claims: deduped.claims, rendered: markdown });
|
|
697
|
+
// Two events, deliberately. The `transition` keeps design §6's promise that *every* state appends
|
|
698
|
+
// one — a replay that indexes by transition must not find a hole here of all places — and the
|
|
699
|
+
// `validation` carries the violations, which is a different kind of record and a different consumer.
|
|
700
|
+
ctx.transition("VALIDATE_BRIEFING", { valid: validation.valid, checked: validation.checked, violations: validation.violations.length });
|
|
701
|
+
trace.append({ state: "VALIDATE_BRIEFING", event: "validation", at: clock(), payload: { valid: validation.valid, checked: validation.checked, violations: validation.violations } });
|
|
702
|
+
const stats = {
|
|
703
|
+
...partialStats(),
|
|
704
|
+
candidatesScored: ranked.stats.scored,
|
|
705
|
+
candidatesCapped,
|
|
706
|
+
itemsSelected: selection.items.length,
|
|
707
|
+
conflicts: conflicts.stats.conflicts,
|
|
708
|
+
elapsedMs: Date.now() - startedAt,
|
|
709
|
+
};
|
|
710
|
+
const complete = {
|
|
711
|
+
runId: request.runId,
|
|
712
|
+
outcome: "DELIVERED",
|
|
713
|
+
finalState: "COLLECT_FEEDBACK",
|
|
714
|
+
delivered: true,
|
|
715
|
+
briefing,
|
|
716
|
+
markdown,
|
|
717
|
+
validation,
|
|
718
|
+
analysis,
|
|
719
|
+
authorization,
|
|
720
|
+
plan,
|
|
721
|
+
policy,
|
|
722
|
+
gaps: briefing.retrieval_gaps,
|
|
723
|
+
sources,
|
|
724
|
+
claims: deduped.claims,
|
|
725
|
+
envelopes,
|
|
726
|
+
candidates,
|
|
727
|
+
graph,
|
|
728
|
+
conflicts,
|
|
729
|
+
selection,
|
|
730
|
+
filters,
|
|
731
|
+
situation,
|
|
732
|
+
intent,
|
|
733
|
+
requirements,
|
|
734
|
+
stats,
|
|
735
|
+
tracePath: trace.path,
|
|
736
|
+
reasons,
|
|
737
|
+
};
|
|
738
|
+
if (!validation.valid) {
|
|
739
|
+
// Fails closed (brief.ts:509-516). An uncertified briefing is not delivered and its rendering
|
|
740
|
+
// is withheld, because the whole point of the provenance gate is that unsourced text must not
|
|
741
|
+
// reach another agent's context. The briefing object is still returned, for the operator.
|
|
742
|
+
reasons.push(`VALIDATE_BRIEFING refused to certify the briefing: ${validation.violations.map((violation) => violation.code).join(", ")}`);
|
|
743
|
+
trace.append({ state: "VALIDATE_BRIEFING", event: "outcome", at: clock(), payload: { outcome: "INSUFFICIENT_INFORMATION", delivered: false, violations: validation.violations } });
|
|
744
|
+
return { ...complete, outcome: "INSUFFICIENT_INFORMATION", finalState: "VALIDATE_BRIEFING", delivered: false, markdown: null };
|
|
745
|
+
}
|
|
746
|
+
/* --- DELIVER / COLLECT_FEEDBACK ------------------------------------------------------------- */
|
|
747
|
+
const partial = briefing.status === "partial";
|
|
748
|
+
if (partial)
|
|
749
|
+
reasons.push(`the briefing is partial: ${briefing.retrieval_gaps.map((gap) => `${gap.sourceId}/${gap.reason}`).join(", ") || "selection dropped material"}`);
|
|
750
|
+
else
|
|
751
|
+
reasons.push(`complete briefing: ${selection.items.length} item(s) over ${briefing.provenance.length} claim(s), ${briefing.token_usage.used}/${briefing.token_usage.budget} tokens`);
|
|
752
|
+
ctx.transition("DELIVER", { status: briefing.status, delivered: true, items: selection.items.length, tokens: briefing.token_usage.used, gaps: briefing.retrieval_gaps.map((gap) => `${gap.sourceId}/${gap.reason}`) });
|
|
753
|
+
ctx.transition("COLLECT_FEEDBACK", { collected: false, reason: "feedback is submitted out of band by the consuming agent via submitFeedback(); design §22 forbids updating a production policy from it online" });
|
|
754
|
+
trace.append({ state: "COLLECT_FEEDBACK", event: "outcome", at: clock(), payload: { outcome: partial ? "PARTIAL_BRIEFING" : "DELIVERED", elapsedMs: stats.elapsedMs, retrievalMs, reasons } });
|
|
755
|
+
return { ...complete, outcome: partial ? "PARTIAL_BRIEFING" : "DELIVERED" };
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Runs the state machine end to end — one standard pass, or a bounded progressive loop around it.
|
|
759
|
+
*
|
|
760
|
+
* Without `deps.progressive` this is exactly `runSinglePass` and nothing else: Phase A and Phase B
|
|
761
|
+
* behavior is byte-identical to the pre-Phase-C build, and no field the older callers read changes.
|
|
762
|
+
*
|
|
763
|
+
* With `deps.progressive`, the pass becomes round 0 of `progressive.ts`'s bounded loop. Round 0 runs
|
|
764
|
+
* first *outside* the loop because its Phase B knowledge requirements are an input to the loop
|
|
765
|
+
* policy (`evaluateCoverage` needs requirements and evidence to compare), not an output of it; the
|
|
766
|
+
* already-computed result is handed back in as round 0 so it is never computed twice. A run that
|
|
767
|
+
* ended before selection produced evidence cannot be helped by another round — every early exit up
|
|
768
|
+
* to that point is derived from the request alone and will recur identically — so it is returned
|
|
769
|
+
* as-is rather than fed through coverage evaluation it cannot meaningfully enter.
|
|
770
|
+
*
|
|
771
|
+
* Each further round is a full `runSinglePass` under its own trace file
|
|
772
|
+
* (``<runId>-r<n>`` — trace.ts's runId pattern allows the suffix), with the previous round's gap
|
|
773
|
+
* terms appended to the curated any-match set. The delivered answer is the best round's own
|
|
774
|
+
* `OrchestrationResult`, carrying the sufficiency report on `.progressive`; the report describes
|
|
775
|
+
* what that round delivered, not the cumulative merge (see `runProgressiveRetrieval`).
|
|
776
|
+
*/
|
|
777
|
+
/**
|
|
778
|
+
* The escalation bound the locked Phase C production policy names (operator decision, 2026-08-22):
|
|
779
|
+
* selective escalation with a two-round hard cap. `budgetPerRoundRatio` is carried because
|
|
780
|
+
* `ProgressiveConfig` requires it; `runProgressiveRetrieval` reads only `maxRounds`, and 1 — every
|
|
781
|
+
* round gets the caller's full budget — is the neutral value an explicit config would have meant.
|
|
782
|
+
*/
|
|
783
|
+
export const DEFAULT_ESCALATION_CONFIG = { maxRounds: 2, budgetPerRoundRatio: 1 };
|
|
784
|
+
export function runBriefing(request, deps) {
|
|
785
|
+
const round0 = runSinglePass(request, deps);
|
|
786
|
+
// **The default escalation gate (locked Phase C production policy).** Without an explicit config,
|
|
787
|
+
// a Conclave seat whose governance block says `verification: "required"` escalates when round 0
|
|
788
|
+
// left knowledge requirements uncovered; everyone else keeps the single pass. The invariant that
|
|
789
|
+
// makes this free where it does not help: round 0 covering every requirement stops the loop on
|
|
790
|
+
// `SUFFICIENT_EVIDENCE` (or the round bound) without issuing a second query, and an early exit
|
|
791
|
+
// before selection never enters the loop at all.
|
|
792
|
+
let progressiveConfig = deps.progressive;
|
|
793
|
+
if (progressiveConfig === undefined) {
|
|
794
|
+
const verificationRequired = profileFor(resolveAgent(round0.analysis.requestingAgent).agent).verification === "required";
|
|
795
|
+
if (!(round0.requirements.length > 0 && verificationRequired))
|
|
796
|
+
return round0;
|
|
797
|
+
progressiveConfig = DEFAULT_ESCALATION_CONFIG;
|
|
798
|
+
}
|
|
799
|
+
const canProgress = round0.requirements.length > 0 && round0.selection !== null;
|
|
800
|
+
if (!canProgress)
|
|
801
|
+
return round0;
|
|
802
|
+
// Rounds are memoized by number: runProgressiveRetrieval re-requests round 0, which is the pass
|
|
803
|
+
// already computed above, and each later round must be built exactly once so its trace file has
|
|
804
|
+
// one writer and the memoized result is the one whose briefing gets selected.
|
|
805
|
+
const roundsByNumber = new Map([[0, round0]]);
|
|
806
|
+
const orchestrateFn = (round, gapTerms, traversalTerms) => {
|
|
807
|
+
const memoized = roundsByNumber.get(round);
|
|
808
|
+
if (memoized !== undefined)
|
|
809
|
+
return memoized;
|
|
810
|
+
// Keep the suffixed id inside trace.ts's 128-char pattern even for a maximal caller runId.
|
|
811
|
+
const suffix = `-r${round}`;
|
|
812
|
+
const base = request.runId.length + suffix.length > 128 ? request.runId.slice(0, 128 - suffix.length) : request.runId;
|
|
813
|
+
const result = runSinglePass(request, deps, gapTerms ?? [], traversalTerms ?? [], `${base}${suffix}`);
|
|
814
|
+
roundsByNumber.set(round, result);
|
|
815
|
+
return result;
|
|
816
|
+
};
|
|
817
|
+
const progressive = runProgressiveRetrieval(orchestrateFn, round0.requirements, progressiveConfig);
|
|
818
|
+
let best = round0;
|
|
819
|
+
for (const result of roundsByNumber.values())
|
|
820
|
+
if (result.briefing !== null && result.briefing === progressive.finalBriefing)
|
|
821
|
+
best = result;
|
|
822
|
+
return { ...best, progressive };
|
|
823
|
+
}
|
|
824
|
+
/** Design §18 risk 3: above this share of unrecognized summary headings, the grammar has drifted. */
|
|
825
|
+
export const SUMMARY_DRIFT_WARNING = 0.2;
|
|
826
|
+
function tally(values) {
|
|
827
|
+
const counts = {};
|
|
828
|
+
for (const value of values)
|
|
829
|
+
counts[value] = (counts[value] ?? 0) + 1;
|
|
830
|
+
return counts;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Reconstructs the inclusion or exclusion story for one claim from the run's JSONL alone.
|
|
834
|
+
*
|
|
835
|
+
* Reads only the trace file — not the databases — which is what makes design §14's claim that the
|
|
836
|
+
* audit is replayable true rather than aspirational: a run whose corpus has since changed still
|
|
837
|
+
* explains itself. A trace that a crash truncated is read as far as it goes (`trace.ts:139-163`) and
|
|
838
|
+
* the shortfall is reported rather than thrown.
|
|
839
|
+
*/
|
|
840
|
+
export function explainDecision(runId, claimId, root) {
|
|
841
|
+
const read = readTrace(runId, root);
|
|
842
|
+
const matches = (event) => {
|
|
843
|
+
if (claimId === null)
|
|
844
|
+
return false;
|
|
845
|
+
const payload = event.payload;
|
|
846
|
+
if (payload.claimId === claimId)
|
|
847
|
+
return true;
|
|
848
|
+
if (Array.isArray(payload.claimIds) && payload.claimIds.includes(claimId))
|
|
849
|
+
return true;
|
|
850
|
+
if (Array.isArray(payload.supersededClaimIds) && payload.supersededClaimIds.includes(claimId))
|
|
851
|
+
return true;
|
|
852
|
+
return false;
|
|
853
|
+
};
|
|
854
|
+
const events = claimId === null ? [] : read.events.filter(matches);
|
|
855
|
+
const outcomeEvent = [...read.events].reverse().find((event) => event.event === "outcome");
|
|
856
|
+
return {
|
|
857
|
+
runId,
|
|
858
|
+
claimId,
|
|
859
|
+
found: read.events.length > 0,
|
|
860
|
+
timeline: read.events
|
|
861
|
+
.filter((event) => event.event === "transition" || event.event === "outcome")
|
|
862
|
+
.map((event) => ({ seq: event.seq, state: event.state, event: event.event, summary: summarize(event) })),
|
|
863
|
+
events,
|
|
864
|
+
outcome: outcomeEvent === undefined ? null : String(outcomeEvent.payload.outcome ?? "(none recorded)"),
|
|
865
|
+
policyId: read.events.find((event) => event.policyId !== null)?.policyId ?? null,
|
|
866
|
+
truncated: read.truncated,
|
|
867
|
+
skippedLines: read.skippedLines,
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
function summarize(event) {
|
|
871
|
+
const payload = event.payload;
|
|
872
|
+
const parts = [];
|
|
873
|
+
for (const key of ["outcome", "earlyExit", "selected", "rejected", "envelopes", "claims", "in", "out", "scored", "conflicts", "status", "reason", "requested", "delivered"]) {
|
|
874
|
+
const value = payload[key];
|
|
875
|
+
if (value === undefined)
|
|
876
|
+
continue;
|
|
877
|
+
parts.push(`${key}=${Array.isArray(value) ? `[${value.length}]` : typeof value === "object" ? JSON.stringify(value).slice(0, 80) : String(value)}`);
|
|
878
|
+
}
|
|
879
|
+
return parts.join(" ") || "(no summary fields)";
|
|
880
|
+
}
|
|
881
|
+
/** Past this size the oldest lines are dropped on the next write, down to half of it. */
|
|
882
|
+
export const FEEDBACK_MAX_BYTES = 2 * 1024 * 1024;
|
|
883
|
+
export function submitFeedback(entry, path) {
|
|
884
|
+
const { agent, ...raw } = entry;
|
|
885
|
+
// The free-text fields come from a model and go to disk, so they pass through the same credential scrub as memories.
|
|
886
|
+
const rest = {
|
|
887
|
+
...raw,
|
|
888
|
+
...(raw.missingEvidence === undefined ? {} : { missingEvidence: redactSensitive(raw.missingEvidence) }),
|
|
889
|
+
...(raw.validatorDisagreement === undefined ? {} : { validatorDisagreement: redactSensitive(raw.validatorDisagreement) }),
|
|
890
|
+
...(raw.comment === undefined ? {} : { comment: redactSensitive(raw.comment) }),
|
|
891
|
+
...(raw.externalFindings === undefined ? {} : { externalFindings: raw.externalFindings.map((item) => ({ ...item, source: redactSensitive(item.source), finding: redactSensitive(item.finding), ...(item.version === undefined ? {} : { version: redactSensitive(item.version) }) })) }),
|
|
892
|
+
...(raw.costObservations === undefined ? {} : { costObservations: raw.costObservations.map((item) => ({ ...item, metric: redactSensitive(item.metric), unit: redactSensitive(item.unit) })) }),
|
|
893
|
+
};
|
|
894
|
+
const full = {
|
|
895
|
+
schemaVersion: FEEDBACK_SCHEMA_VERSION,
|
|
896
|
+
at: entry.at ?? Date.now(),
|
|
897
|
+
agent,
|
|
898
|
+
resolvedAgent: resolveAgent(agent).agent,
|
|
899
|
+
...rest,
|
|
900
|
+
// Computed here rather than by the caller: a validation verdict a caller could supply is a
|
|
901
|
+
// verdict a caller could supply falsely, and the whole value of the field is that an offline
|
|
902
|
+
// pass can trust it without re-deriving the expectation set for every historical seat version.
|
|
903
|
+
validation: validateFeedback(agent, rest),
|
|
904
|
+
};
|
|
905
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
906
|
+
try {
|
|
907
|
+
const size = statSync(path).size;
|
|
908
|
+
if (size > FEEDBACK_MAX_BYTES) {
|
|
909
|
+
// Drop whole oldest lines until about half the bytes remain, then swap the file in so a crash never loses the log.
|
|
910
|
+
const lines = readFileSync(path, "utf8").split("\n").filter((line) => line !== "");
|
|
911
|
+
let kept = 0;
|
|
912
|
+
let from = lines.length;
|
|
913
|
+
while (from > 0 && kept + Buffer.byteLength(lines[from - 1]) + 1 <= size / 2)
|
|
914
|
+
kept += Buffer.byteLength(lines[--from]) + 1;
|
|
915
|
+
const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
|
|
916
|
+
writeFileSync(tmp, lines.slice(from).map((line) => `${line}\n`).join(""), "utf8");
|
|
917
|
+
renameSync(tmp, path);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
catch (error) {
|
|
921
|
+
if (error.code !== "ENOENT")
|
|
922
|
+
throw error;
|
|
923
|
+
}
|
|
924
|
+
appendFileSync(path, `${JSON.stringify(full)}\n`, "utf8");
|
|
925
|
+
return full;
|
|
926
|
+
}
|