@principles/host-runtime 0.15.1 → 1.0.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.
|
@@ -90,32 +90,7 @@ export interface GovernanceCorrectionCandidate {
|
|
|
90
90
|
*/
|
|
91
91
|
readonly explicitChannel?: 'codex_explicit_prefix' | 'codex_explicit_agent' | 'workbuddy_explicit_prefix';
|
|
92
92
|
}
|
|
93
|
-
export
|
|
94
|
-
readonly kind: 'tool_failure';
|
|
95
|
-
readonly hostKind: 'codex';
|
|
96
|
-
readonly logicalObservationKey: string;
|
|
97
|
-
readonly rolloutIdentity: string;
|
|
98
|
-
readonly rootSessionId: string;
|
|
99
|
-
readonly hostTurnId: string;
|
|
100
|
-
readonly toolName: string;
|
|
101
|
-
/** Host event source (e.g. `codex:post_tool_use`) — identity parity with the live handler. */
|
|
102
|
-
readonly source: string;
|
|
103
|
-
/**
|
|
104
|
-
* I1 identity parity: the host's real per-call id (`tool_use_id`). The live
|
|
105
|
-
* handler's canonical derivation includes it, so candidate builders MUST
|
|
106
|
-
* supply it when the host provided one — a candidate without it would derive
|
|
107
|
-
* a second canonical pain for a call the live path already recorded.
|
|
108
|
-
*/
|
|
109
|
-
readonly toolCallId?: string;
|
|
110
|
-
/** Host tool-call id (SPEC-CODEX-PAIN-CLOSURE-001 CR-01) — same id the live PostToolUse path records into tool_calls.tool_use_id for the dedup join. */
|
|
111
|
-
readonly toolUseId?: string;
|
|
112
|
-
/** Native host cwd, when supplied by a live hook; absent for transcript catch-up. */
|
|
113
|
-
readonly projectDir?: string;
|
|
114
|
-
readonly toolInput?: unknown;
|
|
115
|
-
readonly toolOutput?: unknown;
|
|
116
|
-
readonly observedAt: string;
|
|
117
|
-
}
|
|
118
|
-
export type GovernanceSignalCandidate = GovernanceCorrectionCandidate | GovernanceToolFailureCandidate;
|
|
93
|
+
export type GovernanceSignalCandidate = GovernanceCorrectionCandidate;
|
|
119
94
|
export type GovernanceAdmissionOutcome = {
|
|
120
95
|
disposition: 'admitted';
|
|
121
96
|
kind: GovernanceSignalKind;
|
|
@@ -133,11 +108,6 @@ export type GovernanceAdmissionOutcome = {
|
|
|
133
108
|
disposition: 'not_a_signal';
|
|
134
109
|
kind: 'user_correction';
|
|
135
110
|
logicalObservationKey: string;
|
|
136
|
-
} | {
|
|
137
|
-
disposition: 'not_admitted';
|
|
138
|
-
kind: 'tool_failure';
|
|
139
|
-
logicalObservationKey: string;
|
|
140
|
-
reason: string;
|
|
141
111
|
} | {
|
|
142
112
|
disposition: 'rate_limited';
|
|
143
113
|
kind: 'user_correction';
|
|
@@ -399,52 +369,6 @@ export type EnsureGovernanceContinuationResult = {
|
|
|
399
369
|
* provide the current conversation-ingestion consent.
|
|
400
370
|
*/
|
|
401
371
|
export declare function ensureGovernanceContinuation(input: EnsureGovernanceContinuationInput): Promise<EnsureGovernanceContinuationResult>;
|
|
402
|
-
export interface AdmitBareHostPainsInput {
|
|
403
|
-
readonly workspaceDir: string;
|
|
404
|
-
/** The bare-pain host to sweep. Only the WorkBuddy worker uses this seam today. */
|
|
405
|
-
readonly hostKind: 'workbuddy';
|
|
406
|
-
/** Bounded work per pass (default 5, aligned with the worker's candidate limit). */
|
|
407
|
-
readonly limit?: number;
|
|
408
|
-
readonly now?: Date;
|
|
409
|
-
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
410
|
-
}
|
|
411
|
-
export interface AdmitBareHostPainsResult {
|
|
412
|
-
readonly ok: boolean;
|
|
413
|
-
readonly reason?: string;
|
|
414
|
-
readonly nextAction?: string;
|
|
415
|
-
/** Bare pains that got an admission marker in THIS pass. */
|
|
416
|
-
readonly admitted: number;
|
|
417
|
-
/** Diagnostician tasks actually created in THIS pass (crash-safe ensure). */
|
|
418
|
-
readonly ensured: number;
|
|
419
|
-
/** Bare pains below the admission floor — evidence-only by policy. */
|
|
420
|
-
readonly skippedLowScore: number;
|
|
421
|
-
/** Rows that failed the required-field guard (rc-3: counted, never silent). */
|
|
422
|
-
readonly skippedInvalid: number;
|
|
423
|
-
readonly degradations: readonly string[];
|
|
424
|
-
}
|
|
425
|
-
/**
|
|
426
|
-
* Admit bare host pains — failure rows the shared production pain handler
|
|
427
|
-
* already persisted (host_kind set, canonical_pain_id set, runtime_task_id
|
|
428
|
-
* NULL) but that no inline admission exists for. The WorkBuddy hook is the
|
|
429
|
-
* only evidence producer on that host (SPEC workbuddy-host-adapter §1: no
|
|
430
|
-
* transcript reads), so these rows would otherwise stay stranded as
|
|
431
|
-
* evidence-only forever: reconcile only continues ADMITTED markers, and no
|
|
432
|
-
* WorkBuddy admission step existed (review R2/P1).
|
|
433
|
-
*
|
|
434
|
-
* Policy: only failures scoring at/above the Codex tool_failure admission
|
|
435
|
-
* floor (GOVERNANCE_STRONG_PAIN_SCORE = 70) are queued for diagnosis — that
|
|
436
|
-
* floor is the existing signal-quality boundary for write-tool failures, and
|
|
437
|
-
* lower-scored failures stay evidence-only in pain_events/tool_calls rather
|
|
438
|
-
* than diluting the diagnostician queue. Idempotency reuses the ONE existing
|
|
439
|
-
* authorities: the unique admission marker (canonical_pain_id probe +
|
|
440
|
-
* UNIQUE logical key) and the deterministic task id, so repeated sweeps and
|
|
441
|
-
* crash restarts never mint a second task. Task creation reuses
|
|
442
|
-
* `ensureGovernanceDiagnosticianTask` unchanged (including its Case-B link
|
|
443
|
-
* repair). Evidence promotion is deliberately NOT attempted here: the
|
|
444
|
-
* promotion substrate (governance_rollouts/observations) is fed by transcript
|
|
445
|
-
* ingestion, which the WorkBuddy MVP excludes.
|
|
446
|
-
*/
|
|
447
|
-
export declare function admitBareHostPains(input: AdmitBareHostPainsInput): Promise<AdmitBareHostPainsResult>;
|
|
448
372
|
export interface ReconcileGovernanceContinuationInput {
|
|
449
373
|
readonly workspaceDir: string;
|
|
450
374
|
/** Current Owner consent; false means reconcile may ensure tasks/links but must not read or promote Codex session evidence. */
|
|
@@ -35,8 +35,8 @@ import fs from 'node:fs';
|
|
|
35
35
|
import path from 'node:path';
|
|
36
36
|
import { randomUUID } from 'node:crypto';
|
|
37
37
|
import Database from 'better-sqlite3';
|
|
38
|
-
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS,
|
|
39
|
-
import { deriveProductionCorrectionPainIdentity,
|
|
38
|
+
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, disposePainSignalBridgesForWorkspace, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime-v2';
|
|
39
|
+
import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
|
|
40
40
|
import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
|
|
41
41
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
42
42
|
// ─── Shared detector constants (one truth for both hosts) ───────────────────
|
|
@@ -305,8 +305,8 @@ function ensureGovernanceAdmissionSchema(db) {
|
|
|
305
305
|
db.transaction(() => {
|
|
306
306
|
for (const statement of ADMISSION_CREATE_STATEMENTS)
|
|
307
307
|
db.exec(statement);
|
|
308
|
-
// SPEC-CODEX-PAIN-CLOSURE-001 CR-01:
|
|
309
|
-
//
|
|
308
|
+
// SPEC-CODEX-PAIN-CLOSURE-001 CR-01: trajectory evidence writers persist
|
|
309
|
+
// tool_calls; make sure the host tool-use-id join column exists on
|
|
310
310
|
// workspaces whose base schema predates it (idempotent additive ALTER —
|
|
311
311
|
// only when the table itself exists: governance-only databases without a
|
|
312
312
|
// tool_calls table are a valid pre-existing state, not an error).
|
|
@@ -439,29 +439,6 @@ function insertCorrectionPain({ db, candidate, workspaceDir, painId, reason, now
|
|
|
439
439
|
.run(candidate.rootSessionId, 'user_correction', GOVERNANCE_STRONG_PAIN_SCORE, reason.slice(0, MAX_REASON_BOUND), 'severe', 'system_infer', null, excerpt, painId, null, candidate.hostKind, nowIso);
|
|
440
440
|
return reason;
|
|
441
441
|
}
|
|
442
|
-
/**
|
|
443
|
-
* ONE builder for the tool_failure task payload shape — the Codex inline
|
|
444
|
-
* admission path and the WorkBuddy bare-pain sweep must produce the SAME
|
|
445
|
-
* shape, differing only in the attributed host and the pain facts.
|
|
446
|
-
*/
|
|
447
|
-
function buildToolFailureTaskPayload(fields) {
|
|
448
|
-
// P1-1 privacy (review round 2): sanitize the FULL text before any
|
|
449
|
-
// truncation — a token crossing the 200-char boundary must be redacted, not
|
|
450
|
-
// split into a fragment that survives verbatim. sanitizeString bounds itself.
|
|
451
|
-
const payload = {
|
|
452
|
-
painType: 'tool_failure',
|
|
453
|
-
source: fields.toolName,
|
|
454
|
-
reason: fields.reason || `tool=${fields.toolName}`,
|
|
455
|
-
score: fields.score,
|
|
456
|
-
sessionId: fields.sessionId,
|
|
457
|
-
hostKind: fields.hostKind,
|
|
458
|
-
evidence: [{ sourceRef: `governance_observation:${fields.logicalObservationKey}`, note: sanitizeString(fields.reason || fields.toolName, fields.workspaceDir) }],
|
|
459
|
-
};
|
|
460
|
-
return payload;
|
|
461
|
-
}
|
|
462
|
-
function toolFailureTaskPayload(fields) {
|
|
463
|
-
return JSON.stringify(buildToolFailureTaskPayload(fields));
|
|
464
|
-
}
|
|
465
442
|
/**
|
|
466
443
|
* P1 (review round 3): a `behavior_trace` may only name a row that EXISTS in
|
|
467
444
|
* trajectory.db with the SAME lineage tuple. WorkBuddy currently has no
|
|
@@ -486,47 +463,36 @@ function persistedBehaviorTraceEvidence(args) {
|
|
|
486
463
|
}
|
|
487
464
|
function buildTaskSubmissionPayload(candidate, workspaceDir, details) {
|
|
488
465
|
const { reason, db } = details;
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
score: GOVERNANCE_STRONG_PAIN_SCORE,
|
|
498
|
-
sessionId: candidate.rootSessionId,
|
|
499
|
-
hostKind: candidate.hostKind,
|
|
500
|
-
evidence: persistedBehaviorTraceEvidence({
|
|
501
|
-
db,
|
|
502
|
-
hostKind: candidate.hostKind,
|
|
503
|
-
logicalObservationKey: candidate.logicalObservationKey,
|
|
504
|
-
rolloutIdentity: candidate.rolloutIdentity,
|
|
505
|
-
rootSessionId: candidate.rootSessionId,
|
|
506
|
-
hostTurnId: candidate.hostTurnId,
|
|
507
|
-
text: candidate.text,
|
|
508
|
-
workspaceDir,
|
|
509
|
-
}),
|
|
510
|
-
// SPEC-CODEX-PAIN-CLOSURE-001 CR-02 (merged from main): an explicit
|
|
511
|
-
// Owner statement rides as classified correction evidence — never
|
|
512
|
-
// summarized by an AI, never inside evidence[] pseudo-trace entries.
|
|
513
|
-
...(candidate.explicitOwnerStatement === true
|
|
514
|
-
? { correctionEvidence: candidate.hostKind === 'workbuddy'
|
|
515
|
-
? { text: boundCorrectionEvidenceText({ text: candidate.text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }, workspaceDir).text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }
|
|
516
|
-
: { text: sanitizeString(candidate.text, workspaceDir), classification: 'owner_statement', channel: candidate.explicitChannel === 'codex_explicit_agent' ? 'codex_explicit_agent' : 'codex_explicit_prefix' } }
|
|
517
|
-
: {}),
|
|
518
|
-
};
|
|
519
|
-
return payload;
|
|
520
|
-
}
|
|
521
|
-
return buildToolFailureTaskPayload({
|
|
522
|
-
hostKind: candidate.hostKind,
|
|
523
|
-
logicalObservationKey: candidate.logicalObservationKey,
|
|
466
|
+
// P1-1 privacy (review round 2): sanitize the FULL text before any
|
|
467
|
+
// truncation — a token crossing the 200-char boundary must be redacted, not
|
|
468
|
+
// split into a fragment that survives verbatim. sanitizeString bounds itself.
|
|
469
|
+
const payload = {
|
|
470
|
+
painType: 'user_frustration',
|
|
471
|
+
source: 'user_correction',
|
|
472
|
+
reason: reason || 'User correction detected',
|
|
473
|
+
score: GOVERNANCE_STRONG_PAIN_SCORE,
|
|
524
474
|
sessionId: candidate.rootSessionId,
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
475
|
+
hostKind: candidate.hostKind,
|
|
476
|
+
evidence: persistedBehaviorTraceEvidence({
|
|
477
|
+
db,
|
|
478
|
+
hostKind: candidate.hostKind,
|
|
479
|
+
logicalObservationKey: candidate.logicalObservationKey,
|
|
480
|
+
rolloutIdentity: candidate.rolloutIdentity,
|
|
481
|
+
rootSessionId: candidate.rootSessionId,
|
|
482
|
+
hostTurnId: candidate.hostTurnId,
|
|
483
|
+
text: candidate.text,
|
|
484
|
+
workspaceDir,
|
|
485
|
+
}),
|
|
486
|
+
// SPEC-CODEX-PAIN-CLOSURE-001 CR-02 (merged from main): an explicit
|
|
487
|
+
// Owner statement rides as classified correction evidence — never
|
|
488
|
+
// summarized by an AI, never inside evidence[] pseudo-trace entries.
|
|
489
|
+
...(candidate.explicitOwnerStatement === true
|
|
490
|
+
? { correctionEvidence: candidate.hostKind === 'workbuddy'
|
|
491
|
+
? { text: boundCorrectionEvidenceText({ text: candidate.text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }, workspaceDir).text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }
|
|
492
|
+
: { text: sanitizeString(candidate.text, workspaceDir), classification: 'owner_statement', channel: candidate.explicitChannel === 'codex_explicit_agent' ? 'codex_explicit_agent' : 'codex_explicit_prefix' } }
|
|
493
|
+
: {}),
|
|
494
|
+
};
|
|
495
|
+
return payload;
|
|
530
496
|
}
|
|
531
497
|
function taskSubmissionPayload(candidate, workspaceDir, details) {
|
|
532
498
|
return JSON.stringify(buildTaskSubmissionPayload(candidate, workspaceDir, details));
|
|
@@ -1040,106 +1006,6 @@ function admitCorrection({ db, candidate, workspaceDir, now, nowIso, keywordStor
|
|
|
1040
1006
|
}
|
|
1041
1007
|
return { disposition: 'admitted', kind: 'user_correction', logicalObservationKey: candidate.logicalObservationKey, canonicalPainId: painId, duplicate, ruleVersion: detection?.ruleVersion ?? null };
|
|
1042
1008
|
}
|
|
1043
|
-
function admitToolFailure({ db, candidate, workspaceDir, nowIso }) {
|
|
1044
|
-
const identity = deriveProductionToolPainIdentity({
|
|
1045
|
-
workspaceDir,
|
|
1046
|
-
sessionId: candidate.rootSessionId,
|
|
1047
|
-
turnId: candidate.hostTurnId,
|
|
1048
|
-
toolName: candidate.toolName,
|
|
1049
|
-
source: candidate.source,
|
|
1050
|
-
// I1 identity parity: same call id the live handler derived from (the
|
|
1051
|
-
// candidate builder forwards the host `tool_use_id`).
|
|
1052
|
-
...(candidate.toolCallId !== undefined ? { toolCallId: candidate.toolCallId } : {}),
|
|
1053
|
-
...(candidate.toolInput !== undefined ? { toolInput: candidate.toolInput } : {}),
|
|
1054
|
-
...(candidate.toolOutput !== undefined ? { toolOutput: candidate.toolOutput } : {}),
|
|
1055
|
-
});
|
|
1056
|
-
const { outcome, sanitizedParams, paramsJson, resultPreview, painId } = identity;
|
|
1057
|
-
// Admission gate — identical semantics to the live production handler on a
|
|
1058
|
-
// fresh process (ADR-0020 accepts cold in-memory cooldowns for Codex;
|
|
1059
|
-
// canonical idempotency is the guard).
|
|
1060
|
-
const sourceObservation = buildToolFailureObservation({ toolName: candidate.toolName, error: outcome.error, exitCode: outcome.exitCode ?? undefined });
|
|
1061
|
-
const sourceKind = resolveSourceKind({
|
|
1062
|
-
observedAt: nowIso,
|
|
1063
|
-
workspaceId: workspaceDir,
|
|
1064
|
-
sessionId: candidate.rootSessionId,
|
|
1065
|
-
toolName: candidate.toolName,
|
|
1066
|
-
failureSource: sourceObservation.failureSource,
|
|
1067
|
-
toolNotFound: sourceObservation.toolNotFound,
|
|
1068
|
-
nonZeroExit: outcome.exitCode !== null && outcome.exitCode !== 0,
|
|
1069
|
-
});
|
|
1070
|
-
// Risk evaluation mirrors the production handler: it reads the RAW params
|
|
1071
|
-
// (sanitized params replace paths with placeholders and would lose the
|
|
1072
|
-
// absolute-path risk signal). Identity still uses sanitized params.
|
|
1073
|
-
const rawFile = isRecord(outcome.params) ? (own(outcome.params, 'file_path') ?? own(outcome.params, 'path')) : undefined;
|
|
1074
|
-
const relativePath = String(rawFile ?? 'unknown').slice(0, 500);
|
|
1075
|
-
const isRisky = path.isAbsolute(relativePath) && !path.resolve(relativePath).startsWith(`${workspaceDir}${path.sep}`);
|
|
1076
|
-
const painScore = Math.min(100, (outcome.failure ? 70 : 0) + (isRisky ? 20 : 0));
|
|
1077
|
-
const triage = evaluateTriage({ sourceKind, score: painScore, isRisky });
|
|
1078
|
-
const trigger = evaluateTriggerController({ triageResult: triage, isOwnerManual: false, isCooldownActive: false, isValid: true, score: painScore, sessionId: candidate.rootSessionId });
|
|
1079
|
-
const gateAdmitted = outcome.failure && PRODUCTION_WRITE_TOOLS.has(candidate.toolName) && trigger.shouldCreateDiagnosticTask;
|
|
1080
|
-
void sanitizedParams;
|
|
1081
|
-
if (!gateAdmitted) {
|
|
1082
|
-
return { disposition: 'not_admitted', kind: 'tool_failure', logicalObservationKey: candidate.logicalObservationKey, reason: trigger.reason };
|
|
1083
|
-
}
|
|
1084
|
-
let duplicate = false;
|
|
1085
|
-
let duplicateWithoutPain = false;
|
|
1086
|
-
let reason = '';
|
|
1087
|
-
db.transaction(() => {
|
|
1088
|
-
// Same duplicate probes as the production handler: the host tool-call id
|
|
1089
|
-
// (CR-01) is the stable join key; the content-shape probe stays the
|
|
1090
|
-
// fallback for hosts/candidates without ids.
|
|
1091
|
-
// Review R3/P2: admission dedup is host-scoped — a colliding row from
|
|
1092
|
-
// another host is not this candidate's duplicate.
|
|
1093
|
-
if (candidate.toolUseId !== undefined
|
|
1094
|
-
&& (candidate.hostKind !== undefined
|
|
1095
|
-
? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(candidate.rootSessionId, candidate.toolUseId, candidate.hostKind)
|
|
1096
|
-
: db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(candidate.rootSessionId, candidate.toolUseId)) !== undefined) {
|
|
1097
|
-
duplicate = true;
|
|
1098
|
-
duplicateWithoutPain = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) === undefined;
|
|
1099
|
-
}
|
|
1100
|
-
else if ((candidate.hostKind !== undefined
|
|
1101
|
-
? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?')
|
|
1102
|
-
.get(candidate.rootSessionId, candidate.toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, candidate.hostKind)
|
|
1103
|
-
: db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?')
|
|
1104
|
-
.get(candidate.rootSessionId, candidate.toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
|
|
1105
|
-
duplicate = true;
|
|
1106
|
-
duplicateWithoutPain = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) === undefined;
|
|
1107
|
-
}
|
|
1108
|
-
else {
|
|
1109
|
-
db.prepare(`INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at`)
|
|
1110
|
-
.run(candidate.rootSessionId, nowIso, nowIso);
|
|
1111
|
-
const projectDir = typeof candidate.projectDir === 'string' && path.isAbsolute(candidate.projectDir)
|
|
1112
|
-
? path.resolve(candidate.projectDir)
|
|
1113
|
-
: null;
|
|
1114
|
-
db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1115
|
-
.run(candidate.rootSessionId, candidate.toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, null, null, paramsJson, resultPreview, nowIso, candidate.toolUseId ?? null, projectDir, candidate.hostKind);
|
|
1116
|
-
reason = `tool=${candidate.toolName}; error=${outcome.error ?? `exit=${outcome.exitCode}`}; path=${relativePath}`;
|
|
1117
|
-
db.prepare(`INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, host_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1118
|
-
.run(candidate.rootSessionId, sourceObservation.failureSource ?? 'tool_failure', painScore, reason, painScore >= 70 ? 'severe' : painScore >= 40 ? 'moderate' : 'mild', 'system_infer', null, null, painId, null, candidate.hostKind, nowIso);
|
|
1119
|
-
}
|
|
1120
|
-
// PRI-640 §17: enrich unknown → codex on the already-admitted duplicate
|
|
1121
|
-
// pain row; the IS NULL guard keeps any durable attribution.
|
|
1122
|
-
db.prepare('UPDATE pain_events SET host_kind = ? WHERE canonical_pain_id = ? AND host_kind IS NULL').run(candidate.hostKind, painId);
|
|
1123
|
-
if (!duplicateWithoutPain) {
|
|
1124
|
-
insertAdmissionMarker({
|
|
1125
|
-
db,
|
|
1126
|
-
identity: { hostKind: candidate.hostKind, logicalObservationKey: candidate.logicalObservationKey, rolloutIdentity: candidate.rolloutIdentity, rootSessionId: candidate.rootSessionId, signalKind: candidate.kind },
|
|
1127
|
-
canonicalPainId: painId,
|
|
1128
|
-
ruleVersion: null,
|
|
1129
|
-
reason: sanitizeString(reason, workspaceDir),
|
|
1130
|
-
payloadJson: taskSubmissionPayload(candidate, workspaceDir, { reason, db }),
|
|
1131
|
-
nowIso,
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
// A duplicate call row without an admitted pain mirrors the production
|
|
1135
|
-
// handler (no pain insert on duplicates) and records no marker, so a later
|
|
1136
|
-
// delivery whose gate reaches threshold can still admit.
|
|
1137
|
-
})();
|
|
1138
|
-
if (duplicateWithoutPain) {
|
|
1139
|
-
return { disposition: 'not_admitted', kind: 'tool_failure', logicalObservationKey: candidate.logicalObservationKey, reason: 'duplicate_tool_call_without_admitted_pain' };
|
|
1140
|
-
}
|
|
1141
|
-
return { disposition: 'admitted', kind: 'tool_failure', logicalObservationKey: candidate.logicalObservationKey, canonicalPainId: painId, duplicate, ruleVersion: null };
|
|
1142
|
-
}
|
|
1143
1009
|
function admitOne({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDegradation, trustedWorkbuddyLive }) {
|
|
1144
1010
|
if (candidate.hostKind !== 'codex' && !(candidate.hostKind === 'workbuddy' && candidate.kind === 'user_correction' && (candidate.explicitOwnerStatement === true || trustedWorkbuddyLive === true))) {
|
|
1145
1011
|
return { ok: false, reason: 'unsupported_host_kind', nextAction: 'governance signal admission accepts Codex observations or explicit WorkBuddy Owner statements' };
|
|
@@ -1171,10 +1037,7 @@ function admitOne({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDe
|
|
|
1171
1037
|
};
|
|
1172
1038
|
}
|
|
1173
1039
|
try {
|
|
1174
|
-
|
|
1175
|
-
return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
|
|
1176
|
-
}
|
|
1177
|
-
return admitToolFailure({ db, candidate, workspaceDir, nowIso });
|
|
1040
|
+
return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
|
|
1178
1041
|
}
|
|
1179
1042
|
catch (error) {
|
|
1180
1043
|
// RateLimitedSignal never reaches here — admitCorrection converts it to a
|
|
@@ -2117,129 +1980,6 @@ export async function ensureGovernanceContinuation(input) {
|
|
|
2117
1980
|
close();
|
|
2118
1981
|
}
|
|
2119
1982
|
}
|
|
2120
|
-
/**
|
|
2121
|
-
* Admit bare host pains — failure rows the shared production pain handler
|
|
2122
|
-
* already persisted (host_kind set, canonical_pain_id set, runtime_task_id
|
|
2123
|
-
* NULL) but that no inline admission exists for. The WorkBuddy hook is the
|
|
2124
|
-
* only evidence producer on that host (SPEC workbuddy-host-adapter §1: no
|
|
2125
|
-
* transcript reads), so these rows would otherwise stay stranded as
|
|
2126
|
-
* evidence-only forever: reconcile only continues ADMITTED markers, and no
|
|
2127
|
-
* WorkBuddy admission step existed (review R2/P1).
|
|
2128
|
-
*
|
|
2129
|
-
* Policy: only failures scoring at/above the Codex tool_failure admission
|
|
2130
|
-
* floor (GOVERNANCE_STRONG_PAIN_SCORE = 70) are queued for diagnosis — that
|
|
2131
|
-
* floor is the existing signal-quality boundary for write-tool failures, and
|
|
2132
|
-
* lower-scored failures stay evidence-only in pain_events/tool_calls rather
|
|
2133
|
-
* than diluting the diagnostician queue. Idempotency reuses the ONE existing
|
|
2134
|
-
* authorities: the unique admission marker (canonical_pain_id probe +
|
|
2135
|
-
* UNIQUE logical key) and the deterministic task id, so repeated sweeps and
|
|
2136
|
-
* crash restarts never mint a second task. Task creation reuses
|
|
2137
|
-
* `ensureGovernanceDiagnosticianTask` unchanged (including its Case-B link
|
|
2138
|
-
* repair). Evidence promotion is deliberately NOT attempted here: the
|
|
2139
|
-
* promotion substrate (governance_rollouts/observations) is fed by transcript
|
|
2140
|
-
* ingestion, which the WorkBuddy MVP excludes.
|
|
2141
|
-
*/
|
|
2142
|
-
export async function admitBareHostPains(input) {
|
|
2143
|
-
const opened = openAdmissionStore(input.workspaceDir, input.databaseFactory);
|
|
2144
|
-
if (!('db' in opened)) {
|
|
2145
|
-
return { ok: false, reason: opened.reason, nextAction: opened.nextAction, admitted: 0, ensured: 0, skippedLowScore: 0, skippedInvalid: 0, degradations: [opened.reason] };
|
|
2146
|
-
}
|
|
2147
|
-
const { db, close } = opened;
|
|
2148
|
-
if (!hasProductionPainSchema(db)) {
|
|
2149
|
-
close();
|
|
2150
|
-
return { ok: false, reason: 'trajectory_schema_invalid', nextAction: 'run the supported PD workspace migration before enabling the worker', admitted: 0, ensured: 0, skippedLowScore: 0, skippedInvalid: 0, degradations: ['trajectory_schema_invalid'] };
|
|
2151
|
-
}
|
|
2152
|
-
const nowIso = (input.now ?? new Date()).toISOString();
|
|
2153
|
-
const workspaceDir = path.resolve(input.workspaceDir);
|
|
2154
|
-
const limit = Math.min(Math.max(input.limit ?? 5, 1), 50);
|
|
2155
|
-
// Bare pains of this host that no admission marker covers yet. A marker is
|
|
2156
|
-
// the durable "already handled" fact; runtime_task_id additionally excludes
|
|
2157
|
-
// pains that reached a task through another path.
|
|
2158
|
-
const barePainPredicate = `
|
|
2159
|
-
FROM pain_events p
|
|
2160
|
-
WHERE p.host_kind = ?
|
|
2161
|
-
AND p.runtime_task_id IS NULL
|
|
2162
|
-
AND p.canonical_pain_id IS NOT NULL
|
|
2163
|
-
AND NOT EXISTS (SELECT 1 FROM governance_signal_admissions a WHERE a.canonical_pain_id = p.canonical_pain_id)`;
|
|
2164
|
-
try {
|
|
2165
|
-
const lowScoreRow = db.prepare(`SELECT COUNT(*) AS n ${barePainPredicate} AND p.score < ?`).get(input.hostKind, GOVERNANCE_STRONG_PAIN_SCORE);
|
|
2166
|
-
const skippedLowScore = typeof rowField(lowScoreRow, 'n') === 'number' ? rowField(lowScoreRow, 'n') : 0;
|
|
2167
|
-
const rows = db.prepare(`SELECT p.canonical_pain_id, p.session_id, p.source, p.score, p.reason ${barePainPredicate} AND p.score >= ? ORDER BY p.id LIMIT ?`)
|
|
2168
|
-
.all(input.hostKind, GOVERNANCE_STRONG_PAIN_SCORE, limit);
|
|
2169
|
-
let admitted = 0;
|
|
2170
|
-
let ensured = 0;
|
|
2171
|
-
let skippedInvalid = 0;
|
|
2172
|
-
const degradations = [];
|
|
2173
|
-
const freshMarkers = [];
|
|
2174
|
-
for (const row of rows) {
|
|
2175
|
-
const painId = rowField(row, 'canonical_pain_id');
|
|
2176
|
-
const sessionId = rowField(row, 'session_id');
|
|
2177
|
-
const score = rowField(row, 'score');
|
|
2178
|
-
if (typeof painId !== 'string' || painId.length === 0 || typeof sessionId !== 'string' || sessionId.length === 0
|
|
2179
|
-
|| typeof score !== 'number' || !Number.isFinite(score)) {
|
|
2180
|
-
skippedInvalid += 1;
|
|
2181
|
-
continue;
|
|
2182
|
-
}
|
|
2183
|
-
const logicalObservationKey = `${input.hostKind}|${sessionId}|${painId}`;
|
|
2184
|
-
const reason = typeof rowField(row, 'reason') === 'string' ? rowField(row, 'reason') : '';
|
|
2185
|
-
const source = typeof rowField(row, 'source') === 'string' ? rowField(row, 'source') : 'tool_failure';
|
|
2186
|
-
// The pain row carries the tool name only inside its reason prefix
|
|
2187
|
-
// (`tool=<name>; ...` — the production writer's format); the row's
|
|
2188
|
-
// source column is the failure class, used as the fallback.
|
|
2189
|
-
const toolName = /^tool=([^;]{1,120});/.exec(reason)?.[1] ?? source;
|
|
2190
|
-
const inserted = db.transaction(() => {
|
|
2191
|
-
// Re-probe inside the transaction: a concurrent sweep or live admission
|
|
2192
|
-
// may have marked this pain between the scan and this write.
|
|
2193
|
-
if (db.prepare('SELECT 1 FROM governance_signal_admissions WHERE canonical_pain_id = ?').get(painId) !== undefined)
|
|
2194
|
-
return false;
|
|
2195
|
-
insertAdmissionMarker({
|
|
2196
|
-
db,
|
|
2197
|
-
identity: { hostKind: input.hostKind, logicalObservationKey, rolloutIdentity: sessionId, rootSessionId: sessionId, signalKind: 'tool_failure' },
|
|
2198
|
-
canonicalPainId: painId,
|
|
2199
|
-
ruleVersion: null,
|
|
2200
|
-
reason,
|
|
2201
|
-
payloadJson: toolFailureTaskPayload({ hostKind: input.hostKind, logicalObservationKey, sessionId, toolName, reason, score, workspaceDir }),
|
|
2202
|
-
nowIso,
|
|
2203
|
-
});
|
|
2204
|
-
return true;
|
|
2205
|
-
})();
|
|
2206
|
-
if (inserted) {
|
|
2207
|
-
admitted += 1;
|
|
2208
|
-
freshMarkers.push({ logicalObservationKey, canonicalPainId: painId });
|
|
2209
|
-
}
|
|
2210
|
-
}
|
|
2211
|
-
// Reuse the crash-safe ensure semantics unchanged: deterministic task id,
|
|
2212
|
-
// task-store PK idempotency, Case-B link repair.
|
|
2213
|
-
for (const marker of freshMarkers) {
|
|
2214
|
-
const continuation = await ensureGovernanceDiagnosticianTask({
|
|
2215
|
-
workspaceDir,
|
|
2216
|
-
logicalObservationKey: marker.logicalObservationKey,
|
|
2217
|
-
canonicalPainId: marker.canonicalPainId,
|
|
2218
|
-
...(input.databaseFactory ? { databaseFactory: input.databaseFactory } : {}),
|
|
2219
|
-
});
|
|
2220
|
-
if (continuation.ok) {
|
|
2221
|
-
if (continuation.created)
|
|
2222
|
-
ensured += 1;
|
|
2223
|
-
}
|
|
2224
|
-
else {
|
|
2225
|
-
degradations.push(`${marker.logicalObservationKey}:${continuation.reason}`);
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
2228
|
-
return {
|
|
2229
|
-
ok: degradations.length === 0,
|
|
2230
|
-
...(degradations.length > 0 ? { reason: 'bare_pain_admission_degradations', nextAction: 'inspect the per-item degradations; the admitted pains and markers remain durable and reconcile retries task creation' } : {}),
|
|
2231
|
-
admitted, ensured, skippedLowScore, skippedInvalid,
|
|
2232
|
-
degradations: degradations.slice(0, 10),
|
|
2233
|
-
};
|
|
2234
|
-
}
|
|
2235
|
-
catch (error) {
|
|
2236
|
-
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
2237
|
-
return { ok: false, reason: `bare_pain_admission_failed:${detail}`, nextAction: 'inspect the workspace trajectory database and retry; committed markers remain durable', admitted: 0, ensured: 0, skippedLowScore: 0, skippedInvalid: 0, degradations: [`bare_pain_admission_failed:${detail}`] };
|
|
2238
|
-
}
|
|
2239
|
-
finally {
|
|
2240
|
-
close();
|
|
2241
|
-
}
|
|
2242
|
-
}
|
|
2243
1983
|
/**
|
|
2244
1984
|
* Narrow idempotent reconciliation between the trajectory admission markers
|
|
2245
1985
|
* and the Runtime V2 task store (separate SQLite databases — no cross-store
|
|
@@ -1,80 +1,14 @@
|
|
|
1
1
|
import Database from 'better-sqlite3';
|
|
2
2
|
import type { GovernanceHostKind } from '@principles/core/runtime-v2';
|
|
3
3
|
import type { HostEvent, HostEventEmitter, HostEventResult } from '@principles/core/host';
|
|
4
|
-
/** Shared with the governance admission path so both gate tool failures identically. */
|
|
5
|
-
export declare const PRODUCTION_WRITE_TOOLS: ReadonlySet<string>;
|
|
6
|
-
export interface PainEvidenceEntry {
|
|
7
|
-
sourceRef: string;
|
|
8
|
-
note: string;
|
|
9
|
-
}
|
|
10
4
|
export interface ProductionPainEnrichment {
|
|
5
|
+
/** Stable host-supplied occurrence identity for the tool call. */
|
|
11
6
|
eventId?: string;
|
|
12
|
-
painScore?: number;
|
|
13
|
-
isRisky?: boolean;
|
|
14
|
-
consecutiveErrors?: number;
|
|
15
|
-
relativePath?: string;
|
|
16
|
-
agentId?: string;
|
|
17
|
-
errorHash?: string;
|
|
18
|
-
evidence?: readonly PainEvidenceEntry[];
|
|
19
7
|
}
|
|
20
8
|
export type PainEnrichmentProvider = (event: HostEvent) => unknown | Promise<unknown>;
|
|
21
9
|
export type PainDatabaseFactory = (databasePath: string) => Database.Database;
|
|
22
10
|
/** SPEC-CODEX-PAIN-CLOSURE-001 CR-01: a tool result is success, failure or unknown. */
|
|
23
11
|
export type ToolOutcomeClassification = 'success' | 'failure' | 'unknown';
|
|
24
|
-
interface NormalizedOutcome {
|
|
25
|
-
outcome: ToolOutcomeClassification;
|
|
26
|
-
failure: boolean;
|
|
27
|
-
exitCode: number | null;
|
|
28
|
-
/** Bounded structured reason present when the outcome is unknown (rc-9). */
|
|
29
|
-
unknownReason?: string;
|
|
30
|
-
error?: string;
|
|
31
|
-
durationMs?: number;
|
|
32
|
-
params: unknown;
|
|
33
|
-
result: unknown;
|
|
34
|
-
}
|
|
35
|
-
/** Structural input accepted by the canonical derivations (HostEvent satisfies it without a cast). */
|
|
36
|
-
export interface ProductionToolEventFields {
|
|
37
|
-
workspaceDir: string;
|
|
38
|
-
sessionId: string;
|
|
39
|
-
turnId?: string;
|
|
40
|
-
/**
|
|
41
|
-
* I1: the host's real per-call identity (Codex `tool_use_id`, WorkBuddy
|
|
42
|
-
* `call_id`). Two calls with the same session/generation/tool/params/result
|
|
43
|
-
* but DIFFERENT call ids are two real occurrences and must derive two
|
|
44
|
-
* identities; a redelivery of the SAME call id is one occurrence. Optional:
|
|
45
|
-
* hosts that supply no call id keep the historical content-derived identity
|
|
46
|
-
* (identical-content calls then cannot be distinguished — a documented
|
|
47
|
-
* limitation, never fabricated precision).
|
|
48
|
-
*/
|
|
49
|
-
toolCallId?: string;
|
|
50
|
-
toolName?: string;
|
|
51
|
-
toolInput?: unknown;
|
|
52
|
-
toolOutput?: unknown;
|
|
53
|
-
source: string;
|
|
54
|
-
}
|
|
55
|
-
export interface DerivedToolPainIdentity {
|
|
56
|
-
eventId: string;
|
|
57
|
-
painId: string;
|
|
58
|
-
outcome: NormalizedOutcome;
|
|
59
|
-
sanitizedParams: Record<string, unknown>;
|
|
60
|
-
paramsJson: string;
|
|
61
|
-
resultPreview: string | null;
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* The canonical tool-pain identity derivation, exposed for the governance
|
|
65
|
-
* admission path (Codex Governance Closure SPEC §10): the same normalized
|
|
66
|
-
* fields fed to the live production handler derive the same deterministic
|
|
67
|
-
* `pain_host_<sha256>` id, so live and observation-delivered admissions of one
|
|
68
|
-
* tool call converge on one canonical pain.
|
|
69
|
-
*
|
|
70
|
-
* I1 parity obligation: when the host supplies a call id, BOTH paths must pass
|
|
71
|
-
* the same `toolCallId` (Codex admission candidates carry it from the same
|
|
72
|
-
* `tool_use_id` the live decoder required) — otherwise one real call would
|
|
73
|
-
* derive two canonical pains.
|
|
74
|
-
*/
|
|
75
|
-
export declare function deriveProductionToolPainIdentity(fields: ProductionToolEventFields & {
|
|
76
|
-
canonicalEventId?: string;
|
|
77
|
-
}): DerivedToolPainIdentity;
|
|
78
12
|
/**
|
|
79
13
|
* The canonical correction-pain identity derivation (SPEC §10/§12): deterministic,
|
|
80
14
|
* content-derived, retry-safe — replacing the legacy random `correction_<traceId>`
|
|
@@ -137,6 +71,13 @@ export declare function recordVerifiedToolOutcomes(args: {
|
|
|
137
71
|
hostKind?: string;
|
|
138
72
|
}): VerifiedToolOutcomeStatus[];
|
|
139
73
|
/**
|
|
74
|
+
* Shared production tool-call evidence handler.
|
|
75
|
+
*
|
|
76
|
+
* Records the real host tool call in `trajectory.db` (tool_calls) and emits the
|
|
77
|
+
* receipt event. Phase A retired the legacy automatic Pain admission that used
|
|
78
|
+
* to ride on this path: a technical tool failure is trajectory + health
|
|
79
|
+
* evidence, never an Owner-pain by itself.
|
|
80
|
+
*
|
|
140
81
|
* PRI-640: host attribution is supplied by the host adapter that constructs
|
|
141
82
|
* this shared handler (OpenClaw / Codex adapters) — never guessed inside the
|
|
142
83
|
* writer. Omitted -> NULL (unknown).
|
|
@@ -148,6 +89,4 @@ export declare function createProductionPainEvidenceHandler(options?: {
|
|
|
148
89
|
projectDir?: string;
|
|
149
90
|
events?: HostEventEmitter;
|
|
150
91
|
}): (event: HostEvent) => Promise<HostEventResult>;
|
|
151
|
-
export declare function resetProductionPainCooldownForTest(): void;
|
|
152
|
-
export declare function productionPainCooldownEntryCountForTest(): number;
|
|
153
92
|
export { hasCanonicalSchema as hasProductionPainSchema };
|
|
@@ -2,13 +2,8 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
5
|
-
import { applyTrajectorySchemaBase,
|
|
6
|
-
const WRITE_TOOLS = new Set(['write', 'edit', 'apply_patch', 'write_file', 'edit_file', 'replace']);
|
|
7
|
-
/** Shared with the governance admission path so both gate tool failures identically. */
|
|
8
|
-
export const PRODUCTION_WRITE_TOOLS = WRITE_TOOLS;
|
|
5
|
+
import { applyTrajectorySchemaBase, sanitizeToolParams, sanitizeValue, } from '@principles/core/runtime-v2';
|
|
9
6
|
const MAX_PREVIEW = 500;
|
|
10
|
-
const PAIN_COOLDOWN_WINDOW_MS = 15 * 60 * 1000;
|
|
11
|
-
const cooldowns = new Map();
|
|
12
7
|
function isRecord(value) {
|
|
13
8
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
9
|
}
|
|
@@ -33,7 +28,7 @@ function field(value, key) {
|
|
|
33
28
|
* legitimate completion of the tool contract and stay success (SPEC §5.1).
|
|
34
29
|
*/
|
|
35
30
|
function normalizeOutcome(event) {
|
|
36
|
-
const
|
|
31
|
+
const { context } = event;
|
|
37
32
|
const envelope = context.toolOutput;
|
|
38
33
|
const result = field(envelope, 'result') ?? envelope;
|
|
39
34
|
const errorValue = field(envelope, 'error') ?? field(result, 'error');
|
|
@@ -79,46 +74,15 @@ function normalizeOutcome(event) {
|
|
|
79
74
|
result,
|
|
80
75
|
};
|
|
81
76
|
}
|
|
82
|
-
function isEvidence(value) {
|
|
83
|
-
return Array.isArray(value) && value.length <= 8 && value.every((entry) => isRecord(entry) && typeof field(entry, 'sourceRef') === 'string' && String(field(entry, 'sourceRef')).trim().length > 0
|
|
84
|
-
&& String(field(entry, 'sourceRef')).length <= 300 && typeof field(entry, 'note') === 'string' && String(field(entry, 'note')).length <= 200);
|
|
85
|
-
}
|
|
86
77
|
function parseEnrichment(value) {
|
|
87
78
|
if (value === undefined)
|
|
88
79
|
return {};
|
|
89
80
|
if (!isRecord(value))
|
|
90
81
|
return null;
|
|
91
|
-
const painScore = field(value, 'painScore');
|
|
92
|
-
const isRisky = field(value, 'isRisky');
|
|
93
|
-
const consecutiveErrors = field(value, 'consecutiveErrors');
|
|
94
|
-
const evidence = field(value, 'evidence');
|
|
95
82
|
const eventId = field(value, 'eventId');
|
|
96
|
-
|
|
97
|
-
const agentId = field(value, 'agentId');
|
|
98
|
-
const errorHash = field(value, 'errorHash');
|
|
99
|
-
if (painScore !== undefined && (typeof painScore !== 'number' || !Number.isFinite(painScore) || painScore < 0 || painScore > 100))
|
|
100
|
-
return null;
|
|
101
|
-
if (isRisky !== undefined && typeof isRisky !== 'boolean')
|
|
83
|
+
if (eventId !== undefined && (typeof eventId !== 'string' || eventId.trim().length === 0 || eventId.length > 500))
|
|
102
84
|
return null;
|
|
103
|
-
|
|
104
|
-
return null;
|
|
105
|
-
for (const key of ['eventId', 'relativePath', 'agentId', 'errorHash']) {
|
|
106
|
-
const candidate = field(value, key);
|
|
107
|
-
if (candidate !== undefined && (typeof candidate !== 'string' || candidate.trim().length === 0 || candidate.length > 500))
|
|
108
|
-
return null;
|
|
109
|
-
}
|
|
110
|
-
if (evidence !== undefined && !isEvidence(evidence))
|
|
111
|
-
return null;
|
|
112
|
-
return {
|
|
113
|
-
...(typeof eventId === 'string' ? { eventId } : {}),
|
|
114
|
-
...(typeof painScore === 'number' ? { painScore } : {}),
|
|
115
|
-
...(typeof isRisky === 'boolean' ? { isRisky } : {}),
|
|
116
|
-
...(typeof consecutiveErrors === 'number' ? { consecutiveErrors } : {}),
|
|
117
|
-
...(typeof relativePath === 'string' ? { relativePath } : {}),
|
|
118
|
-
...(typeof agentId === 'string' ? { agentId } : {}),
|
|
119
|
-
...(typeof errorHash === 'string' ? { errorHash } : {}),
|
|
120
|
-
...(isEvidence(evidence) ? { evidence } : {}),
|
|
121
|
-
};
|
|
85
|
+
return typeof eventId === 'string' ? { eventId } : {};
|
|
122
86
|
}
|
|
123
87
|
function stable(value, seen = new WeakSet()) {
|
|
124
88
|
if (value === null || typeof value !== 'object') {
|
|
@@ -165,42 +129,7 @@ function ids(input) {
|
|
|
165
129
|
failure: outcome.failure,
|
|
166
130
|
});
|
|
167
131
|
const digest = createHash('sha256').update(canonical).digest('hex');
|
|
168
|
-
return { eventId: `host_${digest}
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* The canonical tool-pain identity derivation, exposed for the governance
|
|
172
|
-
* admission path (Codex Governance Closure SPEC §10): the same normalized
|
|
173
|
-
* fields fed to the live production handler derive the same deterministic
|
|
174
|
-
* `pain_host_<sha256>` id, so live and observation-delivered admissions of one
|
|
175
|
-
* tool call converge on one canonical pain.
|
|
176
|
-
*
|
|
177
|
-
* I1 parity obligation: when the host supplies a call id, BOTH paths must pass
|
|
178
|
-
* the same `toolCallId` (Codex admission candidates carry it from the same
|
|
179
|
-
* `tool_use_id` the live decoder required) — otherwise one real call would
|
|
180
|
-
* derive two canonical pains.
|
|
181
|
-
*/
|
|
182
|
-
export function deriveProductionToolPainIdentity(fields) {
|
|
183
|
-
const outcome = normalizeOutcome(fields);
|
|
184
|
-
const sanitizedParams = sanitizeToolParams(outcome.params, fields.workspaceDir);
|
|
185
|
-
const { eventId, painId } = ids({
|
|
186
|
-
workspaceDir: fields.workspaceDir,
|
|
187
|
-
sessionId: fields.sessionId,
|
|
188
|
-
...(fields.turnId !== undefined ? { turnId: fields.turnId } : {}),
|
|
189
|
-
...(fields.toolName !== undefined ? { toolName: fields.toolName } : {}),
|
|
190
|
-
source: fields.source,
|
|
191
|
-
...(fields.canonicalEventId !== undefined ? { canonicalEventId: fields.canonicalEventId } : {}),
|
|
192
|
-
...(fields.toolCallId !== undefined ? { toolCallId: fields.toolCallId } : {}),
|
|
193
|
-
outcome,
|
|
194
|
-
sanitizedParams,
|
|
195
|
-
});
|
|
196
|
-
return {
|
|
197
|
-
eventId,
|
|
198
|
-
painId,
|
|
199
|
-
outcome,
|
|
200
|
-
sanitizedParams,
|
|
201
|
-
paramsJson: stable(sanitizedParams),
|
|
202
|
-
resultPreview: preview({ eventId, result: sanitizeValue(outcome.result, 0, fields.workspaceDir) }),
|
|
203
|
-
};
|
|
132
|
+
return { eventId: `host_${digest}` };
|
|
204
133
|
}
|
|
205
134
|
/**
|
|
206
135
|
* The canonical correction-pain identity derivation (SPEC §10/§12): deterministic,
|
|
@@ -415,6 +344,13 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
415
344
|
return results;
|
|
416
345
|
}
|
|
417
346
|
/**
|
|
347
|
+
* Shared production tool-call evidence handler.
|
|
348
|
+
*
|
|
349
|
+
* Records the real host tool call in `trajectory.db` (tool_calls) and emits the
|
|
350
|
+
* receipt event. Phase A retired the legacy automatic Pain admission that used
|
|
351
|
+
* to ride on this path: a technical tool failure is trajectory + health
|
|
352
|
+
* evidence, never an Owner-pain by itself.
|
|
353
|
+
*
|
|
418
354
|
* PRI-640: host attribution is supplied by the host adapter that constructs
|
|
419
355
|
* this shared handler (OpenClaw / Codex adapters) — never guessed inside the
|
|
420
356
|
* writer. Omitted -> NULL (unknown).
|
|
@@ -445,7 +381,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
445
381
|
}
|
|
446
382
|
const dbPath = path.join(event.context.workspaceDir, '.state', 'trajectory.db');
|
|
447
383
|
if (!fs.existsSync(dbPath)) {
|
|
448
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_db_not_found'], metadata: { outcome: 'unavailable',
|
|
384
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_db_not_found'], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'initialize the selected PD workspace before retrying the hook' } };
|
|
449
385
|
}
|
|
450
386
|
let db;
|
|
451
387
|
try {
|
|
@@ -457,7 +393,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
457
393
|
if (!hasCanonicalSchema(db)) {
|
|
458
394
|
db.close();
|
|
459
395
|
db = undefined;
|
|
460
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_schema_invalid'], metadata: { outcome: 'unavailable',
|
|
396
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_schema_invalid'], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'run the supported PD workspace migration' } };
|
|
461
397
|
}
|
|
462
398
|
}
|
|
463
399
|
catch (error) {
|
|
@@ -465,7 +401,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
465
401
|
db?.close();
|
|
466
402
|
}
|
|
467
403
|
catch { /* best-effort cleanup of an unusable handle */ }
|
|
468
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_database_unavailable:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: 'unavailable',
|
|
404
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_database_unavailable:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'inspect or repair the selected PD trajectory database' } };
|
|
469
405
|
}
|
|
470
406
|
const warnings = [];
|
|
471
407
|
let enrichment;
|
|
@@ -481,49 +417,12 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
481
417
|
db.close();
|
|
482
418
|
}
|
|
483
419
|
catch { /* no business write occurred */ }
|
|
484
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), ...(warnings.length > 0 ? warnings : ['pain_enrichment_invalid'])], metadata: { outcome: 'unavailable',
|
|
420
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), ...(warnings.length > 0 ? warnings : ['pain_enrichment_invalid'])], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'inspect host tool-call enrichment input' } };
|
|
485
421
|
}
|
|
486
422
|
const outcome = normalizeOutcome(event);
|
|
487
423
|
const sanitizedParams = sanitizeToolParams(outcome.params, event.context.workspaceDir);
|
|
488
424
|
const toolName = event.context.toolName ?? '';
|
|
489
|
-
const
|
|
490
|
-
const nonZeroExit = outcome.exitCode !== null && outcome.exitCode !== 0;
|
|
491
|
-
const sourceKind = resolveSourceKind({
|
|
492
|
-
observedAt: new Date().toISOString(), workspaceId: event.context.workspaceDir,
|
|
493
|
-
sessionId: event.context.sessionId, toolName, failureSource: sourceObservation.failureSource,
|
|
494
|
-
toolNotFound: sourceObservation.toolNotFound, nonZeroExit,
|
|
495
|
-
});
|
|
496
|
-
const relativePath = enrichment.relativePath ?? String(field(outcome.params, 'file_path') ?? field(outcome.params, 'path') ?? 'unknown').slice(0, 500);
|
|
497
|
-
const isRisky = enrichment.isRisky ?? (path.isAbsolute(relativePath) && !path.resolve(relativePath).startsWith(`${path.resolve(event.context.workspaceDir)}${path.sep}`));
|
|
498
|
-
// Merged scoring semantics (WorkBuddy admission floor × CR-01): the 70
|
|
499
|
-
// failure base requires a VERIFIED non-zero exit code (branch review
|
|
500
|
-
// round: a thrown error with no exit evidence stays at the risky-path
|
|
501
|
-
// bonus only, honestly below the GOVERNANCE_STRONG_PAIN_SCORE floor, so
|
|
502
|
-
// unverified error shapes never spawn diagnostician work on their own).
|
|
503
|
-
// Classification and RECORDING remain main's three-way contract — the
|
|
504
|
-
// row still records outcome='failure' with exit_code NULL (never a
|
|
505
|
-
// fabricated 0).
|
|
506
|
-
const verifiedNonZeroExit = outcome.exitCode !== null && outcome.exitCode !== 0;
|
|
507
|
-
const painScore = enrichment.painScore ?? Math.min(100, (verifiedNonZeroExit ? 70 : 0) + (isRisky ? 20 : 0));
|
|
508
|
-
const errorHash = enrichment.errorHash ?? createHash('sha256').update(outcome.error ?? String(outcome.exitCode)).digest('hex');
|
|
509
|
-
// Cooldown is DEBOUNCE, not event identity (I1): the key deliberately has
|
|
510
|
-
// NO toolCallId. Repeated failures of the same failureSource+error within
|
|
511
|
-
// the window suppress the diagnostic trigger storm, while each real call
|
|
512
|
-
// still earns its own tool_calls evidence row through call-id-sensitive
|
|
513
|
-
// identity below.
|
|
514
|
-
const cooldownKey = `${path.resolve(event.context.workspaceDir)}:${event.context.sessionId}:${sourceObservation.failureSource}:${errorHash}`;
|
|
515
|
-
const last = cooldowns.get(cooldownKey);
|
|
516
|
-
const cooldownActive = last !== undefined && Date.now() - last < PAIN_COOLDOWN_WINDOW_MS;
|
|
517
|
-
const triage = evaluateTriage({ sourceKind, score: painScore, consecutiveErrors: enrichment.consecutiveErrors, isRisky });
|
|
518
|
-
const trigger = evaluateTriggerController({ triageResult: triage, isOwnerManual: false, isCooldownActive: cooldownActive, isValid: true, score: painScore, sessionId: event.context.sessionId });
|
|
519
|
-
// Merged semantics (WorkBuddy × CR-01): the three-way classification from
|
|
520
|
-
// SPEC-CODEX-PAIN-CLOSURE-001 gates admission ('unknown' results are never
|
|
521
|
-
// pain), and WorkBuddy tool names are capitalized (Write/Edit — probe P03)
|
|
522
|
-
// while OpenClaw/Codex are lowercase; admission is about the tool FAMILY,
|
|
523
|
-
// so compare case-insensitively at this one boundary. tool_calls evidence
|
|
524
|
-
// above keeps the raw host name.
|
|
525
|
-
const admitted = outcome.outcome === 'failure' && WRITE_TOOLS.has(toolName.toLowerCase()) && trigger.shouldCreateDiagnosticTask;
|
|
526
|
-
const { eventId, painId } = ids({
|
|
425
|
+
const { eventId } = ids({
|
|
527
426
|
workspaceDir: event.context.workspaceDir,
|
|
528
427
|
sessionId: event.context.sessionId,
|
|
529
428
|
...(event.context.turnId !== undefined ? { turnId: event.context.turnId } : {}),
|
|
@@ -542,7 +441,6 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
542
441
|
const paramsJson = stable(sanitizedParams);
|
|
543
442
|
const resultPreview = preview({ eventId, result: sanitizeValue(outcome.result, 0, event.context.workspaceDir) });
|
|
544
443
|
let duplicate = false;
|
|
545
|
-
let duplicateAdmitted = false;
|
|
546
444
|
try {
|
|
547
445
|
db.transaction(() => {
|
|
548
446
|
// CR-01: the host tool-call id is the stable join key for the
|
|
@@ -557,7 +455,6 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
557
455
|
? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(event.context.sessionId, event.context.toolCallId, options.hostKind)
|
|
558
456
|
: db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId)) !== undefined) {
|
|
559
457
|
duplicate = true;
|
|
560
|
-
duplicateAdmitted = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) !== undefined;
|
|
561
458
|
return;
|
|
562
459
|
}
|
|
563
460
|
// Review R3/P2: the content-shape fallback dedup is host-scoped the
|
|
@@ -566,40 +463,15 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
566
463
|
? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, options.hostKind)
|
|
567
464
|
: db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
|
|
568
465
|
duplicate = true;
|
|
569
|
-
duplicateAdmitted = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) !== undefined;
|
|
570
466
|
return;
|
|
571
467
|
}
|
|
572
468
|
db.prepare(`INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at`).run(event.context.sessionId, createdAt, createdAt);
|
|
573
469
|
db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
574
470
|
.run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, null, null, paramsJson, resultPreview, createdAt, event.context.toolCallId ?? null, path.resolve(options.projectDir ?? event.context.workspaceDir), options.hostKind ?? null);
|
|
575
|
-
if (admitted) {
|
|
576
|
-
// Raw observation only (Pain Diagnosis Persistence SPEC §8): the
|
|
577
|
-
// pain row must record WHAT happened, not WHY. Attribution
|
|
578
|
-
// (People/Design/Assumption/Tooling) belongs to the Diagnostician.
|
|
579
|
-
// confidence stays null — no attribution confidence exists at
|
|
580
|
-
// detection time. origin remains 'system_infer' because origin is a
|
|
581
|
-
// declared enum (event-types.ts: who reported the pain), not an
|
|
582
|
-
// attribution claim.
|
|
583
|
-
const reason = `tool=${toolName}; error=${outcome.error ?? `exit=${outcome.exitCode}`}; path=${relativePath}`;
|
|
584
|
-
db.prepare(`INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, host_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
585
|
-
.run(event.context.sessionId, sourceObservation.failureSource ?? 'tool_failure', painScore, reason, painScore >= 70 ? 'severe' : painScore >= 40 ? 'moderate' : 'mild', 'system_infer', null, enrichment.evidence?.map((entry) => `${entry.sourceRef}: ${entry.note}`).join('\n') ?? null, painId, null, options.hostKind ?? null, createdAt);
|
|
586
|
-
}
|
|
587
471
|
})();
|
|
588
|
-
if (admitted && !duplicate) {
|
|
589
|
-
const admittedAt = Date.now();
|
|
590
|
-
// Bound the module-level cooldown map in long-lived host processes
|
|
591
|
-
// (OpenClaw): keys carry sessionId + errorHash, so unbounded retention
|
|
592
|
-
// grows monotonically. Evict entries outside the cooldown window —
|
|
593
|
-
// they can never be consulted again.
|
|
594
|
-
for (const [staleKey, staleAt] of cooldowns) {
|
|
595
|
-
if (admittedAt - staleAt >= PAIN_COOLDOWN_WINDOW_MS)
|
|
596
|
-
cooldowns.delete(staleKey);
|
|
597
|
-
}
|
|
598
|
-
cooldowns.set(cooldownKey, admittedAt);
|
|
599
|
-
}
|
|
600
472
|
}
|
|
601
473
|
catch (error) {
|
|
602
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_write_failed:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: outcome.outcome,
|
|
474
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_write_failed:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: outcome.outcome, duplicate: false, nextAction: 'inspect the workspace trajectory database and retry' } };
|
|
603
475
|
}
|
|
604
476
|
finally {
|
|
605
477
|
try {
|
|
@@ -607,24 +479,14 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
607
479
|
}
|
|
608
480
|
catch { /* write result already determined; cleanup is best-effort */ }
|
|
609
481
|
}
|
|
610
|
-
const effectiveAdmitted = admitted || duplicateAdmitted;
|
|
611
482
|
return {
|
|
612
483
|
decision: 'observe',
|
|
613
484
|
source: event.source,
|
|
614
485
|
...(emissionWarning ? { warnings: [emissionWarning] } : {}),
|
|
615
486
|
metadata: {
|
|
616
|
-
eventId,
|
|
617
|
-
sourceKind, failureSource: sourceObservation.failureSource ?? null, triggerOutcome: trigger.outcome,
|
|
618
|
-
triggerReason: trigger.reason, painScore, isRisky, relativePath, agentId: enrichment.agentId ?? null,
|
|
619
|
-
evidence: enrichment.evidence ?? [],
|
|
487
|
+
eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate,
|
|
620
488
|
}
|
|
621
489
|
};
|
|
622
490
|
};
|
|
623
491
|
}
|
|
624
|
-
export function resetProductionPainCooldownForTest() {
|
|
625
|
-
cooldowns.clear();
|
|
626
|
-
}
|
|
627
|
-
export function productionPainCooldownEntryCountForTest() {
|
|
628
|
-
return cooldowns.size;
|
|
629
|
-
}
|
|
630
492
|
export { hasCanonicalSchema as hasProductionPainSchema };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.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",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"lint": "eslint \"src/**/*.ts\""
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@principles/core": "^
|
|
34
|
+
"@principles/core": "^3.0.0",
|
|
35
35
|
"@principles/install-layout": "^0.4.0",
|
|
36
36
|
"better-sqlite3": "^13.0.3",
|
|
37
37
|
"js-yaml": "^5.4.3"
|
|
@@ -49,5 +49,5 @@
|
|
|
49
49
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
50
50
|
},
|
|
51
51
|
"license": "Apache-2.0",
|
|
52
|
-
"gitHead": "
|
|
52
|
+
"gitHead": "94d353a428b6fc27dd41ff63b767bf915b9ed147"
|
|
53
53
|
}
|