@principles/host-runtime 4.10.0 → 4.12.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/dist/auto-pain-authorization.js +6 -1
- package/dist/conversation-ingestion/consent.d.ts +33 -7
- package/dist/conversation-ingestion/consent.js +240 -42
- package/dist/conversation-ingestion/disclosure.d.ts +21 -0
- package/dist/conversation-ingestion/disclosure.js +74 -0
- package/dist/conversation-ingestion/index.d.ts +1 -0
- package/dist/conversation-ingestion/index.js +1 -0
- package/dist/forward-observation.d.ts +29 -0
- package/dist/forward-observation.js +279 -0
- package/dist/governance-signal-admission.d.ts +6 -1
- package/dist/governance-signal-admission.js +77 -11
- package/dist/idle-turn-audit.d.ts +155 -0
- package/dist/idle-turn-audit.js +786 -0
- package/dist/idle-turn-auditor.d.ts +20 -0
- package/dist/idle-turn-auditor.js +249 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.js +38 -8
- package/dist/pain-inbox.d.ts +137 -0
- package/dist/pain-inbox.js +1020 -0
- package/dist/production-pain-evidence.d.ts +2 -2
- package/dist/production-pain-evidence.js +301 -55
- package/dist/signal-stage2-cycle.d.ts +2 -0
- package/dist/signal-stage2-cycle.js +30 -1
- package/dist/source-revocation-sweep.js +38 -0
- package/dist/stage2-context-hydrator.d.ts +46 -0
- package/dist/stage2-context-hydrator.js +221 -0
- package/dist/trajectory-stall-detector.d.ts +124 -0
- package/dist/trajectory-stall-detector.js +583 -0
- package/package.json +3 -3
|
@@ -0,0 +1,1020 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unified Pain Inbox Service — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R2 (W3 & W4).
|
|
3
|
+
*
|
|
4
|
+
* Bridges BOTH storage authorities (`governance_signal_admissions` for
|
|
5
|
+
* Codex/WorkBuddy and `signal_confirmations` for OpenClaw) behind one
|
|
6
|
+
* Owner-facing Pain Inbox contract and converges ALL Owner approvals onto the
|
|
7
|
+
* single Canonical Admission spine (`pain_events` + Diagnostician task via
|
|
8
|
+
* `governance_signal_admissions` marker).
|
|
9
|
+
*
|
|
10
|
+
* Architectural invariants:
|
|
11
|
+
* - W3 (OpenClaw GSA Marker Bridge + Complete CAS State Machine):
|
|
12
|
+
* Never writes nonexistent columns (`canonical_pain_id`, `diagnostician_task_id`)
|
|
13
|
+
* to `signal_confirmations`. When an Owner approves an OpenClaw confirmation,
|
|
14
|
+
* a unified GSA Admission Marker (`host_kind='openclaw'`,
|
|
15
|
+
* `logical_observation_key='openclaw:confirmation:<id>'`) is created/bound
|
|
16
|
+
* inside `governance_signal_admissions` to own the canonical pain ID,
|
|
17
|
+
* Diagnostician task ID, `ownerApproval`, and cross-DB reconciliation.
|
|
18
|
+
* State transitions:
|
|
19
|
+
* `inbox_candidate` --(CAS claim_token)--> `inbox_approving`
|
|
20
|
+
* `inbox_approving` --(Canonical Admission)--> `inbox_approved` (idempotent terminal)
|
|
21
|
+
* Stale `inbox_approving` (>10m claim TTL) recovers: resumes task creation if
|
|
22
|
+
* `canonical_pain_id` already landed, else reverts safely to `inbox_candidate`.
|
|
23
|
+
* - P2-1 (Neutral Correction Guard):
|
|
24
|
+
* Calm neutral corrections (`acknowledgeOnly: true`) transition to terminal
|
|
25
|
+
* `acknowledged_observation` without escalating into a formal Pain row.
|
|
26
|
+
* - W4 (Explicit Terminal `source_revoked`):
|
|
27
|
+
* `listPainInboxItems()` and `admitOwnerApprovedInboxCandidate()` strictly
|
|
28
|
+
* exclude `source_revoked` rows and re-verify `readSourceMaterialAuthorization()`
|
|
29
|
+
* live before admitting.
|
|
30
|
+
*/
|
|
31
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
32
|
+
import fs from 'node:fs';
|
|
33
|
+
import path from 'node:path';
|
|
34
|
+
import Database from 'better-sqlite3';
|
|
35
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
36
|
+
import { evaluatePainIngress, } from '@principles/core/runtime';
|
|
37
|
+
import { readSourceMaterialAuthorization } from './source-material-authorization.js';
|
|
38
|
+
import { ensureGovernanceDiagnosticianTask } from './governance-signal-admission.js';
|
|
39
|
+
export const PAIN_INBOX_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
40
|
+
export const PAIN_INBOX_APPROVING_TTL_MS = 10 * 60 * 1000;
|
|
41
|
+
function isRecord(value) {
|
|
42
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
function own(value, key) {
|
|
45
|
+
return Object.hasOwn(value, key) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
|
|
46
|
+
}
|
|
47
|
+
function isNullableString(value) {
|
|
48
|
+
return typeof value === 'string' || value === null;
|
|
49
|
+
}
|
|
50
|
+
function isGsaInboxListRow(value) {
|
|
51
|
+
if (!isRecord(value))
|
|
52
|
+
return false;
|
|
53
|
+
return typeof own(value, 'logical_observation_key') === 'string'
|
|
54
|
+
&& typeof own(value, 'host_kind') === 'string'
|
|
55
|
+
&& typeof own(value, 'root_session_id') === 'string'
|
|
56
|
+
&& typeof own(value, 'signal_kind') === 'string'
|
|
57
|
+
&& typeof own(value, 'decision') === 'string'
|
|
58
|
+
&& isNullableString(own(value, 'reason'))
|
|
59
|
+
&& isNullableString(own(value, 'task_payload_json'))
|
|
60
|
+
&& typeof own(value, 'created_at') === 'string';
|
|
61
|
+
}
|
|
62
|
+
function isGsaAdmissionRow(value) {
|
|
63
|
+
return isGsaInboxListRow(value)
|
|
64
|
+
&& typeof own(value, 'id') === 'number'
|
|
65
|
+
&& typeof own(value, 'rollout_identity') === 'string'
|
|
66
|
+
&& isNullableString(own(value, 'canonical_pain_id'))
|
|
67
|
+
&& isNullableString(own(value, 'diagnostician_task_id'));
|
|
68
|
+
}
|
|
69
|
+
function isOpenClawInboxRow(value) {
|
|
70
|
+
if (!isRecord(value))
|
|
71
|
+
return false;
|
|
72
|
+
return typeof own(value, 'id') === 'string'
|
|
73
|
+
&& typeof own(value, 'session_id') === 'string'
|
|
74
|
+
&& typeof own(value, 'excerpt') === 'string'
|
|
75
|
+
&& isNullableString(own(value, 'resolution'))
|
|
76
|
+
&& typeof own(value, 'created_at') === 'string';
|
|
77
|
+
}
|
|
78
|
+
function isOpenClawConfirmationRow(value) {
|
|
79
|
+
return isOpenClawInboxRow(value) && typeof own(value, 'status') === 'string';
|
|
80
|
+
}
|
|
81
|
+
function isGsaBridgeMarkerRow(value) {
|
|
82
|
+
if (!isRecord(value))
|
|
83
|
+
return false;
|
|
84
|
+
return typeof own(value, 'decision') === 'string'
|
|
85
|
+
&& isNullableString(own(value, 'canonical_pain_id'))
|
|
86
|
+
&& isNullableString(own(value, 'diagnostician_task_id'))
|
|
87
|
+
&& isNullableString(own(value, 'task_payload_json'));
|
|
88
|
+
}
|
|
89
|
+
function tableExists(db, name) {
|
|
90
|
+
return (db
|
|
91
|
+
.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1")
|
|
92
|
+
.get(name) !== undefined);
|
|
93
|
+
}
|
|
94
|
+
function readGsaBridgeMarker(db, logicalObservationKey) {
|
|
95
|
+
const raw = db
|
|
96
|
+
.prepare('SELECT decision, canonical_pain_id, diagnostician_task_id, task_payload_json FROM governance_signal_admissions WHERE logical_observation_key = ? LIMIT 1')
|
|
97
|
+
.get(logicalObservationKey);
|
|
98
|
+
if (raw === undefined)
|
|
99
|
+
return undefined;
|
|
100
|
+
if (!isGsaBridgeMarkerRow(raw))
|
|
101
|
+
throw new Error('gsa_bridge_marker_row_malformed');
|
|
102
|
+
return raw;
|
|
103
|
+
}
|
|
104
|
+
function parseJsonSafe(raw) {
|
|
105
|
+
if (!raw)
|
|
106
|
+
return null;
|
|
107
|
+
try {
|
|
108
|
+
const parsed = JSON.parse(raw);
|
|
109
|
+
return isRecord(parsed) ? parsed : null;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function firstEvidenceEntry(sourceRef, note) {
|
|
116
|
+
const entry = { kind: 'behavior_trace', sourceRef, note: note.slice(0, 500) };
|
|
117
|
+
return { status: 'available', entries: [entry] };
|
|
118
|
+
}
|
|
119
|
+
function parseDeviationAnchor(value) {
|
|
120
|
+
if (!isRecord(value))
|
|
121
|
+
return null;
|
|
122
|
+
return typeof value.principleId === 'string' && typeof value.principleVersion === 'string'
|
|
123
|
+
? { principleId: value.principleId, principleVersion: value.principleVersion }
|
|
124
|
+
: null;
|
|
125
|
+
}
|
|
126
|
+
function extractInboxSignalKind(payload, fallback) {
|
|
127
|
+
const inbox = isRecord(payload.inbox) ? payload.inbox : null;
|
|
128
|
+
if (inbox && typeof inbox.signalKind === 'string')
|
|
129
|
+
return inbox.signalKind;
|
|
130
|
+
if (typeof payload.signalKind === 'string')
|
|
131
|
+
return payload.signalKind;
|
|
132
|
+
return fallback;
|
|
133
|
+
}
|
|
134
|
+
function extractInboxExcerpt(payload) {
|
|
135
|
+
const trigger = isRecord(payload.trigger) ? payload.trigger : null;
|
|
136
|
+
if (trigger && typeof trigger.text === 'string' && trigger.text.trim().length > 0)
|
|
137
|
+
return trigger.text;
|
|
138
|
+
if (typeof payload.excerpt === 'string' && payload.excerpt.trim().length > 0)
|
|
139
|
+
return payload.excerpt;
|
|
140
|
+
return '';
|
|
141
|
+
}
|
|
142
|
+
function firstNumericId(value) {
|
|
143
|
+
if (!Array.isArray(value))
|
|
144
|
+
return null;
|
|
145
|
+
for (const item of value)
|
|
146
|
+
if (typeof item === 'number' && Number.isFinite(item))
|
|
147
|
+
return item;
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
function syntheticObservationKey(args) {
|
|
151
|
+
return `${args.hostKind === 'workbuddy' ? 'wb' : args.hostKind}|${args.rolloutIdentity}|${args.hostTurnId}|${args.suffix}`;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Build and evaluate the ONE canonical ingress report for an inbox admission.
|
|
155
|
+
* The approve click is only the Owner gate; it must not bypass ingress
|
|
156
|
+
* semantics, evidence requirements, host binding, or pain-type mapping.
|
|
157
|
+
*/
|
|
158
|
+
function evaluateInboxCanonicalAdmission(args) {
|
|
159
|
+
const signalKind = extractInboxSignalKind(args.payload, args.fallbackSignalKind);
|
|
160
|
+
const painType = signalKind === 'trajectory_stall'
|
|
161
|
+
? 'tool_failure'
|
|
162
|
+
: signalKind === 'idle_audit_deviation'
|
|
163
|
+
? 'principle_deviation'
|
|
164
|
+
: 'user_frustration';
|
|
165
|
+
const excerpt = args.openclawExcerpt && args.openclawExcerpt.trim().length > 0
|
|
166
|
+
? args.openclawExcerpt
|
|
167
|
+
: extractInboxExcerpt(args.payload);
|
|
168
|
+
if (excerpt.trim().length === 0)
|
|
169
|
+
return { ok: false, reason: 'ingress_evidence_missing' };
|
|
170
|
+
let correlation;
|
|
171
|
+
let evidenceRef = `governance_observation:${args.logicalObservationKey}`;
|
|
172
|
+
if (args.hostKind === 'openclaw') {
|
|
173
|
+
correlation = { status: 'bound', hostKind: 'openclaw', sessionId: args.rootSessionId };
|
|
174
|
+
evidenceRef = args.openclawConfirmationId
|
|
175
|
+
? `signal_confirmation:${args.openclawConfirmationId}`
|
|
176
|
+
: `governance_observation:${args.logicalObservationKey}`;
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
let hostTurnId = null;
|
|
180
|
+
let lineageKey = args.logicalObservationKey;
|
|
181
|
+
if (signalKind === 'mid_confidence_correction' || args.fallbackSignalKind === 'user_correction') {
|
|
182
|
+
const trigger = isRecord(args.payload.trigger) ? args.payload.trigger : null;
|
|
183
|
+
hostTurnId = trigger && typeof trigger.hostTurnId === 'string' ? trigger.hostTurnId : null;
|
|
184
|
+
}
|
|
185
|
+
else if (signalKind === 'trajectory_stall') {
|
|
186
|
+
const latestToolCallId = firstNumericId(args.payload.toolCallIds);
|
|
187
|
+
if (latestToolCallId !== null && tableExists(args.db, 'tool_calls')) {
|
|
188
|
+
const row = args.db.prepare('SELECT turn_id FROM tool_calls WHERE id = ? LIMIT 1').get(latestToolCallId);
|
|
189
|
+
hostTurnId = isRecord(row) && typeof row.turn_id === 'string' ? row.turn_id : null;
|
|
190
|
+
if (hostTurnId !== null)
|
|
191
|
+
lineageKey = syntheticObservationKey({ hostKind: args.hostKind, rolloutIdentity: args.rolloutIdentity, hostTurnId, suffix: `stall:${latestToolCallId}` });
|
|
192
|
+
evidenceRef = `tool_call:${latestToolCallId}`;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
else if (signalKind === 'idle_audit_deviation') {
|
|
196
|
+
const match = /go:(\d+)$/.exec(args.logicalObservationKey);
|
|
197
|
+
if (match && tableExists(args.db, 'governance_observations')) {
|
|
198
|
+
const row = args.db.prepare('SELECT logical_key, host_turn_id FROM governance_observations WHERE id = ? LIMIT 1').get(Number(match[1]));
|
|
199
|
+
if (isRecord(row) && typeof row.logical_key === 'string' && typeof row.host_turn_id === 'string') {
|
|
200
|
+
lineageKey = row.logical_key;
|
|
201
|
+
hostTurnId = row.host_turn_id;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
evidenceRef = `idle_audit:${args.logicalObservationKey}`;
|
|
205
|
+
}
|
|
206
|
+
if (args.hostKind === 'codex') {
|
|
207
|
+
if (hostTurnId === null || !lineageKey.startsWith(`codex|${args.rolloutIdentity}|`)) {
|
|
208
|
+
return { ok: false, reason: 'ingress_lineage_unproven' };
|
|
209
|
+
}
|
|
210
|
+
correlation = {
|
|
211
|
+
status: 'bound',
|
|
212
|
+
hostKind: 'codex',
|
|
213
|
+
rootSessionId: args.rootSessionId,
|
|
214
|
+
rolloutIdentity: args.rolloutIdentity,
|
|
215
|
+
logicalObservationKey: lineageKey,
|
|
216
|
+
hostTurnId,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
correlation = {
|
|
221
|
+
status: 'bound',
|
|
222
|
+
hostKind: 'workbuddy',
|
|
223
|
+
sessionId: args.rootSessionId,
|
|
224
|
+
logicalObservationKey: lineageKey,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const deviationAnchor = painType === 'principle_deviation' ? parseDeviationAnchor(args.payload.deviationAnchor) : null;
|
|
229
|
+
if (painType === 'principle_deviation' && deviationAnchor === null) {
|
|
230
|
+
return { ok: false, reason: 'deviation_anchor_unproven' };
|
|
231
|
+
}
|
|
232
|
+
const report = {
|
|
233
|
+
identity: { kind: 'host_observation', observationId: args.painId },
|
|
234
|
+
painType,
|
|
235
|
+
source: signalKind,
|
|
236
|
+
reason: args.reason,
|
|
237
|
+
score: 75,
|
|
238
|
+
origin: { kind: 'automatic_hook', source: `${args.hostKind}:pain_inbox` },
|
|
239
|
+
correlation,
|
|
240
|
+
evidence: firstEvidenceEntry(evidenceRef, excerpt),
|
|
241
|
+
...(deviationAnchor ? { deviationAnchor } : {}),
|
|
242
|
+
};
|
|
243
|
+
const decision = evaluatePainIngress(report);
|
|
244
|
+
if (decision.action !== 'submit' && decision.action !== 'degrade') {
|
|
245
|
+
return { ok: false, reason: `ingress_${decision.action}:${decision.reasonCode}` };
|
|
246
|
+
}
|
|
247
|
+
return { ok: true, decision };
|
|
248
|
+
}
|
|
249
|
+
function openTrajectoryDb(workspaceDir, readonly, factory) {
|
|
250
|
+
const dbPath = resolveTrajectoryDbPath(workspaceDir);
|
|
251
|
+
if (!factory && !fs.existsSync(dbPath))
|
|
252
|
+
return null;
|
|
253
|
+
const db = factory
|
|
254
|
+
? factory(dbPath)
|
|
255
|
+
: new Database(dbPath, readonly ? { readonly: true, fileMustExist: true } : undefined);
|
|
256
|
+
db.pragma('busy_timeout = 5000');
|
|
257
|
+
return {
|
|
258
|
+
db,
|
|
259
|
+
close: () => {
|
|
260
|
+
try {
|
|
261
|
+
db.close();
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
// ignore close error
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function deriveInboxCanonicalPainId(hostKind, key) {
|
|
270
|
+
const digest = createHash('sha256')
|
|
271
|
+
.update(`pain_inbox:${hostKind}:${key}`)
|
|
272
|
+
.digest('hex')
|
|
273
|
+
.slice(0, 16);
|
|
274
|
+
return `pain_${hostKind}_inbox_${digest}`;
|
|
275
|
+
}
|
|
276
|
+
function parseItemId(itemId) {
|
|
277
|
+
if (itemId.startsWith('gsa:') && itemId.length > 4) {
|
|
278
|
+
return { source: 'gsa', rawKey: itemId.slice(4) };
|
|
279
|
+
}
|
|
280
|
+
if (itemId.startsWith('oc:') && itemId.length > 3) {
|
|
281
|
+
return { source: 'openclaw_confirmation', rawKey: itemId.slice(3) };
|
|
282
|
+
}
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
function isExpired(createdAt, nowMs) {
|
|
286
|
+
const ts = Date.parse(createdAt);
|
|
287
|
+
return Number.isFinite(ts) && nowMs - ts >= PAIN_INBOX_TTL_MS;
|
|
288
|
+
}
|
|
289
|
+
function computeExpiresAt(createdAt) {
|
|
290
|
+
const ts = Date.parse(createdAt);
|
|
291
|
+
if (!Number.isFinite(ts))
|
|
292
|
+
return new Date(Date.now() + PAIN_INBOX_TTL_MS).toISOString();
|
|
293
|
+
return new Date(ts + PAIN_INBOX_TTL_MS).toISOString();
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
|
|
297
|
+
* Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
|
|
298
|
+
* unauthorized hosts (fail-closed consent check).
|
|
299
|
+
*/
|
|
300
|
+
export function listPainInboxItems(input) {
|
|
301
|
+
const nowMs = (input.now ?? new Date()).getTime();
|
|
302
|
+
const opened = openTrajectoryDb(input.workspaceDir, true, input.databaseFactory);
|
|
303
|
+
if (!opened) {
|
|
304
|
+
return { ok: true, items: [], total: 0, byHost: { openclaw: 0, codex: 0, workbuddy: 0 } };
|
|
305
|
+
}
|
|
306
|
+
const { db, close } = opened;
|
|
307
|
+
try {
|
|
308
|
+
const items = [];
|
|
309
|
+
const authCache = new Map();
|
|
310
|
+
const isHostAuthorized = (hostKind) => {
|
|
311
|
+
const cached = authCache.get(hostKind);
|
|
312
|
+
if (cached !== undefined)
|
|
313
|
+
return cached;
|
|
314
|
+
// OpenClaw operates in-process without a separate transcript-ingestion
|
|
315
|
+
// consent prerequisite unless explicitly revoked in the ledger.
|
|
316
|
+
const auth = readSourceMaterialAuthorization({
|
|
317
|
+
workspaceDir: input.workspaceDir,
|
|
318
|
+
hostKind,
|
|
319
|
+
});
|
|
320
|
+
const allowed = hostKind === 'openclaw'
|
|
321
|
+
? auth.status === 'authorized' || auth.reason === 'consent_missing'
|
|
322
|
+
: auth.status === 'authorized';
|
|
323
|
+
authCache.set(hostKind, allowed);
|
|
324
|
+
return allowed;
|
|
325
|
+
};
|
|
326
|
+
// 1. Codex / WorkBuddy GSA inbox rows
|
|
327
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
328
|
+
const rows = db
|
|
329
|
+
.prepare(`SELECT logical_observation_key, host_kind, root_session_id, signal_kind,
|
|
330
|
+
decision, reason, task_payload_json, created_at
|
|
331
|
+
FROM governance_signal_admissions
|
|
332
|
+
WHERE decision IN ('inbox_candidate', 'inbox_approving')
|
|
333
|
+
ORDER BY created_at DESC`)
|
|
334
|
+
.all()
|
|
335
|
+
.filter(isGsaInboxListRow);
|
|
336
|
+
for (const row of rows) {
|
|
337
|
+
const hostKind = row.host_kind === 'workbuddy'
|
|
338
|
+
? 'workbuddy'
|
|
339
|
+
: row.host_kind === 'openclaw'
|
|
340
|
+
? 'openclaw'
|
|
341
|
+
: 'codex';
|
|
342
|
+
if (input.hostFilter && input.hostFilter !== hostKind)
|
|
343
|
+
continue;
|
|
344
|
+
if (!isHostAuthorized(hostKind))
|
|
345
|
+
continue;
|
|
346
|
+
if (isExpired(row.created_at, nowMs))
|
|
347
|
+
continue;
|
|
348
|
+
const payload = parseJsonSafe(row.task_payload_json);
|
|
349
|
+
const trigger = payload && isRecord(payload.trigger) ? payload.trigger : null;
|
|
350
|
+
const inbox = payload && isRecord(payload.inbox) ? payload.inbox : null;
|
|
351
|
+
const excerpt = trigger && typeof trigger.text === 'string'
|
|
352
|
+
? trigger.text.slice(0, 300)
|
|
353
|
+
: '';
|
|
354
|
+
const confidence = inbox && typeof inbox.confidence === 'number' ? inbox.confidence : null;
|
|
355
|
+
const signalKind = inbox && typeof inbox.signalKind === 'string'
|
|
356
|
+
? inbox.signalKind
|
|
357
|
+
: row.signal_kind || 'mid_confidence_correction';
|
|
358
|
+
items.push({
|
|
359
|
+
id: `gsa:${row.logical_observation_key}`,
|
|
360
|
+
source: 'gsa',
|
|
361
|
+
hostKind,
|
|
362
|
+
sessionId: row.root_session_id,
|
|
363
|
+
signalKind,
|
|
364
|
+
status: row.decision === 'inbox_approving' ? 'inbox_approving' : 'inbox_candidate',
|
|
365
|
+
excerpt,
|
|
366
|
+
confidence,
|
|
367
|
+
reason: row.reason,
|
|
368
|
+
createdAt: row.created_at,
|
|
369
|
+
expiresAt: computeExpiresAt(row.created_at),
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// 2. OpenClaw signal_confirmations inbox rows
|
|
374
|
+
if ((!input.hostFilter || input.hostFilter === 'openclaw') &&
|
|
375
|
+
isHostAuthorized('openclaw') &&
|
|
376
|
+
tableExists(db, 'signal_confirmations')) {
|
|
377
|
+
const rows = db
|
|
378
|
+
.prepare(`SELECT id, session_id, excerpt, resolution, created_at
|
|
379
|
+
FROM signal_confirmations
|
|
380
|
+
WHERE status = 'pending'
|
|
381
|
+
AND resolution IN ('inbox_candidate', 'inbox_approving')
|
|
382
|
+
ORDER BY created_at DESC`)
|
|
383
|
+
.all()
|
|
384
|
+
.filter(isOpenClawInboxRow);
|
|
385
|
+
for (const row of rows) {
|
|
386
|
+
if (isExpired(row.created_at, nowMs))
|
|
387
|
+
continue;
|
|
388
|
+
items.push({
|
|
389
|
+
id: `oc:${row.id}`,
|
|
390
|
+
source: 'openclaw_confirmation',
|
|
391
|
+
hostKind: 'openclaw',
|
|
392
|
+
sessionId: row.session_id,
|
|
393
|
+
signalKind: 'mid_confidence_correction',
|
|
394
|
+
status: row.resolution === 'inbox_approving' ? 'inbox_approving' : 'inbox_candidate',
|
|
395
|
+
excerpt: (row.excerpt ?? '').slice(0, 300),
|
|
396
|
+
confidence: null,
|
|
397
|
+
reason: row.resolution,
|
|
398
|
+
createdAt: row.created_at,
|
|
399
|
+
expiresAt: computeExpiresAt(row.created_at),
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
items.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
|
|
404
|
+
const byHost = {
|
|
405
|
+
openclaw: items.filter((i) => i.hostKind === 'openclaw').length,
|
|
406
|
+
codex: items.filter((i) => i.hostKind === 'codex').length,
|
|
407
|
+
workbuddy: items.filter((i) => i.hostKind === 'workbuddy').length,
|
|
408
|
+
};
|
|
409
|
+
return { ok: true, items, total: items.length, byHost };
|
|
410
|
+
}
|
|
411
|
+
finally {
|
|
412
|
+
close();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Owner-approved admission of a Pain Inbox candidate (W3 CAS state machine).
|
|
417
|
+
*
|
|
418
|
+
* Supports both GSA (`gsa:<key>`) and OpenClaw (`oc:<id>`) candidates, bridging
|
|
419
|
+
* OpenClaw approvals onto a unified GSA Admission Marker
|
|
420
|
+
* (`logical_observation_key = 'openclaw:confirmation:<id>'`) and inserting
|
|
421
|
+
* into `pain_events` + `ensureGovernanceDiagnosticianTask()`.
|
|
422
|
+
*/
|
|
423
|
+
export async function admitOwnerApprovedInboxCandidate(input) {
|
|
424
|
+
const parsedId = parseItemId(input.itemId);
|
|
425
|
+
if (!parsedId) {
|
|
426
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId, reason: 'invalid_item_id' };
|
|
427
|
+
}
|
|
428
|
+
const now = input.now ?? new Date();
|
|
429
|
+
const nowIso = now.toISOString();
|
|
430
|
+
const nowMs = now.getTime();
|
|
431
|
+
const workspaceDir = path.resolve(input.workspaceDir);
|
|
432
|
+
const opened = openTrajectoryDb(workspaceDir, false, input.databaseFactory);
|
|
433
|
+
if (!opened) {
|
|
434
|
+
return {
|
|
435
|
+
ok: false,
|
|
436
|
+
reason: 'trajectory_db_not_found',
|
|
437
|
+
nextAction: 'Initialize workspace trajectory.db before admitting Pain Inbox candidates.',
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
const { db, close } = opened;
|
|
441
|
+
try {
|
|
442
|
+
const claimToken = randomUUID();
|
|
443
|
+
// ── Branch A: GSA candidate (Codex / WorkBuddy) ─────────────────────────
|
|
444
|
+
if (parsedId.source === 'gsa') {
|
|
445
|
+
if (!tableExists(db, 'governance_signal_admissions')) {
|
|
446
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
447
|
+
}
|
|
448
|
+
const key = parsedId.rawKey;
|
|
449
|
+
const rawRow = db
|
|
450
|
+
.prepare(`SELECT id, logical_observation_key, host_kind, rollout_identity, root_session_id, signal_kind,
|
|
451
|
+
decision, canonical_pain_id, diagnostician_task_id, reason,
|
|
452
|
+
task_payload_json, created_at
|
|
453
|
+
FROM governance_signal_admissions
|
|
454
|
+
WHERE logical_observation_key = ?
|
|
455
|
+
LIMIT 1`)
|
|
456
|
+
.get(key);
|
|
457
|
+
if (rawRow !== undefined && !isGsaAdmissionRow(rawRow)) {
|
|
458
|
+
return {
|
|
459
|
+
ok: false,
|
|
460
|
+
reason: 'gsa_inbox_row_malformed',
|
|
461
|
+
nextAction: 'Inspect governance_signal_admissions for schema drift or corruption before admitting this inbox item.',
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const row = rawRow;
|
|
465
|
+
if (!row)
|
|
466
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
467
|
+
if (row.decision === 'source_revoked') {
|
|
468
|
+
return { ok: true, disposition: 'source_revoked', itemId: input.itemId };
|
|
469
|
+
}
|
|
470
|
+
if (row.decision === 'inbox_approved' || row.decision === 'admitted') {
|
|
471
|
+
return {
|
|
472
|
+
ok: true,
|
|
473
|
+
disposition: 'already_approved',
|
|
474
|
+
itemId: input.itemId,
|
|
475
|
+
...(row.canonical_pain_id ? { canonicalPainId: row.canonical_pain_id } : {}),
|
|
476
|
+
...(row.diagnostician_task_id ? { diagnosticianTaskId: row.diagnostician_task_id } : {}),
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
if (row.decision === 'acknowledged_observation') {
|
|
480
|
+
return { ok: true, disposition: 'acknowledged_observation', itemId: input.itemId };
|
|
481
|
+
}
|
|
482
|
+
const hostKind = row.host_kind === 'workbuddy'
|
|
483
|
+
? 'workbuddy'
|
|
484
|
+
: row.host_kind === 'openclaw'
|
|
485
|
+
? 'openclaw'
|
|
486
|
+
: 'codex';
|
|
487
|
+
const auth = readSourceMaterialAuthorization({ workspaceDir, hostKind });
|
|
488
|
+
if (hostKind !== 'openclaw' && auth.status !== 'authorized') {
|
|
489
|
+
return { ok: true, disposition: 'source_revoked', itemId: input.itemId, reason: auth.reason };
|
|
490
|
+
}
|
|
491
|
+
if (isExpired(row.created_at, nowMs)) {
|
|
492
|
+
return { ok: true, disposition: 'expired', itemId: input.itemId };
|
|
493
|
+
}
|
|
494
|
+
const payload = parseJsonSafe(row.task_payload_json) ?? {};
|
|
495
|
+
// Crash recovery for stale inbox_approving rows
|
|
496
|
+
if (row.decision === 'inbox_approving') {
|
|
497
|
+
const approval = isRecord(payload.inboxApproval) ? payload.inboxApproval : null;
|
|
498
|
+
const claimedAt = approval && typeof approval.claimedAt === 'string' ? Date.parse(approval.claimedAt) : NaN;
|
|
499
|
+
const stale = Number.isFinite(claimedAt) && nowMs - claimedAt >= PAIN_INBOX_APPROVING_TTL_MS;
|
|
500
|
+
if (!stale) {
|
|
501
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId };
|
|
502
|
+
}
|
|
503
|
+
if (row.canonical_pain_id) {
|
|
504
|
+
// Pain already landed before crash — resume Diagnostician task creation.
|
|
505
|
+
// The row stays inbox_approving when task creation is not yet durable;
|
|
506
|
+
// only a successful/idempotently-recovered task may terminate the CAS.
|
|
507
|
+
const ensured = await ensureGovernanceDiagnosticianTask({
|
|
508
|
+
workspaceDir,
|
|
509
|
+
logicalObservationKey: key,
|
|
510
|
+
canonicalPainId: row.canonical_pain_id,
|
|
511
|
+
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
512
|
+
});
|
|
513
|
+
if (!ensured.ok) {
|
|
514
|
+
return {
|
|
515
|
+
ok: false,
|
|
516
|
+
reason: `diagnostician_task_recovery_failed:${ensured.reason}`,
|
|
517
|
+
nextAction: ensured.nextAction,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
db.prepare(`UPDATE governance_signal_admissions
|
|
521
|
+
SET decision = 'inbox_approved', updated_at = ?
|
|
522
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving'`).run(nowIso, key);
|
|
523
|
+
return {
|
|
524
|
+
ok: true,
|
|
525
|
+
disposition: 'inbox_approved',
|
|
526
|
+
itemId: input.itemId,
|
|
527
|
+
canonicalPainId: row.canonical_pain_id,
|
|
528
|
+
diagnosticianTaskId: ensured.taskId,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
// Pain did not land before crash — revert cleanly to inbox_candidate
|
|
532
|
+
db.prepare(`UPDATE governance_signal_admissions
|
|
533
|
+
SET decision = 'inbox_candidate', updated_at = ?
|
|
534
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving'`).run(nowIso, key);
|
|
535
|
+
}
|
|
536
|
+
// P2-1: calm neutral correction -> archive as acknowledged_observation without escalating to Pain
|
|
537
|
+
if (input.acknowledgeOnly === true) {
|
|
538
|
+
const nextPayload = {
|
|
539
|
+
...payload,
|
|
540
|
+
ownerApproval: {
|
|
541
|
+
decision: 'acknowledged_observation',
|
|
542
|
+
decidedAt: nowIso,
|
|
543
|
+
...(input.ownerNote ? { note: input.ownerNote.slice(0, 300) } : {}),
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
const { changes } = db
|
|
547
|
+
.prepare(`UPDATE governance_signal_admissions
|
|
548
|
+
SET decision = 'acknowledged_observation', task_payload_json = ?, updated_at = ?
|
|
549
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_candidate'`)
|
|
550
|
+
.run(JSON.stringify(nextPayload), nowIso, key);
|
|
551
|
+
if (changes !== 1) {
|
|
552
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId };
|
|
553
|
+
}
|
|
554
|
+
return { ok: true, disposition: 'acknowledged_observation', itemId: input.itemId };
|
|
555
|
+
}
|
|
556
|
+
const painId = typeof payload.pain_id === 'string' && payload.pain_id.length > 0
|
|
557
|
+
? payload.pain_id
|
|
558
|
+
: deriveInboxCanonicalPainId(hostKind, key);
|
|
559
|
+
const reason = `owner_approved_inbox:${(input.ownerNote ?? row.reason ?? 'mid_confidence_correction').slice(0, 180)}`;
|
|
560
|
+
const ingress = evaluateInboxCanonicalAdmission({
|
|
561
|
+
db,
|
|
562
|
+
hostKind,
|
|
563
|
+
logicalObservationKey: key,
|
|
564
|
+
rolloutIdentity: row.rollout_identity,
|
|
565
|
+
rootSessionId: row.root_session_id,
|
|
566
|
+
fallbackSignalKind: row.signal_kind,
|
|
567
|
+
painId,
|
|
568
|
+
reason,
|
|
569
|
+
payload,
|
|
570
|
+
});
|
|
571
|
+
if (!ingress.ok) {
|
|
572
|
+
return {
|
|
573
|
+
ok: false,
|
|
574
|
+
reason: `canonical_ingress_failed:${ingress.reason}`,
|
|
575
|
+
nextAction: 'Do not approve this inbox item into Pain until its host lineage, evidence, and deviation anchor are proven.',
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
const canonical = ingress.decision.legacy;
|
|
579
|
+
// W3 Step 1: CAS claim inbox_candidate -> inbox_approving
|
|
580
|
+
const approvingPayload = {
|
|
581
|
+
...payload,
|
|
582
|
+
inboxApproval: { claimToken, claimedAt: nowIso },
|
|
583
|
+
};
|
|
584
|
+
const claimed = db
|
|
585
|
+
.prepare(`UPDATE governance_signal_admissions
|
|
586
|
+
SET decision = 'inbox_approving', task_payload_json = ?, updated_at = ?
|
|
587
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_candidate'`)
|
|
588
|
+
.run(JSON.stringify(approvingPayload), nowIso, key);
|
|
589
|
+
if (claimed.changes !== 1) {
|
|
590
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId };
|
|
591
|
+
}
|
|
592
|
+
// W3 Step 2: Canonical Pain write + marker transition. `canonical` is
|
|
593
|
+
// the evaluatePainIngress-derived legacy submission; never a parallel
|
|
594
|
+
// hand-assembled Pain shape.
|
|
595
|
+
const trigger = isRecord(payload.trigger) ? payload.trigger : null;
|
|
596
|
+
const excerpt = trigger && typeof trigger.text === 'string' ? trigger.text : '';
|
|
597
|
+
const baseTaskPayload = isRecord(payload.task_payload)
|
|
598
|
+
? payload.task_payload
|
|
599
|
+
: {
|
|
600
|
+
canonicalPainId: painId,
|
|
601
|
+
sessionId: row.root_session_id,
|
|
602
|
+
excerpt: excerpt.slice(0, 500),
|
|
603
|
+
};
|
|
604
|
+
const finalTaskPayload = {
|
|
605
|
+
...baseTaskPayload,
|
|
606
|
+
painType: canonical.painType,
|
|
607
|
+
source: canonical.source,
|
|
608
|
+
reason: canonical.reason,
|
|
609
|
+
score: canonical.score ?? 75,
|
|
610
|
+
sessionId: canonical.sessionId ?? row.root_session_id,
|
|
611
|
+
hostKind,
|
|
612
|
+
evidence: canonical.evidence.map((entry) => ({ sourceRef: entry.sourceRef, note: entry.note })),
|
|
613
|
+
painIngress: canonical.painIngress,
|
|
614
|
+
origin: { kind: 'automatic_hook', source: `${hostKind}:pain_inbox` },
|
|
615
|
+
ownerApproval: {
|
|
616
|
+
approvedAt: nowIso,
|
|
617
|
+
...(input.ownerNote ? { note: input.ownerNote.slice(0, 300) } : {}),
|
|
618
|
+
},
|
|
619
|
+
};
|
|
620
|
+
db.transaction(() => {
|
|
621
|
+
if (tableExists(db, 'pain_events')) {
|
|
622
|
+
const exists = db
|
|
623
|
+
.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ? LIMIT 1')
|
|
624
|
+
.get(painId);
|
|
625
|
+
if (!exists) {
|
|
626
|
+
db.prepare(`INSERT INTO pain_events (
|
|
627
|
+
session_id, source, score, reason, severity, origin,
|
|
628
|
+
canonical_pain_id, host_kind, created_at
|
|
629
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(canonical.sessionId ?? row.root_session_id, canonical.source, canonical.score ?? 75, canonical.reason, canonical.painType === 'user_frustration' ? 'severe' : 'medium', canonical.provenance, painId, hostKind, nowIso);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
const markerUpdate = db.prepare(`UPDATE governance_signal_admissions
|
|
633
|
+
SET canonical_pain_id = ?, reason = ?, task_payload_json = ?, updated_at = ?
|
|
634
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving'`).run(painId, reason.slice(0, 200), JSON.stringify(finalTaskPayload), nowIso, key);
|
|
635
|
+
if (markerUpdate.changes !== 1)
|
|
636
|
+
throw new Error('gsa_inbox_marker_cas_lost');
|
|
637
|
+
})();
|
|
638
|
+
const ensured = await ensureGovernanceDiagnosticianTask({
|
|
639
|
+
workspaceDir,
|
|
640
|
+
logicalObservationKey: key,
|
|
641
|
+
canonicalPainId: painId,
|
|
642
|
+
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
643
|
+
});
|
|
644
|
+
if (!ensured.ok) {
|
|
645
|
+
return {
|
|
646
|
+
ok: false,
|
|
647
|
+
reason: `diagnostician_task_creation_failed:${ensured.reason}`,
|
|
648
|
+
nextAction: ensured.nextAction,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
const terminal = db.prepare(`UPDATE governance_signal_admissions
|
|
652
|
+
SET decision = 'inbox_approved', updated_at = ?
|
|
653
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving' AND canonical_pain_id = ?`).run(nowIso, key, painId);
|
|
654
|
+
if (terminal.changes !== 1) {
|
|
655
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId, canonicalPainId: painId };
|
|
656
|
+
}
|
|
657
|
+
return {
|
|
658
|
+
ok: true,
|
|
659
|
+
disposition: 'inbox_approved',
|
|
660
|
+
itemId: input.itemId,
|
|
661
|
+
canonicalPainId: painId,
|
|
662
|
+
diagnosticianTaskId: ensured.taskId,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
// ── Branch B: OpenClaw signal_confirmations candidate (W3 GSA Bridge) ──
|
|
666
|
+
if (!tableExists(db, 'signal_confirmations')) {
|
|
667
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
668
|
+
}
|
|
669
|
+
const confirmationId = parsedId.rawKey;
|
|
670
|
+
const rawOcRow = db
|
|
671
|
+
.prepare(`SELECT id, session_id, excerpt, status, resolution, created_at
|
|
672
|
+
FROM signal_confirmations
|
|
673
|
+
WHERE id = ?
|
|
674
|
+
LIMIT 1`)
|
|
675
|
+
.get(confirmationId);
|
|
676
|
+
if (rawOcRow !== undefined && !isOpenClawConfirmationRow(rawOcRow)) {
|
|
677
|
+
return {
|
|
678
|
+
ok: false,
|
|
679
|
+
reason: 'openclaw_inbox_row_malformed',
|
|
680
|
+
nextAction: 'Inspect signal_confirmations for schema drift or corruption before admitting this inbox item.',
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
let ocRow = rawOcRow;
|
|
684
|
+
if (!ocRow)
|
|
685
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
686
|
+
if (ocRow.resolution === 'source_revoked') {
|
|
687
|
+
return { ok: true, disposition: 'source_revoked', itemId: input.itemId };
|
|
688
|
+
}
|
|
689
|
+
const gsaBridgeKey = `openclaw:confirmation:${confirmationId}`;
|
|
690
|
+
const readBridgeMarker = () => tableExists(db, 'governance_signal_admissions')
|
|
691
|
+
? readGsaBridgeMarker(db, gsaBridgeKey)
|
|
692
|
+
: undefined;
|
|
693
|
+
if (ocRow.resolution === 'inbox_approving') {
|
|
694
|
+
const marker = readBridgeMarker();
|
|
695
|
+
const markerPayload = parseJsonSafe(marker?.task_payload_json ?? null);
|
|
696
|
+
const approval = markerPayload && isRecord(markerPayload.ownerApproval) ? markerPayload.ownerApproval : null;
|
|
697
|
+
const claimedAt = approval && typeof approval.claimedAt === 'string' ? Date.parse(approval.claimedAt) : NaN;
|
|
698
|
+
const stale = Number.isFinite(claimedAt) && nowMs - claimedAt >= PAIN_INBOX_APPROVING_TTL_MS;
|
|
699
|
+
if (!stale)
|
|
700
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId };
|
|
701
|
+
if (marker?.canonical_pain_id) {
|
|
702
|
+
// Crash-after-pain-write recovery: the canonical Pain and bridge payload
|
|
703
|
+
// are durable, but the Diagnostician continuation/terminal CAS may not be.
|
|
704
|
+
const ensured = await ensureGovernanceDiagnosticianTask({
|
|
705
|
+
workspaceDir,
|
|
706
|
+
logicalObservationKey: gsaBridgeKey,
|
|
707
|
+
canonicalPainId: marker.canonical_pain_id,
|
|
708
|
+
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
709
|
+
});
|
|
710
|
+
if (!ensured.ok) {
|
|
711
|
+
return {
|
|
712
|
+
ok: false,
|
|
713
|
+
reason: `diagnostician_task_recovery_failed:${ensured.reason}`,
|
|
714
|
+
nextAction: ensured.nextAction,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
db.transaction(() => {
|
|
718
|
+
db.prepare(`UPDATE governance_signal_admissions
|
|
719
|
+
SET decision = 'inbox_approved', updated_at = ?
|
|
720
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving'`).run(nowIso, gsaBridgeKey);
|
|
721
|
+
db.prepare(`UPDATE signal_confirmations
|
|
722
|
+
SET status = 'confirmed', resolution = 'inbox_approved', resolved_at = ?
|
|
723
|
+
WHERE id = ? AND resolution = 'inbox_approving'`).run(nowIso, confirmationId);
|
|
724
|
+
})();
|
|
725
|
+
return {
|
|
726
|
+
ok: true,
|
|
727
|
+
disposition: 'inbox_approved',
|
|
728
|
+
itemId: input.itemId,
|
|
729
|
+
canonicalPainId: marker.canonical_pain_id,
|
|
730
|
+
diagnosticianTaskId: ensured.taskId,
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
db.transaction(() => {
|
|
734
|
+
db.prepare("UPDATE signal_confirmations SET resolution = 'inbox_candidate' WHERE id = ? AND resolution = 'inbox_approving'").run(confirmationId);
|
|
735
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
736
|
+
db.prepare("UPDATE governance_signal_admissions SET decision = 'inbox_candidate', updated_at = ? WHERE logical_observation_key = ? AND decision = 'inbox_approving'").run(nowIso, gsaBridgeKey);
|
|
737
|
+
}
|
|
738
|
+
})();
|
|
739
|
+
ocRow = { ...ocRow, resolution: 'inbox_candidate' };
|
|
740
|
+
}
|
|
741
|
+
if (ocRow.resolution === 'inbox_approved' || ocRow.status === 'confirmed') {
|
|
742
|
+
const marker = tableExists(db, 'governance_signal_admissions')
|
|
743
|
+
? readGsaBridgeMarker(db, gsaBridgeKey)
|
|
744
|
+
: undefined;
|
|
745
|
+
return {
|
|
746
|
+
ok: true,
|
|
747
|
+
disposition: 'already_approved',
|
|
748
|
+
itemId: input.itemId,
|
|
749
|
+
...(marker?.canonical_pain_id ? { canonicalPainId: marker.canonical_pain_id } : {}),
|
|
750
|
+
...(marker?.diagnostician_task_id ? { diagnosticianTaskId: marker.diagnostician_task_id } : {}),
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
if (ocRow.resolution === 'acknowledged_observation') {
|
|
754
|
+
return { ok: true, disposition: 'acknowledged_observation', itemId: input.itemId };
|
|
755
|
+
}
|
|
756
|
+
// Live consent check for OpenClaw (only blocks if explicitly revoked)
|
|
757
|
+
const ocAuth = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'openclaw' });
|
|
758
|
+
if (ocAuth.status !== 'authorized' && ocAuth.reason !== 'consent_missing') {
|
|
759
|
+
return { ok: true, disposition: 'source_revoked', itemId: input.itemId, reason: ocAuth.reason };
|
|
760
|
+
}
|
|
761
|
+
if (isExpired(ocRow.created_at, nowMs)) {
|
|
762
|
+
return { ok: true, disposition: 'expired', itemId: input.itemId };
|
|
763
|
+
}
|
|
764
|
+
// P2-1: calm neutral correction -> archive as acknowledged_observation
|
|
765
|
+
if (input.acknowledgeOnly === true) {
|
|
766
|
+
const { changes } = db
|
|
767
|
+
.prepare(`UPDATE signal_confirmations
|
|
768
|
+
SET status = 'rejected', resolution = 'acknowledged_observation', resolved_at = ?
|
|
769
|
+
WHERE id = ? AND status = 'pending' AND resolution = 'inbox_candidate'`)
|
|
770
|
+
.run(nowIso, confirmationId);
|
|
771
|
+
if (changes !== 1) {
|
|
772
|
+
return { ok: true, disposition: 'already_in_progress', itemId: input.itemId };
|
|
773
|
+
}
|
|
774
|
+
return { ok: true, disposition: 'acknowledged_observation', itemId: input.itemId };
|
|
775
|
+
}
|
|
776
|
+
const painId = deriveInboxCanonicalPainId('openclaw', confirmationId);
|
|
777
|
+
const reason = `owner_approved_inbox:${(input.ownerNote ?? 'mid_confidence_correction').slice(0, 180)}`;
|
|
778
|
+
const ocPayload = { signalKind: 'mid_confidence_correction', excerpt: ocRow.excerpt ?? '' };
|
|
779
|
+
const ingress = evaluateInboxCanonicalAdmission({
|
|
780
|
+
db,
|
|
781
|
+
hostKind: 'openclaw',
|
|
782
|
+
logicalObservationKey: gsaBridgeKey,
|
|
783
|
+
rolloutIdentity: ocRow.session_id,
|
|
784
|
+
rootSessionId: ocRow.session_id,
|
|
785
|
+
fallbackSignalKind: 'user_correction',
|
|
786
|
+
painId,
|
|
787
|
+
reason,
|
|
788
|
+
payload: ocPayload,
|
|
789
|
+
openclawConfirmationId: confirmationId,
|
|
790
|
+
openclawExcerpt: ocRow.excerpt ?? '',
|
|
791
|
+
});
|
|
792
|
+
if (!ingress.ok) {
|
|
793
|
+
return {
|
|
794
|
+
ok: false,
|
|
795
|
+
reason: `canonical_ingress_failed:${ingress.reason}`,
|
|
796
|
+
nextAction: 'Do not approve this inbox item into Pain until its host lineage and evidence are proven.',
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
const canonical = ingress.decision.legacy;
|
|
800
|
+
const claimPayload = {
|
|
801
|
+
signalKind: 'mid_confidence_correction',
|
|
802
|
+
excerpt: (ocRow.excerpt ?? '').slice(0, 500),
|
|
803
|
+
ownerApproval: { claimToken, claimedAt: nowIso, confirmationId },
|
|
804
|
+
};
|
|
805
|
+
// W3 Step 1: CAS claim on signal_confirmations AND the bridge marker. The
|
|
806
|
+
// marker owns claim metadata because signal_confirmations has no such columns.
|
|
807
|
+
// Without the marker table there is no durable crash-recovery authority, so
|
|
808
|
+
// approval must fail before the claim instead of stranding inbox_approving.
|
|
809
|
+
if (!tableExists(db, 'governance_signal_admissions')) {
|
|
810
|
+
return {
|
|
811
|
+
ok: false,
|
|
812
|
+
reason: 'gsa_bridge_unavailable',
|
|
813
|
+
nextAction: 'Initialize the governance admission schema before approving OpenClaw inbox candidates.',
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
db.transaction(() => {
|
|
817
|
+
const claimed = db
|
|
818
|
+
.prepare(`UPDATE signal_confirmations
|
|
819
|
+
SET resolution = 'inbox_approving'
|
|
820
|
+
WHERE id = ? AND status = 'pending' AND resolution = 'inbox_candidate'`)
|
|
821
|
+
.run(confirmationId);
|
|
822
|
+
if (claimed.changes !== 1)
|
|
823
|
+
throw new Error('openclaw_inbox_claim_lost');
|
|
824
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
825
|
+
db.prepare(`INSERT INTO governance_signal_admissions (
|
|
826
|
+
logical_observation_key, host_kind, rollout_identity, root_session_id,
|
|
827
|
+
signal_kind, decision, canonical_pain_id, rule_version, reason,
|
|
828
|
+
task_payload_json, created_at, updated_at
|
|
829
|
+
) VALUES (?, 'openclaw', ?, ?, 'user_correction', 'inbox_approving', NULL, 'pain_inbox_v1', ?, ?, ?, ?)
|
|
830
|
+
ON CONFLICT(logical_observation_key) DO UPDATE SET
|
|
831
|
+
decision = 'inbox_approving', task_payload_json = excluded.task_payload_json, updated_at = excluded.updated_at`).run(gsaBridgeKey, ocRow.session_id, ocRow.session_id, 'inbox_claimed', JSON.stringify(claimPayload), nowIso, nowIso);
|
|
832
|
+
}
|
|
833
|
+
})();
|
|
834
|
+
const bridgePayload = {
|
|
835
|
+
canonicalPainId: painId,
|
|
836
|
+
sessionId: canonical.sessionId ?? ocRow.session_id,
|
|
837
|
+
painType: canonical.painType,
|
|
838
|
+
source: canonical.source,
|
|
839
|
+
reason: canonical.reason,
|
|
840
|
+
score: canonical.score ?? 75,
|
|
841
|
+
hostKind: 'openclaw',
|
|
842
|
+
excerpt: (ocRow.excerpt ?? '').slice(0, 500),
|
|
843
|
+
evidence: canonical.evidence.map((entry) => ({ sourceRef: entry.sourceRef, note: entry.note })),
|
|
844
|
+
painIngress: canonical.painIngress,
|
|
845
|
+
origin: { kind: 'automatic_hook', source: 'openclaw:pain_inbox' },
|
|
846
|
+
ownerApproval: {
|
|
847
|
+
approvedAt: nowIso,
|
|
848
|
+
claimToken,
|
|
849
|
+
claimedAt: nowIso,
|
|
850
|
+
confirmationId,
|
|
851
|
+
...(input.ownerNote ? { note: input.ownerNote.slice(0, 300) } : {}),
|
|
852
|
+
},
|
|
853
|
+
};
|
|
854
|
+
db.transaction(() => {
|
|
855
|
+
if (tableExists(db, 'pain_events')) {
|
|
856
|
+
const exists = db
|
|
857
|
+
.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ? LIMIT 1')
|
|
858
|
+
.get(painId);
|
|
859
|
+
if (!exists) {
|
|
860
|
+
db.prepare(`INSERT INTO pain_events (
|
|
861
|
+
session_id, source, score, reason, severity, origin,
|
|
862
|
+
canonical_pain_id, host_kind, created_at
|
|
863
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(canonical.sessionId ?? ocRow.session_id, canonical.source, canonical.score ?? 75, canonical.reason, 'severe', canonical.provenance, painId, 'openclaw', nowIso);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
// W3 Bridge: persist canonical_pain_id + diagnostician_task_id + ownerApproval on
|
|
867
|
+
// governance_signal_admissions (never writing nonexistent columns to signal_confirmations).
|
|
868
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
869
|
+
db.prepare(`INSERT INTO governance_signal_admissions (
|
|
870
|
+
logical_observation_key, host_kind, rollout_identity, root_session_id,
|
|
871
|
+
signal_kind, decision, canonical_pain_id, rule_version, reason,
|
|
872
|
+
task_payload_json, created_at, updated_at
|
|
873
|
+
) VALUES (?, 'openclaw', ?, ?, 'user_correction', 'inbox_approving', ?, 'pain_inbox_v1', ?, ?, ?, ?)
|
|
874
|
+
ON CONFLICT(logical_observation_key) DO UPDATE SET
|
|
875
|
+
decision = 'inbox_approving',
|
|
876
|
+
canonical_pain_id = excluded.canonical_pain_id,
|
|
877
|
+
reason = excluded.reason,
|
|
878
|
+
task_payload_json = excluded.task_payload_json,
|
|
879
|
+
updated_at = excluded.updated_at`).run(gsaBridgeKey, ocRow.session_id, ocRow.session_id, painId, reason.slice(0, 200), JSON.stringify(bridgePayload), nowIso, nowIso);
|
|
880
|
+
}
|
|
881
|
+
})();
|
|
882
|
+
const ensured = await ensureGovernanceDiagnosticianTask({
|
|
883
|
+
workspaceDir,
|
|
884
|
+
logicalObservationKey: gsaBridgeKey,
|
|
885
|
+
canonicalPainId: painId,
|
|
886
|
+
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
887
|
+
});
|
|
888
|
+
if (!ensured.ok) {
|
|
889
|
+
return {
|
|
890
|
+
ok: false,
|
|
891
|
+
reason: `diagnostician_task_creation_failed:${ensured.reason}`,
|
|
892
|
+
nextAction: ensured.nextAction,
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
db.transaction(() => {
|
|
896
|
+
db.prepare(`UPDATE governance_signal_admissions
|
|
897
|
+
SET decision = 'inbox_approved', updated_at = ?
|
|
898
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_approving' AND canonical_pain_id = ?`).run(nowIso, gsaBridgeKey, painId);
|
|
899
|
+
db.prepare(`UPDATE signal_confirmations
|
|
900
|
+
SET status = 'confirmed', resolution = 'inbox_approved', resolved_at = ?
|
|
901
|
+
WHERE id = ? AND resolution = 'inbox_approving'`).run(nowIso, confirmationId);
|
|
902
|
+
})();
|
|
903
|
+
return {
|
|
904
|
+
ok: true,
|
|
905
|
+
disposition: 'inbox_approved',
|
|
906
|
+
itemId: input.itemId,
|
|
907
|
+
canonicalPainId: painId,
|
|
908
|
+
diagnosticianTaskId: ensured.taskId,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
catch (error) {
|
|
912
|
+
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
913
|
+
return {
|
|
914
|
+
ok: false,
|
|
915
|
+
reason: `inbox_admission_failed:${detail}`,
|
|
916
|
+
nextAction: 'Inspect trajectory.db and retry; stale inbox_approving claims recover automatically.',
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
finally {
|
|
920
|
+
close();
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Dismiss a Pain Inbox candidate (CAS terminal `inbox_dismissed`).
|
|
925
|
+
*/
|
|
926
|
+
export function dismissPainInboxCandidate(input) {
|
|
927
|
+
const parsedId = parseItemId(input.itemId);
|
|
928
|
+
if (!parsedId) {
|
|
929
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
930
|
+
}
|
|
931
|
+
const nowIso = (input.now ?? new Date()).toISOString();
|
|
932
|
+
const opened = openTrajectoryDb(input.workspaceDir, false, input.databaseFactory);
|
|
933
|
+
if (!opened) {
|
|
934
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
935
|
+
}
|
|
936
|
+
const { db, close } = opened;
|
|
937
|
+
try {
|
|
938
|
+
if (parsedId.source === 'gsa') {
|
|
939
|
+
if (!tableExists(db, 'governance_signal_admissions')) {
|
|
940
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
941
|
+
}
|
|
942
|
+
const { changes } = db
|
|
943
|
+
.prepare(`UPDATE governance_signal_admissions
|
|
944
|
+
SET decision = 'inbox_dismissed', reason = ?, updated_at = ?
|
|
945
|
+
WHERE logical_observation_key = ? AND decision = 'inbox_candidate'`)
|
|
946
|
+
.run((input.reason ?? 'owner_dismissed').slice(0, 200), nowIso, parsedId.rawKey);
|
|
947
|
+
return {
|
|
948
|
+
ok: true,
|
|
949
|
+
disposition: changes === 1 ? 'inbox_dismissed' : 'already_resolved',
|
|
950
|
+
itemId: input.itemId,
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
if (!tableExists(db, 'signal_confirmations')) {
|
|
954
|
+
return { ok: true, disposition: 'not_found', itemId: input.itemId };
|
|
955
|
+
}
|
|
956
|
+
const { changes } = db
|
|
957
|
+
.prepare(`UPDATE signal_confirmations
|
|
958
|
+
SET status = 'rejected', resolution = 'inbox_dismissed', resolved_at = ?
|
|
959
|
+
WHERE id = ? AND status = 'pending' AND resolution = 'inbox_candidate'`)
|
|
960
|
+
.run(nowIso, parsedId.rawKey);
|
|
961
|
+
return {
|
|
962
|
+
ok: true,
|
|
963
|
+
disposition: changes === 1 ? 'inbox_dismissed' : 'already_resolved',
|
|
964
|
+
itemId: input.itemId,
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
catch (error) {
|
|
968
|
+
return {
|
|
969
|
+
ok: false,
|
|
970
|
+
reason: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200),
|
|
971
|
+
nextAction: 'Retry dismissing the Pain Inbox item.',
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
finally {
|
|
975
|
+
close();
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* 7-day Inbox TTL cleanup across both `governance_signal_admissions` and
|
|
980
|
+
* `signal_confirmations`. Safe to invoke from worker housekeeping cycles.
|
|
981
|
+
*/
|
|
982
|
+
export function expireStalePainInboxItems(input) {
|
|
983
|
+
const now = input.now ?? new Date();
|
|
984
|
+
const nowIso = now.toISOString();
|
|
985
|
+
const cutoffIso = new Date(now.getTime() - PAIN_INBOX_TTL_MS).toISOString();
|
|
986
|
+
const opened = openTrajectoryDb(input.workspaceDir, false, input.databaseFactory);
|
|
987
|
+
if (!opened)
|
|
988
|
+
return { ok: true, expiredGsa: 0, expiredOpenClaw: 0 };
|
|
989
|
+
const { db, close } = opened;
|
|
990
|
+
try {
|
|
991
|
+
let expiredGsa = 0;
|
|
992
|
+
let expiredOpenClaw = 0;
|
|
993
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
994
|
+
expiredGsa = db
|
|
995
|
+
.prepare(`UPDATE governance_signal_admissions
|
|
996
|
+
SET decision = 'abandoned', reason = 'inbox_ttl_expired', updated_at = ?
|
|
997
|
+
WHERE decision = 'inbox_candidate' AND created_at <= ?`)
|
|
998
|
+
.run(nowIso, cutoffIso).changes;
|
|
999
|
+
}
|
|
1000
|
+
if (tableExists(db, 'signal_confirmations')) {
|
|
1001
|
+
expiredOpenClaw = db
|
|
1002
|
+
.prepare(`UPDATE signal_confirmations
|
|
1003
|
+
SET status = 'abandoned', resolution = 'inbox_ttl_expired', resolved_at = ?
|
|
1004
|
+
WHERE status = 'pending' AND resolution = 'inbox_candidate' AND created_at <= ?`)
|
|
1005
|
+
.run(nowIso, cutoffIso).changes;
|
|
1006
|
+
}
|
|
1007
|
+
return { ok: true, expiredGsa, expiredOpenClaw };
|
|
1008
|
+
}
|
|
1009
|
+
catch (error) {
|
|
1010
|
+
return {
|
|
1011
|
+
ok: false,
|
|
1012
|
+
expiredGsa: 0,
|
|
1013
|
+
expiredOpenClaw: 0,
|
|
1014
|
+
reason: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200),
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
finally {
|
|
1018
|
+
close();
|
|
1019
|
+
}
|
|
1020
|
+
}
|