@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,20 @@
|
|
|
1
|
+
import { type PDRuntimeAdapter } from '@principles/core/runtime';
|
|
2
|
+
import { type SignalClassifierProfile } from './signal-classifier.js';
|
|
3
|
+
import type { IdleTurnAuditor } from './idle-turn-audit.js';
|
|
4
|
+
export interface CreateIdleTurnAuditorOptions {
|
|
5
|
+
readonly adapter?: Pick<PDRuntimeAdapter, 'startRun' | 'pollRun' | 'fetchOutput'>;
|
|
6
|
+
readonly timeoutMs?: number;
|
|
7
|
+
readonly log?: (event: string, detail: string) => void;
|
|
8
|
+
}
|
|
9
|
+
/** Build an auditor from an already-resolved pi-ai profile (no config I/O). */
|
|
10
|
+
export declare function createIdleTurnAuditor(profile: SignalClassifierProfile, workspaceDir: string, options?: CreateIdleTurnAuditorOptions): IdleTurnAuditor;
|
|
11
|
+
export type IdleTurnAuditorResolution = {
|
|
12
|
+
readonly ok: true;
|
|
13
|
+
readonly auditor: IdleTurnAuditor;
|
|
14
|
+
} | {
|
|
15
|
+
readonly ok: false;
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
readonly readiness: string;
|
|
18
|
+
};
|
|
19
|
+
/** Resolve the existing lightweight signalCollector pi-ai profile and build the production auditor. */
|
|
20
|
+
export declare function createIdleTurnAuditorForWorkspace(workspaceDir: string, options?: CreateIdleTurnAuditorOptions): IdleTurnAuditorResolution;
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production LLM auditor for the R5 idle-turn audit.
|
|
3
|
+
*
|
|
4
|
+
* This module hides evidence collection, active-principle lookup, prompt
|
|
5
|
+
* construction, pi-ai invocation, and untrusted-output validation behind the
|
|
6
|
+
* single `IdleTurnAuditor` seam consumed by `runIdleTurnAuditCycle`.
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import Database from 'better-sqlite3';
|
|
11
|
+
import { PiAiRuntimeAdapter, RUNTIME_CONTRACT_SCHEMA_VERSION, buildL2PrincipleReaderFromLedger, } from '@principles/core/runtime';
|
|
12
|
+
import { loadLedger } from '@principles/core/principle-tree-ledger';
|
|
13
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
14
|
+
import { createSignalClassifierForWorkspace } from './signal-classifier.js';
|
|
15
|
+
const DEFAULT_AUDIT_TIMEOUT_MS = 25_000;
|
|
16
|
+
const MAX_EVIDENCE_ROWS = 18;
|
|
17
|
+
const MAX_ENTRY_CHARS = 520;
|
|
18
|
+
const MAX_TOTAL_EVIDENCE_CHARS = 9_000;
|
|
19
|
+
function isRecord(value) {
|
|
20
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
21
|
+
}
|
|
22
|
+
function tableExists(db, name) {
|
|
23
|
+
return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1").get(name) !== undefined;
|
|
24
|
+
}
|
|
25
|
+
function truncate(text, maxChars) {
|
|
26
|
+
const collapsed = text.replace(/\s+/g, ' ').trim();
|
|
27
|
+
return collapsed.length <= maxChars ? collapsed : `${collapsed.slice(0, maxChars - 1)}…`;
|
|
28
|
+
}
|
|
29
|
+
function evidenceRow(params) {
|
|
30
|
+
if (!isRecord(params.value) || typeof params.value[params.timeColumn] !== 'string')
|
|
31
|
+
return null;
|
|
32
|
+
const rawText = params.value[params.textColumn];
|
|
33
|
+
const text = typeof rawText === 'string' ? rawText : '';
|
|
34
|
+
const at = params.value[params.timeColumn];
|
|
35
|
+
if (text.trim().length === 0 || typeof at !== 'string')
|
|
36
|
+
return null;
|
|
37
|
+
return { at, kind: params.kind, text: truncate(text, MAX_ENTRY_CHARS) };
|
|
38
|
+
}
|
|
39
|
+
function collectOpenClawEvidence(db, sessionId) {
|
|
40
|
+
const rows = [];
|
|
41
|
+
if (tableExists(db, 'user_turns')) {
|
|
42
|
+
const raw = db.prepare(`SELECT id, COALESCE(raw_text, raw_excerpt, '') AS body, created_at FROM user_turns WHERE session_id = ? ORDER BY id DESC LIMIT ?`).all(sessionId, MAX_EVIDENCE_ROWS);
|
|
43
|
+
if (Array.isArray(raw)) {
|
|
44
|
+
for (const row of raw) {
|
|
45
|
+
const parsed = evidenceRow({ value: row, kind: 'user', textColumn: 'body', timeColumn: 'created_at' });
|
|
46
|
+
if (parsed !== null)
|
|
47
|
+
rows.push(parsed);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (tableExists(db, 'assistant_turns')) {
|
|
52
|
+
const raw = db.prepare('SELECT id, sanitized_text AS body, created_at FROM assistant_turns WHERE session_id = ? ORDER BY id DESC LIMIT ?').all(sessionId, MAX_EVIDENCE_ROWS);
|
|
53
|
+
if (Array.isArray(raw)) {
|
|
54
|
+
for (const row of raw) {
|
|
55
|
+
const parsed = evidenceRow({ value: row, kind: 'assistant', textColumn: 'body', timeColumn: 'created_at' });
|
|
56
|
+
if (parsed !== null)
|
|
57
|
+
rows.push(parsed);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (tableExists(db, 'tool_calls')) {
|
|
62
|
+
const raw = db.prepare(`SELECT id, tool_name, outcome, COALESCE(error_message, result_preview, '') AS detail, created_at
|
|
63
|
+
FROM tool_calls WHERE session_id = ? ORDER BY id DESC LIMIT ?`).all(sessionId, MAX_EVIDENCE_ROWS);
|
|
64
|
+
if (Array.isArray(raw)) {
|
|
65
|
+
for (const value of raw) {
|
|
66
|
+
if (!isRecord(value) || typeof value.created_at !== 'string' || typeof value.tool_name !== 'string' || typeof value.outcome !== 'string')
|
|
67
|
+
continue;
|
|
68
|
+
const detail = typeof value.detail === 'string' && value.detail.length > 0 ? ` — ${value.detail}` : '';
|
|
69
|
+
rows.push({ at: value.created_at, kind: 'tool', text: truncate(`${value.tool_name}: ${value.outcome}${detail}`, MAX_ENTRY_CHARS) });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return rows;
|
|
74
|
+
}
|
|
75
|
+
function collectGovernanceEvidence(db, candidate) {
|
|
76
|
+
if (!tableExists(db, 'governance_observations'))
|
|
77
|
+
return [];
|
|
78
|
+
const raw = db.prepare(`SELECT id, kind, visible_text, sanitized_tool_facts_json, observed_at
|
|
79
|
+
FROM governance_observations
|
|
80
|
+
WHERE host_kind = ? AND root_session_id = ?
|
|
81
|
+
AND kind IN ('user_turn', 'assistant_turn', 'tool_call')
|
|
82
|
+
AND retention_class IN ('operational', 'promoted')
|
|
83
|
+
ORDER BY id DESC LIMIT ?`).all(candidate.hostKind, candidate.sessionId, MAX_EVIDENCE_ROWS * 2);
|
|
84
|
+
if (!Array.isArray(raw))
|
|
85
|
+
return [];
|
|
86
|
+
const rows = [];
|
|
87
|
+
for (const value of raw) {
|
|
88
|
+
if (!isRecord(value) || typeof value.kind !== 'string' || typeof value.observed_at !== 'string')
|
|
89
|
+
continue;
|
|
90
|
+
const visible = typeof value.visible_text === 'string' ? value.visible_text : '';
|
|
91
|
+
const facts = typeof value.sanitized_tool_facts_json === 'string' ? value.sanitized_tool_facts_json : '';
|
|
92
|
+
const text = visible.trim().length > 0 ? visible : facts;
|
|
93
|
+
if (text.trim().length === 0)
|
|
94
|
+
continue;
|
|
95
|
+
rows.push({ at: value.observed_at, kind: value.kind, text: truncate(text, MAX_ENTRY_CHARS) });
|
|
96
|
+
}
|
|
97
|
+
return rows;
|
|
98
|
+
}
|
|
99
|
+
function collectAuditEvidence(workspaceDir, candidate) {
|
|
100
|
+
const dbPath = resolveTrajectoryDbPath(workspaceDir);
|
|
101
|
+
if (!fs.existsSync(dbPath))
|
|
102
|
+
return [];
|
|
103
|
+
let db = null;
|
|
104
|
+
try {
|
|
105
|
+
db = new Database(dbPath, { readonly: true, fileMustExist: true });
|
|
106
|
+
const rows = candidate.hostKind === 'openclaw'
|
|
107
|
+
? collectOpenClawEvidence(db, candidate.sessionId)
|
|
108
|
+
: collectGovernanceEvidence(db, candidate);
|
|
109
|
+
rows.sort((a, b) => a.at.localeCompare(b.at));
|
|
110
|
+
const bounded = [];
|
|
111
|
+
let total = 0;
|
|
112
|
+
for (const row of rows.slice(-MAX_EVIDENCE_ROWS)) {
|
|
113
|
+
if (total + row.text.length > MAX_TOTAL_EVIDENCE_CHARS)
|
|
114
|
+
break;
|
|
115
|
+
bounded.push(row);
|
|
116
|
+
total += row.text.length;
|
|
117
|
+
}
|
|
118
|
+
return bounded;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
if (db !== null) {
|
|
125
|
+
try {
|
|
126
|
+
db.close();
|
|
127
|
+
}
|
|
128
|
+
catch { /* readonly close best-effort */ }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async function listActivePrinciplesAsync(workspaceDir) {
|
|
133
|
+
try {
|
|
134
|
+
const reader = buildL2PrincipleReaderFromLedger(loadLedger(path.join(workspaceDir, '.state')), {
|
|
135
|
+
logger: { warn: () => undefined },
|
|
136
|
+
});
|
|
137
|
+
return await reader.listActivePrinciples();
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return [];
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function buildAuditPrompt(args) {
|
|
144
|
+
return JSON.stringify({
|
|
145
|
+
task: 'Review the bounded host-session evidence for a behavior deviation from an active principle.',
|
|
146
|
+
rules: [
|
|
147
|
+
'Judge only evidence present in this payload; do not invent missing facts.',
|
|
148
|
+
'A deviation is a violation of an active principle by assistant behavior, not merely task failure or user dissatisfaction.',
|
|
149
|
+
'Return detected=false when evidence is insufficient or no active principle clearly applies.',
|
|
150
|
+
'When detected=true, principleId must be copied exactly from activePrinciples, and observedAt must be copied exactly from the evidence row where the deviation occurred.',
|
|
151
|
+
'Return exactly one JSON object and no markdown.',
|
|
152
|
+
],
|
|
153
|
+
outputShape: {
|
|
154
|
+
detected: 'boolean',
|
|
155
|
+
principleId: 'string, required when detected=true',
|
|
156
|
+
observedAt: 'ISO timestamp copied from evidence, required when detected=true',
|
|
157
|
+
runId: 'optional string when visible in evidence',
|
|
158
|
+
excerpt: 'short evidence excerpt',
|
|
159
|
+
confidence: 'number between 0 and 1',
|
|
160
|
+
reasoning: 'brief factual explanation',
|
|
161
|
+
},
|
|
162
|
+
session: {
|
|
163
|
+
hostKind: args.candidate.hostKind,
|
|
164
|
+
sessionId: args.candidate.sessionId,
|
|
165
|
+
turnCount: args.candidate.turnCount,
|
|
166
|
+
lastTurnCompletedAt: args.candidate.lastTurnCompletedAt,
|
|
167
|
+
},
|
|
168
|
+
activePrinciples: args.principles,
|
|
169
|
+
evidence: args.evidence,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
function parseFinding(payload) {
|
|
173
|
+
if (!isRecord(payload) || typeof payload.detected !== 'boolean')
|
|
174
|
+
return null;
|
|
175
|
+
if (!payload.detected)
|
|
176
|
+
return { detected: false };
|
|
177
|
+
if (typeof payload.principleId !== 'string' || payload.principleId.trim().length === 0)
|
|
178
|
+
return null;
|
|
179
|
+
if (typeof payload.observedAt !== 'string' || !Number.isFinite(Date.parse(payload.observedAt)))
|
|
180
|
+
return null;
|
|
181
|
+
return {
|
|
182
|
+
detected: true,
|
|
183
|
+
principleId: payload.principleId.trim(),
|
|
184
|
+
observedAt: payload.observedAt,
|
|
185
|
+
...(typeof payload.runId === 'string' && payload.runId.trim().length > 0 ? { runId: payload.runId.trim() } : {}),
|
|
186
|
+
...(typeof payload.excerpt === 'string' ? { excerpt: truncate(payload.excerpt, 800) } : {}),
|
|
187
|
+
...(typeof payload.confidence === 'number' && Number.isFinite(payload.confidence) ? { confidence: Math.max(0, Math.min(1, payload.confidence)) } : {}),
|
|
188
|
+
...(typeof payload.reasoning === 'string' ? { reasoning: truncate(payload.reasoning, 1000) } : {}),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** Build an auditor from an already-resolved pi-ai profile (no config I/O). */
|
|
192
|
+
export function createIdleTurnAuditor(profile, workspaceDir, options = {}) {
|
|
193
|
+
const timeoutMs = options.timeoutMs ?? Math.min(profile.timeoutMs, DEFAULT_AUDIT_TIMEOUT_MS);
|
|
194
|
+
const adapter = options.adapter ?? new PiAiRuntimeAdapter({
|
|
195
|
+
provider: profile.provider,
|
|
196
|
+
model: profile.model,
|
|
197
|
+
apiKeyEnv: profile.apiKeyEnv,
|
|
198
|
+
timeoutMs,
|
|
199
|
+
maxTokens: profile.maxTokens,
|
|
200
|
+
baseUrl: profile.baseUrl,
|
|
201
|
+
workspace: workspaceDir,
|
|
202
|
+
outputPathStrategy: 'free_form_only',
|
|
203
|
+
maxRepairAttempts: 0,
|
|
204
|
+
});
|
|
205
|
+
return async (candidate) => {
|
|
206
|
+
const evidence = collectAuditEvidence(workspaceDir, candidate);
|
|
207
|
+
const principles = await listActivePrinciplesAsync(workspaceDir);
|
|
208
|
+
if (evidence.length === 0 || principles.length === 0)
|
|
209
|
+
return { detected: false };
|
|
210
|
+
const prompt = buildAuditPrompt({ candidate, principles, evidence });
|
|
211
|
+
try {
|
|
212
|
+
const handle = await adapter.startRun({
|
|
213
|
+
agentSpec: { agentId: 'idle-turn-auditor', schemaVersion: RUNTIME_CONTRACT_SCHEMA_VERSION },
|
|
214
|
+
inputPayload: { prompt },
|
|
215
|
+
contextItems: [],
|
|
216
|
+
timeoutMs,
|
|
217
|
+
maxTokens: 1_200,
|
|
218
|
+
systemPrompt: 'You are a strict behavior-deviation auditor. Use only supplied evidence and return exactly one JSON object.',
|
|
219
|
+
});
|
|
220
|
+
let status = await adapter.pollRun(handle.runId);
|
|
221
|
+
const deadline = performance.now() + timeoutMs;
|
|
222
|
+
while (status.status === 'running' && performance.now() < deadline) {
|
|
223
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
224
|
+
status = await adapter.pollRun(handle.runId);
|
|
225
|
+
}
|
|
226
|
+
if (status.status !== 'succeeded') {
|
|
227
|
+
options.log?.('IDLE_AUDIT_LLM_NOT_SUCCEEDED', JSON.stringify({ status: status.status }));
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
const output = await adapter.fetchOutput(handle.runId);
|
|
231
|
+
return parseFinding(output?.payload);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
options.log?.('IDLE_AUDIT_LLM_FAILED', String(error).slice(0, 200));
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/** Resolve the existing lightweight signalCollector pi-ai profile and build the production auditor. */
|
|
240
|
+
export function createIdleTurnAuditorForWorkspace(workspaceDir, options = {}) {
|
|
241
|
+
const resolved = createSignalClassifierForWorkspace(workspaceDir, {
|
|
242
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_AUDIT_TIMEOUT_MS,
|
|
243
|
+
...(options.log !== undefined ? { log: options.log } : {}),
|
|
244
|
+
});
|
|
245
|
+
if (!resolved.ok) {
|
|
246
|
+
return { ok: false, reason: resolved.reason, readiness: resolved.readiness };
|
|
247
|
+
}
|
|
248
|
+
return { ok: true, auditor: createIdleTurnAuditor(resolved.profile, path.resolve(workspaceDir), options) };
|
|
249
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export * from './production-rulehost-gate.js';
|
|
|
20
20
|
export * from './rule-implementation-runtime.js';
|
|
21
21
|
export * from './production-pain-evidence.js';
|
|
22
22
|
export * from './environment-facts.js';
|
|
23
|
+
export * from './forward-observation.js';
|
|
23
24
|
export * from './governance-observation-store.js';
|
|
24
25
|
export * from './governance-trajectory-turn-reader.js';
|
|
25
26
|
export * from './plugin-trajectory-turn-store.js';
|
|
@@ -32,7 +33,12 @@ export * from './signal-classifier.js';
|
|
|
32
33
|
export * from './adaptive-selection.js';
|
|
33
34
|
export * from './adaptive-priority-provider.js';
|
|
34
35
|
export * from './adaptive-background-append.js';
|
|
36
|
+
export * from './stage2-context-hydrator.js';
|
|
35
37
|
export * from './signal-stage2-cycle.js';
|
|
38
|
+
export * from './pain-inbox.js';
|
|
39
|
+
export * from './trajectory-stall-detector.js';
|
|
40
|
+
export * from './idle-turn-audit.js';
|
|
41
|
+
export * from './idle-turn-auditor.js';
|
|
36
42
|
export * from './host-liveness-contract.js';
|
|
37
43
|
export * from './internalization-consumer-governance.js';
|
|
38
44
|
export { INTERNALIZATION_AUTO_CONSUMER_FLAG_ID, orderKindsByOldestReadyStage, oldestReadyAgeMs, runInternalizationConsumerCycle, } from './internalization-consumer-cycle.js';
|
|
@@ -96,11 +102,11 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
|
|
|
96
102
|
/** Host project cwd, distinct from the workspace owning shared PD state. */
|
|
97
103
|
projectDir?: string;
|
|
98
104
|
/**
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* allow-listed fields exist — an
|
|
102
|
-
*
|
|
103
|
-
* secret-bearing value.
|
|
105
|
+
* Adapter-known environment facts for the event-scoped pre-gate opportunity
|
|
106
|
+
* capture used by authorized E0 synthetic fixtures. PostToolUse no longer
|
|
107
|
+
* writes environment snapshots. Only these allow-listed fields exist — an
|
|
108
|
+
* adapter that does not know a fact omits it and the row records NULL
|
|
109
|
+
* (unknown), never a guess and never a secret-bearing value.
|
|
104
110
|
*/
|
|
105
111
|
afterToolCallEnvironment?: AfterToolCallEnvironmentFacts | ((event: HostEvent) => AfterToolCallEnvironmentFacts);
|
|
106
112
|
/** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { loadPdConfigForPlugin } from './pd-config.js';
|
|
|
5
5
|
import { buildActivePrinciplePromptContext } from './active-principle-prompt.js';
|
|
6
6
|
import { createProductionRuleHostGate } from './production-rulehost-gate.js';
|
|
7
7
|
import { createProductionPainEvidenceHandler } from './production-pain-evidence.js';
|
|
8
|
+
import { capturePreGateOpportunity, recordForwardGateDecision } from './forward-observation.js';
|
|
8
9
|
export * from './active-principle-prompt.js';
|
|
9
10
|
export * from './prompt-activation-authority.js';
|
|
10
11
|
export * from './prompt-injection-projection.js';
|
|
@@ -32,6 +33,7 @@ export * from './production-rulehost-gate.js';
|
|
|
32
33
|
export * from './rule-implementation-runtime.js';
|
|
33
34
|
export * from './production-pain-evidence.js';
|
|
34
35
|
export * from './environment-facts.js';
|
|
36
|
+
export * from './forward-observation.js';
|
|
35
37
|
export * from './governance-observation-store.js';
|
|
36
38
|
// PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
|
|
37
39
|
// pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
|
|
@@ -64,7 +66,12 @@ export * from './adaptive-priority-provider.js';
|
|
|
64
66
|
// first request goes out as Native and one directive may be appended later in
|
|
65
67
|
// the same turn.
|
|
66
68
|
export * from './adaptive-background-append.js';
|
|
69
|
+
export * from './stage2-context-hydrator.js';
|
|
67
70
|
export * from './signal-stage2-cycle.js';
|
|
71
|
+
export * from './pain-inbox.js';
|
|
72
|
+
export * from './trajectory-stall-detector.js';
|
|
73
|
+
export * from './idle-turn-audit.js';
|
|
74
|
+
export * from './idle-turn-auditor.js';
|
|
68
75
|
export * from './host-liveness-contract.js';
|
|
69
76
|
// PRI-624 Slice C: shared internalization consumer execution (OpenClaw
|
|
70
77
|
// auto-consumer + Service-Host-spawned workspace workers call the same cycle).
|
|
@@ -261,15 +268,38 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
261
268
|
...(options.hostKind ? { hostKind: options.hostKind } : {}),
|
|
262
269
|
...(options.projectDir ? { projectDir: options.projectDir } : {}),
|
|
263
270
|
...(options.events ? { events: options.events } : {}),
|
|
264
|
-
// PD Phase 1.5 (SPEC R10): adapter-supplied environment facts for the
|
|
265
|
-
// forward evidence capture; fields the adapter omits stay NULL.
|
|
266
|
-
...(afterToolCallEnvironment ? {
|
|
267
|
-
environmentProvider: typeof afterToolCallEnvironment === 'function'
|
|
268
|
-
? afterToolCallEnvironment
|
|
269
|
-
: () => afterToolCallEnvironment,
|
|
270
|
-
} : {}),
|
|
271
271
|
}),
|
|
272
|
-
beforeToolCall:
|
|
272
|
+
beforeToolCall: (() => {
|
|
273
|
+
const gate = options.beforeToolCall ?? productionGate;
|
|
274
|
+
const environmentProvider = typeof afterToolCallEnvironment === 'function'
|
|
275
|
+
? afterToolCallEnvironment
|
|
276
|
+
: afterToolCallEnvironment !== undefined
|
|
277
|
+
? () => afterToolCallEnvironment
|
|
278
|
+
: undefined;
|
|
279
|
+
return async (event) => {
|
|
280
|
+
const capture = capturePreGateOpportunity(event, {
|
|
281
|
+
...(options.hostKind !== undefined ? { hostKind: options.hostKind } : {}),
|
|
282
|
+
...(environmentProvider !== undefined ? { environmentProvider } : {}),
|
|
283
|
+
});
|
|
284
|
+
const result = await gate(event);
|
|
285
|
+
const decisionWarnings = capture.opportunityId === null
|
|
286
|
+
? []
|
|
287
|
+
: recordForwardGateDecision({ event, result, opportunityId: capture.opportunityId, hostKind: options.hostKind });
|
|
288
|
+
const warnings = [...capture.warnings, ...decisionWarnings];
|
|
289
|
+
if (warnings.length === 0)
|
|
290
|
+
return result;
|
|
291
|
+
return {
|
|
292
|
+
...result,
|
|
293
|
+
warnings: [...(result.warnings ?? []).slice(0, 15), ...warnings].slice(0, 16),
|
|
294
|
+
metadata: {
|
|
295
|
+
...(result.metadata ?? {}),
|
|
296
|
+
forwardOpportunity: capture.opportunityId === null
|
|
297
|
+
? { status: 'write_degraded' }
|
|
298
|
+
: { status: 'persisted', opportunityId: capture.opportunityId },
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
})(),
|
|
273
303
|
async beforePromptBuild(event) {
|
|
274
304
|
// PRI-904 Phase-1 (Option 3): Codex never writes
|
|
275
305
|
// trajectory.db::user_turns — its ingestion writes governance_* rows
|
|
@@ -0,0 +1,137 @@
|
|
|
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 type { ObservationDatabaseFactory } from './governance-observation-store.js';
|
|
32
|
+
export declare const PAIN_INBOX_TTL_MS: number;
|
|
33
|
+
export declare const PAIN_INBOX_APPROVING_TTL_MS: number;
|
|
34
|
+
export type PainInboxSource = 'gsa' | 'openclaw_confirmation';
|
|
35
|
+
export type PainInboxHostKind = 'codex' | 'workbuddy' | 'openclaw';
|
|
36
|
+
export type PainInboxStatus = 'inbox_candidate' | 'inbox_approving';
|
|
37
|
+
export interface PainInboxItem {
|
|
38
|
+
/** Stable composite item id: `gsa:<logicalObservationKey>` or `oc:<confirmationId>`. */
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly source: PainInboxSource;
|
|
41
|
+
readonly hostKind: PainInboxHostKind;
|
|
42
|
+
readonly sessionId: string;
|
|
43
|
+
readonly signalKind: string;
|
|
44
|
+
readonly status: PainInboxStatus;
|
|
45
|
+
readonly excerpt: string;
|
|
46
|
+
readonly confidence: number | null;
|
|
47
|
+
readonly reason: string | null;
|
|
48
|
+
readonly createdAt: string;
|
|
49
|
+
readonly expiresAt: string;
|
|
50
|
+
}
|
|
51
|
+
export interface ListPainInboxResult {
|
|
52
|
+
readonly ok: true;
|
|
53
|
+
readonly items: readonly PainInboxItem[];
|
|
54
|
+
readonly total: number;
|
|
55
|
+
readonly byHost: {
|
|
56
|
+
readonly openclaw: number;
|
|
57
|
+
readonly codex: number;
|
|
58
|
+
readonly workbuddy: number;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export interface AdmitInboxCandidateInput {
|
|
62
|
+
readonly workspaceDir: string;
|
|
63
|
+
readonly itemId: string;
|
|
64
|
+
/** Optional Owner note or frustration confirmation. */
|
|
65
|
+
readonly ownerNote?: string;
|
|
66
|
+
/** P2-1: calm neutral correction — archive as acknowledged_observation without escalating to Pain. */
|
|
67
|
+
readonly acknowledgeOnly?: boolean;
|
|
68
|
+
readonly now?: Date;
|
|
69
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
70
|
+
}
|
|
71
|
+
export type AdmitInboxCandidateResult = {
|
|
72
|
+
readonly ok: true;
|
|
73
|
+
readonly disposition: 'inbox_approved' | 'already_approved' | 'acknowledged_observation' | 'already_in_progress' | 'not_found' | 'source_revoked' | 'expired';
|
|
74
|
+
readonly itemId: string;
|
|
75
|
+
readonly canonicalPainId?: string;
|
|
76
|
+
readonly diagnosticianTaskId?: string;
|
|
77
|
+
readonly reason?: string;
|
|
78
|
+
} | {
|
|
79
|
+
readonly ok: false;
|
|
80
|
+
readonly reason: string;
|
|
81
|
+
readonly nextAction: string;
|
|
82
|
+
};
|
|
83
|
+
export interface DismissInboxCandidateInput {
|
|
84
|
+
readonly workspaceDir: string;
|
|
85
|
+
readonly itemId: string;
|
|
86
|
+
readonly reason?: string;
|
|
87
|
+
readonly now?: Date;
|
|
88
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
89
|
+
}
|
|
90
|
+
export type DismissInboxCandidateResult = {
|
|
91
|
+
readonly ok: true;
|
|
92
|
+
readonly disposition: 'inbox_dismissed' | 'not_found' | 'already_resolved';
|
|
93
|
+
readonly itemId: string;
|
|
94
|
+
} | {
|
|
95
|
+
readonly ok: false;
|
|
96
|
+
readonly reason: string;
|
|
97
|
+
readonly nextAction: string;
|
|
98
|
+
};
|
|
99
|
+
export interface ExpireStalePainInboxResult {
|
|
100
|
+
readonly ok: boolean;
|
|
101
|
+
readonly expiredGsa: number;
|
|
102
|
+
readonly expiredOpenClaw: number;
|
|
103
|
+
readonly reason?: string;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
|
|
107
|
+
* Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
|
|
108
|
+
* unauthorized hosts (fail-closed consent check).
|
|
109
|
+
*/
|
|
110
|
+
export declare function listPainInboxItems(input: {
|
|
111
|
+
readonly workspaceDir: string;
|
|
112
|
+
readonly hostFilter?: PainInboxHostKind;
|
|
113
|
+
readonly now?: Date;
|
|
114
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
115
|
+
}): ListPainInboxResult;
|
|
116
|
+
/**
|
|
117
|
+
* Owner-approved admission of a Pain Inbox candidate (W3 CAS state machine).
|
|
118
|
+
*
|
|
119
|
+
* Supports both GSA (`gsa:<key>`) and OpenClaw (`oc:<id>`) candidates, bridging
|
|
120
|
+
* OpenClaw approvals onto a unified GSA Admission Marker
|
|
121
|
+
* (`logical_observation_key = 'openclaw:confirmation:<id>'`) and inserting
|
|
122
|
+
* into `pain_events` + `ensureGovernanceDiagnosticianTask()`.
|
|
123
|
+
*/
|
|
124
|
+
export declare function admitOwnerApprovedInboxCandidate(input: AdmitInboxCandidateInput): Promise<AdmitInboxCandidateResult>;
|
|
125
|
+
/**
|
|
126
|
+
* Dismiss a Pain Inbox candidate (CAS terminal `inbox_dismissed`).
|
|
127
|
+
*/
|
|
128
|
+
export declare function dismissPainInboxCandidate(input: DismissInboxCandidateInput): DismissInboxCandidateResult;
|
|
129
|
+
/**
|
|
130
|
+
* 7-day Inbox TTL cleanup across both `governance_signal_admissions` and
|
|
131
|
+
* `signal_confirmations`. Safe to invoke from worker housekeeping cycles.
|
|
132
|
+
*/
|
|
133
|
+
export declare function expireStalePainInboxItems(input: {
|
|
134
|
+
readonly workspaceDir: string;
|
|
135
|
+
readonly now?: Date;
|
|
136
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
137
|
+
}): ExpireStalePainInboxResult;
|