@principles/host-runtime 4.9.4 → 4.11.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/environment-facts.d.ts +12 -0
- package/dist/environment-facts.js +16 -0
- package/dist/governance-signal-admission.d.ts +6 -1
- package/dist/governance-signal-admission.js +50 -8
- 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 +8 -9
- package/dist/index.js +11 -1
- package/dist/internalization-task-executor.d.ts +6 -1
- package/dist/internalization-task-executor.js +6 -2
- package/dist/pain-inbox.d.ts +137 -0
- package/dist/pain-inbox.js +1020 -0
- package/dist/production-pain-evidence.d.ts +1 -1
- package/dist/production-pain-evidence.js +49 -14
- 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,583 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trajectory Stall Detector — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R4 (W5).
|
|
3
|
+
*
|
|
4
|
+
* Detects repeated tool-failure loops ("spinning in place") and routes them
|
|
5
|
+
* strictly to the Owner-confirmable Pain Inbox (`governance_signal_admissions`
|
|
6
|
+
* with `signal_kind = 'trajectory_stall'`, `decision = 'inbox_candidate'`).
|
|
7
|
+
* Never writes directly to `pain_events`.
|
|
8
|
+
*
|
|
9
|
+
* Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.5 / W5):
|
|
10
|
+
* 1. Cross-table deterministic ordering for Codex & WorkBuddy:
|
|
11
|
+
* `tool_calls` is joined to `governance_observations` via
|
|
12
|
+
* `(host_kind, root_session_id = session_id, tool_use_id)` with
|
|
13
|
+
* `kind = 'tool_call'` and `retention_class IN ('operational', 'promoted')`.
|
|
14
|
+
* If ANY tool call in the candidate window matches 0 or >1 observation rows,
|
|
15
|
+
* lacks `tool_use_id`, or has `source_order IS NULL`, returns
|
|
16
|
+
* `status: 'unknown_incomplete'` and skips — NEVER falls back to
|
|
17
|
+
* `tool_calls.created_at`.
|
|
18
|
+
* OpenClaw real-time in-process detection may use `orderMode: 'openclaw_realtime'`
|
|
19
|
+
* which orders directly by monotonic `tc.id DESC` (+ `tc.turn_id`).
|
|
20
|
+
* 2. Structured infrastructure failure classification & null-error degradation:
|
|
21
|
+
* `classifyToolFailureOrigin()` distinguishes `'infrastructure'`,
|
|
22
|
+
* `'actionable_failure'`, and `'unknown'`. Backfilled rows whose
|
|
23
|
+
* `error_type` and `error_message` are both NULL and whose structured
|
|
24
|
+
* facts / preview do not prove a non-infrastructure failure degrade to
|
|
25
|
+
* `'unknown'` and break the streak.
|
|
26
|
+
* 3. Isolation & target path requirement:
|
|
27
|
+
* Strictly isolated by `(host_kind, session_id)`. Both `'success'` and
|
|
28
|
+
* `'unknown'` outcomes, `'infrastructure'` / `'unknown'` failure origins,
|
|
29
|
+
* and missing `normalizedTargetPath` break the consecutive streak.
|
|
30
|
+
* Requires `>= 3` consecutive actionable failures with the same
|
|
31
|
+
* `(toolName, normalizedTargetPath)` fingerprint.
|
|
32
|
+
*/
|
|
33
|
+
import fs from 'node:fs';
|
|
34
|
+
import Database from 'better-sqlite3';
|
|
35
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
36
|
+
import { readSourceMaterialAuthorization } from './source-material-authorization.js';
|
|
37
|
+
export const DEFAULT_STALL_WINDOW_SIZE = 8;
|
|
38
|
+
export const DEFAULT_STALL_MIN_CONSECUTIVE = 3;
|
|
39
|
+
export const MAX_STALL_INBOX_PER_SESSION = 2;
|
|
40
|
+
const INFRASTRUCTURE_ERROR_PATTERNS = [
|
|
41
|
+
/\bprovider_failure\b/i,
|
|
42
|
+
/\brate_limit\b/i,
|
|
43
|
+
/\brate[\s_-]?limit(ed|ing)?\b/i,
|
|
44
|
+
/\btoo many requests\b/i,
|
|
45
|
+
/\bhttp\s*429\b|\bstatus[:=\s]+429\b|\b429\b/i,
|
|
46
|
+
/\bnetwork_timeout\b/i,
|
|
47
|
+
/\betimedout\b/i,
|
|
48
|
+
/\beconnreset\b/i,
|
|
49
|
+
/\beconnrefused\b/i,
|
|
50
|
+
/\benotfound\b/i,
|
|
51
|
+
/\bsocket hang up\b/i,
|
|
52
|
+
/\bupstream_timeout\b/i,
|
|
53
|
+
/\bgateway timeout\b/i,
|
|
54
|
+
/\bservice unavailable\b/i,
|
|
55
|
+
/\boverloaded_error\b/i,
|
|
56
|
+
/\bquota_exceeded\b|\binsufficient_quota\b/i,
|
|
57
|
+
/\bauth_error\b|\bunauthorized\b|\bhttp\s*401\b|\bhttp\s*403\b/i,
|
|
58
|
+
/\bhttp\s*(502|503|504)\b|\bstatus[:=\s]+(502|503|504)\b/i,
|
|
59
|
+
];
|
|
60
|
+
function isRecord(value) {
|
|
61
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
function tableExists(db, name) {
|
|
64
|
+
return (db
|
|
65
|
+
.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1")
|
|
66
|
+
.get(name) !== undefined);
|
|
67
|
+
}
|
|
68
|
+
function nonEmptyString(value) {
|
|
69
|
+
if (typeof value !== 'string')
|
|
70
|
+
return null;
|
|
71
|
+
const trimmed = value.trim();
|
|
72
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
73
|
+
}
|
|
74
|
+
function matchesInfrastructurePattern(text) {
|
|
75
|
+
return INFRASTRUCTURE_ERROR_PATTERNS.some((pattern) => pattern.test(text));
|
|
76
|
+
}
|
|
77
|
+
function extractStructuredToolFacts(rawJson) {
|
|
78
|
+
if (!rawJson)
|
|
79
|
+
return { texts: [], hasActionableFailureSignal: false };
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(rawJson);
|
|
82
|
+
if (!isRecord(parsed))
|
|
83
|
+
return { texts: [], hasActionableFailureSignal: false };
|
|
84
|
+
const facts = isRecord(parsed.facts) ? parsed.facts : parsed;
|
|
85
|
+
const texts = [];
|
|
86
|
+
for (const key of ['errorType', 'error_type', 'errorMessage', 'error_message', 'error', 'stderr', 'message', 'summary', 'reason']) {
|
|
87
|
+
const val = nonEmptyString(facts[key]);
|
|
88
|
+
if (val !== null)
|
|
89
|
+
texts.push(val);
|
|
90
|
+
}
|
|
91
|
+
const exitCode = typeof facts.exitCode === 'number'
|
|
92
|
+
? facts.exitCode
|
|
93
|
+
: typeof facts.exit_code === 'number'
|
|
94
|
+
? facts.exit_code
|
|
95
|
+
: null;
|
|
96
|
+
const hasNonZeroExit = exitCode !== null && exitCode !== 0;
|
|
97
|
+
return {
|
|
98
|
+
texts,
|
|
99
|
+
hasActionableFailureSignal: hasNonZeroExit || texts.length > 0,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return { texts: [], hasActionableFailureSignal: false };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Pure failure origin classifier (TD §2.5 / W5).
|
|
108
|
+
*
|
|
109
|
+
* - Infrastructure/network/provider/rate-limit/auth errors -> 'infrastructure'
|
|
110
|
+
* - Backfilled rows with NULL errorType & errorMessage and no concrete failure
|
|
111
|
+
* evidence in sanitizedToolFactsJson or resultPreview -> 'unknown'
|
|
112
|
+
* - Concrete non-infrastructure failure evidence -> 'actionable_failure'
|
|
113
|
+
*/
|
|
114
|
+
export function classifyToolFailureOrigin(input) {
|
|
115
|
+
if (input.outcome !== undefined && input.outcome !== null && input.outcome !== 'failure') {
|
|
116
|
+
return 'unknown';
|
|
117
|
+
}
|
|
118
|
+
const errorType = nonEmptyString(input.errorType);
|
|
119
|
+
const errorMessage = nonEmptyString(input.errorMessage);
|
|
120
|
+
const resultPreview = nonEmptyString(input.resultPreview);
|
|
121
|
+
const structured = extractStructuredToolFacts(input.sanitizedToolFactsJson);
|
|
122
|
+
const allTexts = [];
|
|
123
|
+
if (errorType !== null)
|
|
124
|
+
allTexts.push(errorType);
|
|
125
|
+
if (errorMessage !== null)
|
|
126
|
+
allTexts.push(errorMessage);
|
|
127
|
+
allTexts.push(...structured.texts);
|
|
128
|
+
if (resultPreview !== null)
|
|
129
|
+
allTexts.push(resultPreview);
|
|
130
|
+
for (const text of allTexts) {
|
|
131
|
+
if (matchesInfrastructurePattern(text)) {
|
|
132
|
+
return 'infrastructure';
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (errorType === null && errorMessage === null) {
|
|
136
|
+
// W5 null-error degradation: only treat as actionable if structured facts
|
|
137
|
+
// or result preview explicitly show a concrete failure signal.
|
|
138
|
+
if (structured.hasActionableFailureSignal) {
|
|
139
|
+
return 'actionable_failure';
|
|
140
|
+
}
|
|
141
|
+
if (resultPreview !== null && /\b(failed|exception|enoent|syntaxerror|typeerror|exit code [1-9]\d*|traceback)\b|\berror\s*:/i.test(resultPreview)) {
|
|
142
|
+
return 'actionable_failure';
|
|
143
|
+
}
|
|
144
|
+
return 'unknown';
|
|
145
|
+
}
|
|
146
|
+
return 'actionable_failure';
|
|
147
|
+
}
|
|
148
|
+
export function extractNormalizedTargetPath(paramsJson) {
|
|
149
|
+
if (!paramsJson)
|
|
150
|
+
return null;
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(paramsJson);
|
|
153
|
+
if (!isRecord(parsed))
|
|
154
|
+
return null;
|
|
155
|
+
const candidates = [
|
|
156
|
+
parsed.file_path,
|
|
157
|
+
parsed.filePath,
|
|
158
|
+
parsed.path,
|
|
159
|
+
parsed.target_path,
|
|
160
|
+
parsed.targetPath,
|
|
161
|
+
parsed.filename,
|
|
162
|
+
parsed.file,
|
|
163
|
+
parsed.target,
|
|
164
|
+
];
|
|
165
|
+
for (const candidate of candidates) {
|
|
166
|
+
const val = nonEmptyString(candidate);
|
|
167
|
+
if (val !== null) {
|
|
168
|
+
return val.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\.\//, '');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
function isRawToolCallRow(value) {
|
|
178
|
+
if (!isRecord(value))
|
|
179
|
+
return false;
|
|
180
|
+
return (typeof value.id === 'number' &&
|
|
181
|
+
typeof value.tool_name === 'string' &&
|
|
182
|
+
typeof value.outcome === 'string' &&
|
|
183
|
+
(value.error_type === null || typeof value.error_type === 'string') &&
|
|
184
|
+
(value.error_message === null || typeof value.error_message === 'string') &&
|
|
185
|
+
typeof value.params_json === 'string' &&
|
|
186
|
+
(value.result_preview === null || typeof value.result_preview === 'string') &&
|
|
187
|
+
(value.tool_use_id === null || typeof value.tool_use_id === 'string') &&
|
|
188
|
+
(value.turn_id === null || typeof value.turn_id === 'string'));
|
|
189
|
+
}
|
|
190
|
+
function isRawObsMatchRow(value) {
|
|
191
|
+
if (!isRecord(value))
|
|
192
|
+
return false;
|
|
193
|
+
return (typeof value.rollout_identity === 'string' &&
|
|
194
|
+
(value.source_order === null || typeof value.source_order === 'number') &&
|
|
195
|
+
(value.source_ordinal === null || typeof value.source_ordinal === 'number') &&
|
|
196
|
+
(value.sanitized_tool_facts_json === null || typeof value.sanitized_tool_facts_json === 'string'));
|
|
197
|
+
}
|
|
198
|
+
function evaluateOrderedWindow(params) {
|
|
199
|
+
const { orderedDesc, hostKind, sessionId, minConsecutive } = params;
|
|
200
|
+
if (orderedDesc.length < minConsecutive) {
|
|
201
|
+
return { status: 'no_stall', reason: 'insufficient_tool_calls' };
|
|
202
|
+
}
|
|
203
|
+
let activeFingerprint = null;
|
|
204
|
+
let activeToolName = '';
|
|
205
|
+
let activeTargetPath = '';
|
|
206
|
+
let rolloutIdentity = '';
|
|
207
|
+
const streakIds = [];
|
|
208
|
+
for (const call of orderedDesc) {
|
|
209
|
+
// Both 'success' and 'unknown' (or any non-'failure') break the streak.
|
|
210
|
+
if (call.outcome !== 'failure') {
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
const origin = classifyToolFailureOrigin({
|
|
214
|
+
outcome: call.outcome,
|
|
215
|
+
errorType: call.errorType,
|
|
216
|
+
errorMessage: call.errorMessage,
|
|
217
|
+
resultPreview: call.resultPreview,
|
|
218
|
+
sanitizedToolFactsJson: call.sanitizedToolFactsJson,
|
|
219
|
+
});
|
|
220
|
+
if (origin !== 'actionable_failure') {
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
const targetPath = extractNormalizedTargetPath(call.paramsJson);
|
|
224
|
+
if (targetPath === null) {
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
const toolName = call.toolName.trim().toLowerCase();
|
|
228
|
+
const fingerprint = `${toolName}::${targetPath}`;
|
|
229
|
+
if (activeFingerprint === null) {
|
|
230
|
+
activeFingerprint = fingerprint;
|
|
231
|
+
activeToolName = call.toolName.trim();
|
|
232
|
+
activeTargetPath = targetPath;
|
|
233
|
+
({ rolloutIdentity } = call);
|
|
234
|
+
streakIds.push(call.id);
|
|
235
|
+
}
|
|
236
|
+
else if (activeFingerprint === fingerprint) {
|
|
237
|
+
streakIds.push(call.id);
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (activeFingerprint !== null && streakIds.length >= minConsecutive) {
|
|
244
|
+
const [latestToolCallId] = streakIds;
|
|
245
|
+
if (latestToolCallId !== undefined) {
|
|
246
|
+
return {
|
|
247
|
+
status: 'stall_detected',
|
|
248
|
+
hostKind,
|
|
249
|
+
sessionId,
|
|
250
|
+
fingerprint: activeFingerprint,
|
|
251
|
+
toolName: activeToolName,
|
|
252
|
+
targetPath: activeTargetPath,
|
|
253
|
+
consecutiveFailures: streakIds.length,
|
|
254
|
+
toolCallIds: streakIds,
|
|
255
|
+
latestToolCallId,
|
|
256
|
+
rolloutIdentity: rolloutIdentity || `${hostKind}:${sessionId}`,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return { status: 'no_stall', reason: 'streak_below_threshold' };
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Evaluate whether `(hostKind, sessionId)` is currently in a repeated-failure
|
|
264
|
+
* trajectory stall. Pure read; never mutates the DB.
|
|
265
|
+
*/
|
|
266
|
+
export function detectTrajectoryStallForSession(input) {
|
|
267
|
+
const minConsecutive = Math.max(2, input.minConsecutive ?? DEFAULT_STALL_MIN_CONSECUTIVE);
|
|
268
|
+
const windowSize = Math.max(minConsecutive, input.windowSize ?? DEFAULT_STALL_WINDOW_SIZE);
|
|
269
|
+
const orderMode = input.orderMode ?? (input.hostKind === 'openclaw' ? 'openclaw_realtime' : 'cross_table');
|
|
270
|
+
const dbPath = resolveTrajectoryDbPath(input.workspaceDir);
|
|
271
|
+
if (!input.databaseFactory && !fs.existsSync(dbPath)) {
|
|
272
|
+
return { status: 'no_stall', reason: 'trajectory_db_absent' };
|
|
273
|
+
}
|
|
274
|
+
let db = null;
|
|
275
|
+
try {
|
|
276
|
+
db = input.databaseFactory
|
|
277
|
+
? input.databaseFactory(dbPath)
|
|
278
|
+
: new Database(dbPath, { readonly: true, fileMustExist: true });
|
|
279
|
+
if (!tableExists(db, 'tool_calls')) {
|
|
280
|
+
return { status: 'no_stall', reason: 'tool_calls_table_absent' };
|
|
281
|
+
}
|
|
282
|
+
if (orderMode === 'openclaw_realtime') {
|
|
283
|
+
const rawRows = db
|
|
284
|
+
.prepare(`SELECT id, tool_name, outcome, error_type, error_message,
|
|
285
|
+
params_json, result_preview, tool_use_id, turn_id
|
|
286
|
+
FROM tool_calls
|
|
287
|
+
WHERE host_kind = ? AND session_id = ?
|
|
288
|
+
ORDER BY id DESC
|
|
289
|
+
LIMIT ?`)
|
|
290
|
+
.all(input.hostKind, input.sessionId, windowSize);
|
|
291
|
+
const rows = Array.isArray(rawRows) ? rawRows.filter(isRawToolCallRow) : [];
|
|
292
|
+
const ordered = rows.map((r) => ({
|
|
293
|
+
id: r.id,
|
|
294
|
+
toolName: r.tool_name,
|
|
295
|
+
outcome: r.outcome,
|
|
296
|
+
errorType: r.error_type,
|
|
297
|
+
errorMessage: r.error_message,
|
|
298
|
+
paramsJson: r.params_json,
|
|
299
|
+
resultPreview: r.result_preview,
|
|
300
|
+
sanitizedToolFactsJson: null,
|
|
301
|
+
sourceOrder: r.id,
|
|
302
|
+
sourceOrdinal: r.id,
|
|
303
|
+
rolloutIdentity: `${input.hostKind}:${input.sessionId}`,
|
|
304
|
+
}));
|
|
305
|
+
return evaluateOrderedWindow({ orderedDesc: ordered, hostKind: input.hostKind, sessionId: input.sessionId, minConsecutive });
|
|
306
|
+
}
|
|
307
|
+
// Cross-table deterministic ordering (W5): requires `governance_observations`
|
|
308
|
+
if (!tableExists(db, 'governance_observations')) {
|
|
309
|
+
return { status: 'unknown_incomplete', reason: 'governance_observations_absent' };
|
|
310
|
+
}
|
|
311
|
+
const rawToolCalls = db
|
|
312
|
+
.prepare(`SELECT id, tool_name, outcome, error_type, error_message,
|
|
313
|
+
params_json, result_preview, tool_use_id, turn_id
|
|
314
|
+
FROM tool_calls
|
|
315
|
+
WHERE host_kind = ? AND session_id = ?`)
|
|
316
|
+
.all(input.hostKind, input.sessionId);
|
|
317
|
+
const toolCalls = Array.isArray(rawToolCalls) ? rawToolCalls.filter(isRawToolCallRow) : [];
|
|
318
|
+
if (toolCalls.length === 0) {
|
|
319
|
+
return { status: 'no_stall', reason: 'no_tool_calls' };
|
|
320
|
+
}
|
|
321
|
+
const obsStmt = db.prepare(`SELECT rollout_identity, source_order, source_ordinal, sanitized_tool_facts_json
|
|
322
|
+
FROM governance_observations
|
|
323
|
+
WHERE host_kind = ?
|
|
324
|
+
AND root_session_id = ?
|
|
325
|
+
AND tool_use_id = ?
|
|
326
|
+
AND kind = 'tool_call'
|
|
327
|
+
AND retention_class IN ('operational', 'promoted')`);
|
|
328
|
+
const joined = [];
|
|
329
|
+
for (const tc of toolCalls) {
|
|
330
|
+
const toolUseId = nonEmptyString(tc.tool_use_id);
|
|
331
|
+
if (toolUseId === null) {
|
|
332
|
+
return { status: 'unknown_incomplete', reason: 'missing_tool_use_id' };
|
|
333
|
+
}
|
|
334
|
+
const rawMatches = obsStmt.all(input.hostKind, input.sessionId, toolUseId);
|
|
335
|
+
const matches = Array.isArray(rawMatches) ? rawMatches.filter(isRawObsMatchRow) : [];
|
|
336
|
+
if (matches.length !== 1) {
|
|
337
|
+
return {
|
|
338
|
+
status: 'unknown_incomplete',
|
|
339
|
+
reason: matches.length === 0 ? 'observation_join_missing' : 'observation_join_ambiguous',
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
const [match] = matches;
|
|
343
|
+
if (!match || match.source_order === null) {
|
|
344
|
+
return { status: 'unknown_incomplete', reason: 'missing_source_order' };
|
|
345
|
+
}
|
|
346
|
+
joined.push({
|
|
347
|
+
id: tc.id,
|
|
348
|
+
toolName: tc.tool_name,
|
|
349
|
+
outcome: tc.outcome,
|
|
350
|
+
errorType: tc.error_type,
|
|
351
|
+
errorMessage: tc.error_message,
|
|
352
|
+
paramsJson: tc.params_json,
|
|
353
|
+
resultPreview: tc.result_preview,
|
|
354
|
+
sanitizedToolFactsJson: match.sanitized_tool_facts_json,
|
|
355
|
+
sourceOrder: match.source_order,
|
|
356
|
+
sourceOrdinal: match.source_ordinal ?? tc.id,
|
|
357
|
+
rolloutIdentity: match.rollout_identity,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
// Sort by true execution order DESC (source_order DESC, COALESCE(source_ordinal, tc.id) DESC)
|
|
361
|
+
joined.sort((a, b) => {
|
|
362
|
+
if (b.sourceOrder !== a.sourceOrder)
|
|
363
|
+
return b.sourceOrder - a.sourceOrder;
|
|
364
|
+
if (b.sourceOrdinal !== a.sourceOrdinal)
|
|
365
|
+
return b.sourceOrdinal - a.sourceOrdinal;
|
|
366
|
+
return b.id - a.id;
|
|
367
|
+
});
|
|
368
|
+
const latestWindow = joined.slice(0, windowSize);
|
|
369
|
+
return evaluateOrderedWindow({ orderedDesc: latestWindow, hostKind: input.hostKind, sessionId: input.sessionId, minConsecutive });
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
return { status: 'unknown_incomplete', reason: 'trajectory_read_error' };
|
|
373
|
+
}
|
|
374
|
+
finally {
|
|
375
|
+
if (db !== null) {
|
|
376
|
+
try {
|
|
377
|
+
db.close();
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
// ignore close errors
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Detect a trajectory stall for `(hostKind, sessionId)` and, if confirmed and
|
|
387
|
+
* authorized, write an Inbox-only candidate (`decision = 'inbox_candidate'`)
|
|
388
|
+
* into `governance_signal_admissions`.
|
|
389
|
+
*/
|
|
390
|
+
export function detectAndAdmitTrajectoryStall(input) {
|
|
391
|
+
const authz = readSourceMaterialAuthorization({
|
|
392
|
+
workspaceDir: input.workspaceDir,
|
|
393
|
+
hostKind: input.hostKind,
|
|
394
|
+
});
|
|
395
|
+
if (authz.status !== 'authorized') {
|
|
396
|
+
return { ok: true, disposition: 'unauthorized', reason: authz.reason };
|
|
397
|
+
}
|
|
398
|
+
const detection = detectTrajectoryStallForSession(input);
|
|
399
|
+
if (detection.status === 'no_stall') {
|
|
400
|
+
return { ok: true, disposition: 'no_stall', reason: detection.reason };
|
|
401
|
+
}
|
|
402
|
+
if (detection.status === 'unknown_incomplete') {
|
|
403
|
+
return { ok: true, disposition: 'unknown_incomplete', reason: detection.reason };
|
|
404
|
+
}
|
|
405
|
+
const dbPath = resolveTrajectoryDbPath(input.workspaceDir);
|
|
406
|
+
if (!input.databaseFactory && !fs.existsSync(dbPath)) {
|
|
407
|
+
return { ok: false, disposition: 'db_unavailable', reason: 'trajectory_db_absent' };
|
|
408
|
+
}
|
|
409
|
+
const nowIso = (input.now ?? new Date()).toISOString();
|
|
410
|
+
const logicalObservationKey = `stall:${detection.hostKind}:${detection.sessionId}:${detection.fingerprint}:${detection.latestToolCallId}`;
|
|
411
|
+
let db = null;
|
|
412
|
+
try {
|
|
413
|
+
db = input.databaseFactory ? input.databaseFactory(dbPath) : new Database(dbPath);
|
|
414
|
+
db.pragma('busy_timeout = 5000');
|
|
415
|
+
if (!tableExists(db, 'governance_signal_admissions')) {
|
|
416
|
+
return { ok: false, disposition: 'db_unavailable', reason: 'gsa_table_absent' };
|
|
417
|
+
}
|
|
418
|
+
const existing = db
|
|
419
|
+
.prepare('SELECT 1 FROM governance_signal_admissions WHERE logical_observation_key = ? LIMIT 1')
|
|
420
|
+
.get(logicalObservationKey);
|
|
421
|
+
if (existing !== undefined) {
|
|
422
|
+
return { ok: true, disposition: 'already_exists', logicalObservationKey };
|
|
423
|
+
}
|
|
424
|
+
const activeCountRow = db
|
|
425
|
+
.prepare(`SELECT COUNT(*) AS n
|
|
426
|
+
FROM governance_signal_admissions
|
|
427
|
+
WHERE host_kind = ?
|
|
428
|
+
AND root_session_id = ?
|
|
429
|
+
AND signal_kind = 'trajectory_stall'
|
|
430
|
+
AND decision IN ('inbox_candidate', 'inbox_approving')`)
|
|
431
|
+
.get(detection.hostKind, detection.sessionId);
|
|
432
|
+
const activeCount = isRecord(activeCountRow) && typeof activeCountRow.n === 'number' ? activeCountRow.n : 0;
|
|
433
|
+
if (activeCount >= MAX_STALL_INBOX_PER_SESSION) {
|
|
434
|
+
return { ok: true, disposition: 'session_cap_reached', logicalObservationKey };
|
|
435
|
+
}
|
|
436
|
+
const excerpt = `${detection.toolName} failed ${detection.consecutiveFailures} consecutive times on ${detection.targetPath}`;
|
|
437
|
+
const payload = {
|
|
438
|
+
signalKind: 'trajectory_stall',
|
|
439
|
+
excerpt,
|
|
440
|
+
confidence: 0.72,
|
|
441
|
+
reasoning: `Detected ${detection.consecutiveFailures} consecutive actionable failures on ${detection.targetPath} using ${detection.toolName}.`,
|
|
442
|
+
fingerprint: detection.fingerprint,
|
|
443
|
+
toolName: detection.toolName,
|
|
444
|
+
targetPath: detection.targetPath,
|
|
445
|
+
consecutiveFailures: detection.consecutiveFailures,
|
|
446
|
+
toolCallIds: detection.toolCallIds,
|
|
447
|
+
detectedAt: nowIso,
|
|
448
|
+
};
|
|
449
|
+
db.prepare(`INSERT OR IGNORE INTO governance_signal_admissions (
|
|
450
|
+
host_kind,
|
|
451
|
+
logical_observation_key,
|
|
452
|
+
rollout_identity,
|
|
453
|
+
root_session_id,
|
|
454
|
+
signal_kind,
|
|
455
|
+
decision,
|
|
456
|
+
canonical_pain_id,
|
|
457
|
+
diagnostician_task_id,
|
|
458
|
+
rule_version,
|
|
459
|
+
reason,
|
|
460
|
+
task_payload_json,
|
|
461
|
+
created_at,
|
|
462
|
+
updated_at
|
|
463
|
+
) VALUES (?, ?, ?, ?, 'trajectory_stall', 'inbox_candidate', NULL, NULL, NULL, 'trajectory_stall_repeated_failure', ?, ?, ?)`).run(detection.hostKind, logicalObservationKey, detection.rolloutIdentity, detection.sessionId, JSON.stringify(payload), nowIso, nowIso);
|
|
464
|
+
return { ok: true, disposition: 'inbox_candidate', logicalObservationKey };
|
|
465
|
+
}
|
|
466
|
+
catch (err) {
|
|
467
|
+
return {
|
|
468
|
+
ok: false,
|
|
469
|
+
disposition: 'db_unavailable',
|
|
470
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
if (db !== null) {
|
|
475
|
+
try {
|
|
476
|
+
db.close();
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
// ignore close errors
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function isSessionKeyRow(value) {
|
|
485
|
+
if (!isRecord(value))
|
|
486
|
+
return false;
|
|
487
|
+
return typeof value.host_kind === 'string' && typeof value.session_id === 'string';
|
|
488
|
+
}
|
|
489
|
+
function isStallHostKind(value) {
|
|
490
|
+
return value === 'codex' || value === 'workbuddy' || value === 'openclaw';
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Bounded workspace-wide scan intended to run inside the existing worker cycle
|
|
494
|
+
* (zero new background services). Scans recent `(host_kind, session_id)` pairs
|
|
495
|
+
* with failures in `tool_calls` and admits confirmed stalls into Pain Inbox.
|
|
496
|
+
*/
|
|
497
|
+
export function scanWorkspaceTrajectoryStalls(input) {
|
|
498
|
+
const maxPerHost = Math.max(1, input.maxSessionsPerHost ?? 10);
|
|
499
|
+
const dbPath = resolveTrajectoryDbPath(input.workspaceDir);
|
|
500
|
+
if (!input.databaseFactory && !fs.existsSync(dbPath)) {
|
|
501
|
+
return {
|
|
502
|
+
scannedSessions: 0,
|
|
503
|
+
admittedInboxCandidates: 0,
|
|
504
|
+
skippedUnknownIncomplete: 0,
|
|
505
|
+
skippedUnauthorized: 0,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
let candidateSessions;
|
|
509
|
+
let db = null;
|
|
510
|
+
try {
|
|
511
|
+
db = input.databaseFactory
|
|
512
|
+
? input.databaseFactory(dbPath)
|
|
513
|
+
: new Database(dbPath, { readonly: true, fileMustExist: true });
|
|
514
|
+
if (!tableExists(db, 'tool_calls')) {
|
|
515
|
+
return {
|
|
516
|
+
scannedSessions: 0,
|
|
517
|
+
admittedInboxCandidates: 0,
|
|
518
|
+
skippedUnknownIncomplete: 0,
|
|
519
|
+
skippedUnauthorized: 0,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
candidateSessions = [];
|
|
523
|
+
for (const hostKind of ['codex', 'workbuddy', 'openclaw']) {
|
|
524
|
+
const rawRows = db
|
|
525
|
+
.prepare(`SELECT host_kind, session_id
|
|
526
|
+
FROM tool_calls
|
|
527
|
+
WHERE outcome = 'failure'
|
|
528
|
+
AND host_kind = ?
|
|
529
|
+
GROUP BY host_kind, session_id
|
|
530
|
+
HAVING COUNT(*) >= ?
|
|
531
|
+
ORDER BY MAX(id) DESC
|
|
532
|
+
LIMIT ?`)
|
|
533
|
+
.all(hostKind, DEFAULT_STALL_MIN_CONSECUTIVE, maxPerHost);
|
|
534
|
+
const rows = Array.isArray(rawRows) ? rawRows.filter(isSessionKeyRow) : [];
|
|
535
|
+
candidateSessions.push(...rows
|
|
536
|
+
.filter((r) => isStallHostKind(r.host_kind))
|
|
537
|
+
.map((r) => ({ hostKind: r.host_kind, sessionId: r.session_id })));
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
catch (error) {
|
|
541
|
+
return {
|
|
542
|
+
scannedSessions: 0,
|
|
543
|
+
admittedInboxCandidates: 0,
|
|
544
|
+
skippedUnknownIncomplete: 0,
|
|
545
|
+
skippedUnauthorized: 0,
|
|
546
|
+
scanError: error instanceof Error ? error.message.slice(0, 160) : String(error).slice(0, 160),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
if (db !== null) {
|
|
551
|
+
try {
|
|
552
|
+
db.close();
|
|
553
|
+
}
|
|
554
|
+
catch {
|
|
555
|
+
// ignore close errors
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
let admittedInboxCandidates = 0;
|
|
560
|
+
let skippedUnknownIncomplete = 0;
|
|
561
|
+
let skippedUnauthorized = 0;
|
|
562
|
+
for (const session of candidateSessions) {
|
|
563
|
+
const res = detectAndAdmitTrajectoryStall({
|
|
564
|
+
workspaceDir: input.workspaceDir,
|
|
565
|
+
hostKind: session.hostKind,
|
|
566
|
+
sessionId: session.sessionId,
|
|
567
|
+
...(input.now ? { now: input.now } : {}),
|
|
568
|
+
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
569
|
+
});
|
|
570
|
+
if (res.disposition === 'inbox_candidate')
|
|
571
|
+
admittedInboxCandidates += 1;
|
|
572
|
+
else if (res.disposition === 'unknown_incomplete')
|
|
573
|
+
skippedUnknownIncomplete += 1;
|
|
574
|
+
else if (res.disposition === 'unauthorized')
|
|
575
|
+
skippedUnauthorized += 1;
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
scannedSessions: candidateSessions.length,
|
|
579
|
+
admittedInboxCandidates,
|
|
580
|
+
skippedUnknownIncomplete,
|
|
581
|
+
skippedUnauthorized,
|
|
582
|
+
};
|
|
583
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.11.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"lint": "eslint \"src/**/*.ts\""
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@principles/core": "^
|
|
42
|
+
"@principles/core": "^9.0.0",
|
|
43
43
|
"@principles/install-layout": "^0.12.0",
|
|
44
44
|
"better-sqlite3": "^13.0.3",
|
|
45
45
|
"js-yaml": "^5.4.3"
|
|
@@ -57,5 +57,5 @@
|
|
|
57
57
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
58
58
|
},
|
|
59
59
|
"license": "Apache-2.0",
|
|
60
|
-
"gitHead": "
|
|
60
|
+
"gitHead": "1e6fc5c3f3083d24dc50a65c420609e21307d9d5"
|
|
61
61
|
}
|