-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolver.ts
More file actions
301 lines (267 loc) · 9.93 KB
/
Copy pathresolver.ts
File metadata and controls
301 lines (267 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// The pure-code Resolver. No LLM. No network. No randomness.
// Same artifact + same evidence chain => same resolutions, every time.
import { runGates, type Gate } from "./gates";
import type {
DialecticArtifact,
DialecticReceipt,
EvidenceChainItem,
Objection,
ObjectionSeverity,
Resolution,
ResolverConfig,
ResolverResult,
SourceKind,
} from "./types";
const SEVERITY_ORDER: Record<ObjectionSeverity, number> = {
BLOCKING: 0,
HIGH: 1,
MEDIUM: 2,
LOW: 3,
};
const FRESHNESS_OK_FOR_FRESH_RESEARCH = new Set(["live", "recent"]);
const RESOLVED_ACTIONS = new Set([
"accepted-revision",
"evidence-upgraded",
"rejected-with-reason",
"deferred",
]);
function bySeverity(a: Objection, b: Objection): number {
return SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
}
function hashJson(value: unknown): string {
// Cheap stable hash; fine for receipt inputHash. Swap for a real hash in prod.
const s = JSON.stringify(value, Object.keys(value as object).sort());
let h = 0;
for (let i = 0; i < s.length; i++) {
h = (h * 31 + s.charCodeAt(i)) | 0;
}
return `h${(h >>> 0).toString(16)}`;
}
function makeReceipt(
kind: DialecticReceipt["receiptKind"],
artifact: DialecticArtifact,
payload: Record<string, unknown>,
): DialecticReceipt {
return {
receiptId: `r_${Date.now().toString(36)}_${Math.random()
.toString(36)
.slice(2, 8)}`,
receiptKind: kind,
artifactId: artifact.artifactId,
stage: artifact.stage,
timestamp: new Date().toISOString(),
inputHash: hashJson({
proposal: artifact.proposal,
objections: artifact.objections,
evidenceChain: artifact.evidenceChain,
}),
payload,
};
}
function replaceOrPush(arr: Resolution[], r: Resolution): void {
const i = arr.findIndex(x => x.objectionId === r.objectionId);
if (i >= 0) arr[i] = r;
else arr.push(r);
}
function authorityRankOf(
kind: SourceKind,
config: ResolverConfig,
): number {
return config.authorityRank[kind];
}
/** Step 1: Did the latest Proposer revision touch the data path the objection targets? */
function tryAcceptedRevision(
objection: Objection,
artifact: DialecticArtifact,
): Resolution | null {
if (!objection.targetFieldPath) return null;
const field = artifact.proposal.fields[objection.targetFieldPath];
if (!field) return null;
// If the proposal is a revision and the target field exists, accept.
// Domains can override this with a smarter "was the field actually touched" check.
if (artifact.proposal.revisionOf) {
return {
objectionId: objection.objectionId,
action: "accepted-revision",
note: `Proposer revision updated field "${objection.targetFieldPath}".`,
revisionDelta: { [objection.targetFieldPath]: field.value },
};
}
return null;
}
/** Step 2: Has new evidence cleared the threshold for this objection? */
function tryEvidenceUpgraded(
objection: Objection,
artifact: DialecticArtifact,
evidenceChain: EvidenceChainItem[],
config: ResolverConfig,
): Resolution | null {
const threshold = config.thresholdsByCategory[objection.category];
if (threshold == null) return null; // unknown category — be conservative, hold
const allowedKinds = new Set(config.minSourceKindForSeverity[objection.severity]);
// Evidence that targets either the objection's evidenceRefs OR the field path.
const candidates = evidenceChain.filter(e => {
const refsObjection =
objection.evidenceRefs.includes(e.id) ||
(objection.targetFieldPath
? artifact.proposal.fields[objection.targetFieldPath]?.evidenceRefs.includes(e.id)
: false);
return refsObjection && allowedKinds.has(e.sourceKind);
});
// Rank candidates: highest authority first (lowest rank number), then highest confidence.
candidates.sort((a, b) => {
const ra = authorityRankOf(a.sourceKind, config);
const rb = authorityRankOf(b.sourceKind, config);
if (ra !== rb) return ra - rb;
return b.confidence - a.confidence;
});
for (const e of candidates) {
if (e.confidence < threshold) continue;
if (e.sourceKind === "fresh-research" && !FRESHNESS_OK_FOR_FRESH_RESEARCH.has(e.freshness)) {
continue;
}
if (e.sourceKind === "llm-inference") continue; // never resolves anything alone
if (e.sourceKind === "modeled-fallback" && objection.severity === "BLOCKING") continue;
return {
objectionId: objection.objectionId,
action: "evidence-upgraded",
note: `Evidence ${e.id} (${e.sourceKind}, conf ${e.confidence.toFixed(2)}) cleared threshold ${threshold} for category "${objection.category}".`,
triggeringEvidenceId: e.id,
};
}
return null;
}
/** Step 3: Non-blocking, deferred to a later stage by the proposal. */
function tryDeferred(
objection: Objection,
artifact: DialecticArtifact,
): Resolution | null {
if (objection.severity === "BLOCKING") return null;
if (!objection.targetFieldPath) return null;
const deferral = artifact.proposal.defersToStage?.[objection.targetFieldPath];
if (!deferral) return null;
return {
objectionId: objection.objectionId,
action: "deferred",
note: `Proposal defers field "${objection.targetFieldPath}" to stage "${deferral}".`,
};
}
/** Step 4: Proposer cited contradicting evidence that outranks the objection's evidence. */
function tryRejectedWithReason(
objection: Objection,
artifact: DialecticArtifact,
evidenceChain: EvidenceChainItem[],
config: ResolverConfig,
): Resolution | null {
if (!objection.targetFieldPath) return null;
const field = artifact.proposal.fields[objection.targetFieldPath];
if (!field) return null;
const objectionEvidence = evidenceChain.filter(e =>
objection.evidenceRefs.includes(e.id),
);
if (objectionEvidence.length === 0) return null;
const bestObjectionRank = Math.min(
...objectionEvidence.map(e => authorityRankOf(e.sourceKind, config)),
);
const proposalEvidence = evidenceChain.filter(e =>
field.evidenceRefs.includes(e.id),
);
const contradicting = proposalEvidence.find(
e =>
authorityRankOf(e.sourceKind, config) < bestObjectionRank &&
e.sourceKind !== "llm-inference",
);
if (!contradicting) return null;
return {
objectionId: objection.objectionId,
action: "rejected-with-reason",
note: `Proposal cites ${contradicting.sourceKind} evidence "${contradicting.id}" which outranks the objection's evidence in the Authority Hierarchy.`,
triggeringEvidenceId: contradicting.id,
};
}
function tryResolve(
objection: Objection,
artifact: DialecticArtifact,
evidenceChain: EvidenceChainItem[],
config: ResolverConfig,
): Resolution | null {
// Order matters. Prefer the verdict that names the *actual* reason the
// objection cleared. Evidence beats a revision-shape match.
return (
tryEvidenceUpgraded(objection, artifact, evidenceChain, config) ||
tryRejectedWithReason(objection, artifact, evidenceChain, config) ||
tryAcceptedRevision(objection, artifact) ||
tryDeferred(objection, artifact) ||
null
);
}
export interface RunDialecticResolverInput {
artifact: DialecticArtifact;
evidenceChain: EvidenceChainItem[];
config: ResolverConfig;
gates?: Gate[];
}
export function runDialecticResolver(
input: RunDialecticResolverInput,
): ResolverResult {
const out: DialecticArtifact = structuredClone(input.artifact);
out.evidenceChain = input.evidenceChain;
out.revisedAt = new Date().toISOString();
const receipts: DialecticReceipt[] = [];
for (const objection of [...out.objections].sort(bySeverity)) {
const existing = out.resolutions.find(
r => r.objectionId === objection.objectionId,
);
if (existing && RESOLVED_ACTIONS.has(existing.action)) continue;
const resolution = tryResolve(
objection,
out,
input.evidenceChain,
input.config,
);
if (resolution) {
replaceOrPush(out.resolutions, resolution);
receipts.push(
makeReceipt("resolution-applied", out, {
objectionId: objection.objectionId,
action: resolution.action,
triggeringEvidenceId: resolution.triggeringEvidenceId ?? null,
}),
);
}
}
out.validation = runGates(out, input.evidenceChain, input.gates);
const stillBlocking = out.objections.some(o => {
if (o.severity !== "BLOCKING") return false;
const r = out.resolutions.find(x => x.objectionId === o.objectionId);
return !r || !RESOLVED_ACTIONS.has(r.action) || r.action === "deferred";
});
if (!out.validation.readyToAdvance) {
receipts.push(
makeReceipt("gate-failed", out, {
gatesFailed: out.validation.gatesFailed,
blockingObjectionsOpen: out.validation.blockingObjectionsOpen,
}),
);
}
const roundsSoFar = out.roundsSoFar ?? 0;
const needsAnotherRound = stillBlocking && roundsSoFar < input.config.maxRounds;
if (stillBlocking && !needsAnotherRound) {
receipts.push(
makeReceipt("escalation", out, {
reason: "Blocking objections remain after maxRounds. Routing to human review.",
}),
);
}
receipts.unshift(
makeReceipt("dialectic-pass", out, {
roundsSoFar,
resolutionsApplied: receipts.filter(r => r.receiptKind === "resolution-applied").length,
}),
);
return {
artifact: out,
receipts,
needsAnotherRound,
};
}