@principles/host-runtime 0.15.1 → 2.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.
- package/dist/governance-signal-admission.d.ts +1 -79
- package/dist/governance-signal-admission.js +47 -308
- package/dist/production-pain-evidence.d.ts +9 -70
- package/dist/production-pain-evidence.js +60 -163
- package/dist/production-rulehost-gate.d.ts +0 -1
- package/dist/production-rulehost-gate.js +3 -4
- package/dist/signal-classifier.d.ts +8 -0
- package/dist/signal-classifier.js +10 -2
- package/package.json +3 -3
|
@@ -17,8 +17,6 @@ export declare const HIGH_PRECISION_CORRECTION_OVERLAY: readonly (readonly [stri
|
|
|
17
17
|
* 它们仍是候选(进入 Stage 2),但永不直达 STRONG。
|
|
18
18
|
*/
|
|
19
19
|
export declare const AMBIGUOUS_CORRECTION_OVERLAY: readonly (readonly [string, number])[];
|
|
20
|
-
/** empathy seed overlay(检测行为不变) */
|
|
21
|
-
export declare const EMPATHY_SEED_OVERLAY: readonly (readonly [string, number])[];
|
|
22
20
|
export declare function buildSharedSeedKeywordStore(): UnifiedKeywordStore;
|
|
23
21
|
export interface SharedCorrectionKeywordStore {
|
|
24
22
|
resolve(): UnifiedKeywordStore;
|
|
@@ -90,32 +88,7 @@ export interface GovernanceCorrectionCandidate {
|
|
|
90
88
|
*/
|
|
91
89
|
readonly explicitChannel?: 'codex_explicit_prefix' | 'codex_explicit_agent' | 'workbuddy_explicit_prefix';
|
|
92
90
|
}
|
|
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;
|
|
91
|
+
export type GovernanceSignalCandidate = GovernanceCorrectionCandidate;
|
|
119
92
|
export type GovernanceAdmissionOutcome = {
|
|
120
93
|
disposition: 'admitted';
|
|
121
94
|
kind: GovernanceSignalKind;
|
|
@@ -133,11 +106,6 @@ export type GovernanceAdmissionOutcome = {
|
|
|
133
106
|
disposition: 'not_a_signal';
|
|
134
107
|
kind: 'user_correction';
|
|
135
108
|
logicalObservationKey: string;
|
|
136
|
-
} | {
|
|
137
|
-
disposition: 'not_admitted';
|
|
138
|
-
kind: 'tool_failure';
|
|
139
|
-
logicalObservationKey: string;
|
|
140
|
-
reason: string;
|
|
141
109
|
} | {
|
|
142
110
|
disposition: 'rate_limited';
|
|
143
111
|
kind: 'user_correction';
|
|
@@ -399,52 +367,6 @@ export type EnsureGovernanceContinuationResult = {
|
|
|
399
367
|
* provide the current conversation-ingestion consent.
|
|
400
368
|
*/
|
|
401
369
|
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
370
|
export interface ReconcileGovernanceContinuationInput {
|
|
449
371
|
readonly workspaceDir: string;
|
|
450
372
|
/** 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, migrateLegacyGfiSchema, 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) ───────────────────
|
|
@@ -86,10 +86,6 @@ export const AMBIGUOUS_CORRECTION_OVERLAY = [
|
|
|
86
86
|
['我说的是', 0.9],
|
|
87
87
|
['都说了', 0.8],
|
|
88
88
|
];
|
|
89
|
-
/** empathy seed overlay(检测行为不变) */
|
|
90
|
-
export const EMPATHY_SEED_OVERLAY = [
|
|
91
|
-
['搞什么', 0.5],
|
|
92
|
-
];
|
|
93
89
|
function isValidLearnedKeyword(v) {
|
|
94
90
|
if (typeof v !== 'object' || v === null)
|
|
95
91
|
return false;
|
|
@@ -147,7 +143,6 @@ function projectLearnedStore(raw) {
|
|
|
147
143
|
const weight = Math.max(0, Math.min(1, kw.weight));
|
|
148
144
|
terms[term] = {
|
|
149
145
|
term,
|
|
150
|
-
category: 'correction',
|
|
151
146
|
weight,
|
|
152
147
|
precision: precisionFor(kw.source, term, weight),
|
|
153
148
|
source: mapLearnedSource(kw.source),
|
|
@@ -160,22 +155,18 @@ function projectLearnedStore(raw) {
|
|
|
160
155
|
export function buildSharedSeedKeywordStore() {
|
|
161
156
|
const terms = {};
|
|
162
157
|
for (const [term, weight] of HIGH_PRECISION_CORRECTION_OVERLAY) {
|
|
163
|
-
terms[term] = { term,
|
|
164
|
-
}
|
|
165
|
-
for (const [term, weight] of EMPATHY_SEED_OVERLAY) {
|
|
166
|
-
terms[term] = { term, category: 'empathy', weight, precision: 'ambiguous', source: 'seed' };
|
|
158
|
+
terms[term] = { term, weight, precision: 'high', source: 'seed' };
|
|
167
159
|
}
|
|
168
160
|
for (const [term, weight] of AMBIGUOUS_CORRECTION_OVERLAY) {
|
|
169
161
|
if (Object.hasOwn(terms, term))
|
|
170
162
|
continue;
|
|
171
|
-
terms[term] = { term,
|
|
163
|
+
terms[term] = { term, weight, precision: 'ambiguous', source: 'seed' };
|
|
172
164
|
}
|
|
173
165
|
for (const kw of CORRECTION_SEED_KEYWORDS) {
|
|
174
166
|
if (Object.hasOwn(terms, kw.term))
|
|
175
167
|
continue;
|
|
176
168
|
terms[kw.term] = {
|
|
177
169
|
term: kw.term,
|
|
178
|
-
category: 'correction',
|
|
179
170
|
weight: kw.weight,
|
|
180
171
|
precision: kw.weight >= HIGH_PRECISION_LEARNED_WEIGHT ? 'high' : 'ambiguous',
|
|
181
172
|
source: 'seed',
|
|
@@ -305,8 +296,8 @@ function ensureGovernanceAdmissionSchema(db) {
|
|
|
305
296
|
db.transaction(() => {
|
|
306
297
|
for (const statement of ADMISSION_CREATE_STATEMENTS)
|
|
307
298
|
db.exec(statement);
|
|
308
|
-
// SPEC-CODEX-PAIN-CLOSURE-001 CR-01:
|
|
309
|
-
//
|
|
299
|
+
// SPEC-CODEX-PAIN-CLOSURE-001 CR-01: trajectory evidence writers persist
|
|
300
|
+
// tool_calls; make sure the host tool-use-id join column exists on
|
|
310
301
|
// workspaces whose base schema predates it (idempotent additive ALTER —
|
|
311
302
|
// only when the table itself exists: governance-only databases without a
|
|
312
303
|
// tool_calls table are a valid pre-existing state, not an error).
|
|
@@ -355,6 +346,11 @@ function openAdmissionStore(workspaceDir, factory) {
|
|
|
355
346
|
db.pragma('busy_timeout = 5000');
|
|
356
347
|
db.pragma('journal_mode = WAL');
|
|
357
348
|
ensureGovernanceAdmissionSchema(db);
|
|
349
|
+
// GFI-COMPLETE-REMOVAL-001: the additive governance open does not retire
|
|
350
|
+
// the GFI columns, so a v1 workspace would be judged non-canonical by
|
|
351
|
+
// hasProductionPainSchema and refused. Converge it here with the SAME
|
|
352
|
+
// migration the other raw open paths use (idempotent, no-op on v2).
|
|
353
|
+
migrateLegacyGfiSchema(db);
|
|
358
354
|
// The reconciliation pass reads observation-owned tables (promotion
|
|
359
355
|
// tails): one open makes the whole governance schema ready.
|
|
360
356
|
ensureGovernanceSchema(db);
|
|
@@ -439,29 +435,6 @@ function insertCorrectionPain({ db, candidate, workspaceDir, painId, reason, now
|
|
|
439
435
|
.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
436
|
return reason;
|
|
441
437
|
}
|
|
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
438
|
/**
|
|
466
439
|
* P1 (review round 3): a `behavior_trace` may only name a row that EXISTS in
|
|
467
440
|
* trajectory.db with the SAME lineage tuple. WorkBuddy currently has no
|
|
@@ -486,47 +459,36 @@ function persistedBehaviorTraceEvidence(args) {
|
|
|
486
459
|
}
|
|
487
460
|
function buildTaskSubmissionPayload(candidate, workspaceDir, details) {
|
|
488
461
|
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,
|
|
462
|
+
// P1-1 privacy (review round 2): sanitize the FULL text before any
|
|
463
|
+
// truncation — a token crossing the 200-char boundary must be redacted, not
|
|
464
|
+
// split into a fragment that survives verbatim. sanitizeString bounds itself.
|
|
465
|
+
const payload = {
|
|
466
|
+
painType: 'user_frustration',
|
|
467
|
+
source: 'user_correction',
|
|
468
|
+
reason: reason || 'User correction detected',
|
|
469
|
+
score: GOVERNANCE_STRONG_PAIN_SCORE,
|
|
524
470
|
sessionId: candidate.rootSessionId,
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
471
|
+
hostKind: candidate.hostKind,
|
|
472
|
+
evidence: persistedBehaviorTraceEvidence({
|
|
473
|
+
db,
|
|
474
|
+
hostKind: candidate.hostKind,
|
|
475
|
+
logicalObservationKey: candidate.logicalObservationKey,
|
|
476
|
+
rolloutIdentity: candidate.rolloutIdentity,
|
|
477
|
+
rootSessionId: candidate.rootSessionId,
|
|
478
|
+
hostTurnId: candidate.hostTurnId,
|
|
479
|
+
text: candidate.text,
|
|
480
|
+
workspaceDir,
|
|
481
|
+
}),
|
|
482
|
+
// SPEC-CODEX-PAIN-CLOSURE-001 CR-02 (merged from main): an explicit
|
|
483
|
+
// Owner statement rides as classified correction evidence — never
|
|
484
|
+
// summarized by an AI, never inside evidence[] pseudo-trace entries.
|
|
485
|
+
...(candidate.explicitOwnerStatement === true
|
|
486
|
+
? { correctionEvidence: candidate.hostKind === 'workbuddy'
|
|
487
|
+
? { text: boundCorrectionEvidenceText({ text: candidate.text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }, workspaceDir).text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }
|
|
488
|
+
: { text: sanitizeString(candidate.text, workspaceDir), classification: 'owner_statement', channel: candidate.explicitChannel === 'codex_explicit_agent' ? 'codex_explicit_agent' : 'codex_explicit_prefix' } }
|
|
489
|
+
: {}),
|
|
490
|
+
};
|
|
491
|
+
return payload;
|
|
530
492
|
}
|
|
531
493
|
function taskSubmissionPayload(candidate, workspaceDir, details) {
|
|
532
494
|
return JSON.stringify(buildTaskSubmissionPayload(candidate, workspaceDir, details));
|
|
@@ -582,7 +544,7 @@ function parsePendingReviewMeta(value) {
|
|
|
582
544
|
if (!isRecord(reviewRaw))
|
|
583
545
|
return null;
|
|
584
546
|
const verdict = own(reviewRaw, 'verdict');
|
|
585
|
-
if (verdict !== 'correction' && verdict !== 'none'
|
|
547
|
+
if (verdict !== 'correction' && verdict !== 'none'
|
|
586
548
|
&& verdict !== 'pending_low_confidence' && verdict !== 'pending_llm_error')
|
|
587
549
|
return null;
|
|
588
550
|
const confidence = own(reviewRaw, 'confidence');
|
|
@@ -1040,106 +1002,6 @@ function admitCorrection({ db, candidate, workspaceDir, now, nowIso, keywordStor
|
|
|
1040
1002
|
}
|
|
1041
1003
|
return { disposition: 'admitted', kind: 'user_correction', logicalObservationKey: candidate.logicalObservationKey, canonicalPainId: painId, duplicate, ruleVersion: detection?.ruleVersion ?? null };
|
|
1042
1004
|
}
|
|
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
1005
|
function admitOne({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDegradation, trustedWorkbuddyLive }) {
|
|
1144
1006
|
if (candidate.hostKind !== 'codex' && !(candidate.hostKind === 'workbuddy' && candidate.kind === 'user_correction' && (candidate.explicitOwnerStatement === true || trustedWorkbuddyLive === true))) {
|
|
1145
1007
|
return { ok: false, reason: 'unsupported_host_kind', nextAction: 'governance signal admission accepts Codex observations or explicit WorkBuddy Owner statements' };
|
|
@@ -1171,10 +1033,7 @@ function admitOne({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDe
|
|
|
1171
1033
|
};
|
|
1172
1034
|
}
|
|
1173
1035
|
try {
|
|
1174
|
-
|
|
1175
|
-
return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
|
|
1176
|
-
}
|
|
1177
|
-
return admitToolFailure({ db, candidate, workspaceDir, nowIso });
|
|
1036
|
+
return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
|
|
1178
1037
|
}
|
|
1179
1038
|
catch (error) {
|
|
1180
1039
|
// RateLimitedSignal never reaches here — admitCorrection converts it to a
|
|
@@ -1661,14 +1520,17 @@ export async function settlePendingCorrection(input) {
|
|
|
1661
1520
|
close();
|
|
1662
1521
|
}
|
|
1663
1522
|
}
|
|
1664
|
-
/** P0: a four-term projection of existing canonical high-precision seeds. */
|
|
1523
|
+
/** P0: a four-term projection of existing canonical high-precision correction seeds. */
|
|
1665
1524
|
const WORKBUDDY_AUTO_TERMS = new Set(['这是错的', '不要自作主张', '不应该这么做', '又搞错']);
|
|
1666
1525
|
const WORKBUDDY_MAX_PROMPT_BYTES = 16 * 1024;
|
|
1667
1526
|
function workbuddyP0KeywordStore() {
|
|
1668
1527
|
const seed = buildSharedSeedKeywordStore();
|
|
1669
1528
|
const terms = {};
|
|
1670
1529
|
for (const [term, def] of Object.entries(seed.terms)) {
|
|
1671
|
-
|
|
1530
|
+
// The shared seed store only contains correction phrases (the empathy
|
|
1531
|
+
// keyword store was retired with GFI-COMPLETE-REMOVAL-001), so the term
|
|
1532
|
+
// membership + high precision is the whole filter.
|
|
1533
|
+
if (WORKBUDDY_AUTO_TERMS.has(term) && def.precision === 'high') {
|
|
1672
1534
|
terms[term] = def;
|
|
1673
1535
|
}
|
|
1674
1536
|
}
|
|
@@ -2117,129 +1979,6 @@ export async function ensureGovernanceContinuation(input) {
|
|
|
2117
1979
|
close();
|
|
2118
1980
|
}
|
|
2119
1981
|
}
|
|
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
1982
|
/**
|
|
2244
1983
|
* Narrow idempotent reconciliation between the trajectory admission markers
|
|
2245
1984
|
* 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>`
|
|
@@ -118,7 +52,7 @@ export type VerifiedToolOutcomeStatus = {
|
|
|
118
52
|
reason: 'outcome_already_final';
|
|
119
53
|
} | {
|
|
120
54
|
status: 'unavailable';
|
|
121
|
-
reason: 'trajectory_db_not_found' | 'trajectory_write_failed' | `trajectory_write_failed:${string}`;
|
|
55
|
+
reason: 'trajectory_db_not_found' | 'trajectory_write_failed' | `trajectory_write_failed:${string}` | `trajectory_migration_failed:${string}`;
|
|
122
56
|
};
|
|
123
57
|
/**
|
|
124
58
|
* SPEC-CODEX-PAIN-CLOSURE-001 CR-01: upgrade the live-hook observation of a
|
|
@@ -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, migrateLegacyGfiSchema, 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')
|
|
102
|
-
return null;
|
|
103
|
-
if (consecutiveErrors !== undefined && (typeof consecutiveErrors !== 'number' || !Number.isInteger(consecutiveErrors) || consecutiveErrors < 0))
|
|
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))
|
|
83
|
+
if (eventId !== undefined && (typeof eventId !== 'string' || eventId.trim().length === 0 || eventId.length > 500))
|
|
111
84
|
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,
|
|
@@ -225,7 +154,7 @@ export function deriveProductionCorrectionPainIdentity(fields) {
|
|
|
225
154
|
}
|
|
226
155
|
const REQUIRED_COLUMNS = {
|
|
227
156
|
sessions: { session_id: 'TEXT', started_at: 'TEXT', updated_at: 'TEXT' },
|
|
228
|
-
tool_calls: { session_id: 'TEXT', tool_name: 'TEXT', outcome: 'TEXT', duration_ms: 'INTEGER', exit_code: 'INTEGER', error_type: 'TEXT', error_message: 'TEXT',
|
|
157
|
+
tool_calls: { session_id: 'TEXT', tool_name: 'TEXT', outcome: 'TEXT', duration_ms: 'INTEGER', exit_code: 'INTEGER', error_type: 'TEXT', error_message: 'TEXT', params_json: 'TEXT', result_preview: 'TEXT', created_at: 'TEXT', project_dir: 'TEXT' },
|
|
229
158
|
pain_events: { session_id: 'TEXT', source: 'TEXT', score: 'REAL', reason: 'TEXT', severity: 'TEXT', origin: 'TEXT', confidence: 'REAL', text: 'TEXT', canonical_pain_id: 'TEXT', runtime_task_id: 'TEXT', host_kind: 'TEXT', created_at: 'TEXT' },
|
|
230
159
|
};
|
|
231
160
|
function pragmaField(row, key) {
|
|
@@ -261,6 +190,12 @@ function hasCanonicalSchema(db) {
|
|
|
261
190
|
if (actual.get(name) !== type)
|
|
262
191
|
return false;
|
|
263
192
|
}
|
|
193
|
+
// GFI-COMPLETE-REMOVAL-001: a v1 database still carrying the retired GFI
|
|
194
|
+
// columns is NOT canonical, even though every required column is present.
|
|
195
|
+
// Without this check the raw open path judged v1 as canonical and the
|
|
196
|
+
// physical schema stayed at v1 forever.
|
|
197
|
+
if (table === 'tool_calls' && (actual.has('gfi_before') || actual.has('gfi_after')))
|
|
198
|
+
return false;
|
|
264
199
|
}
|
|
265
200
|
const indexes = db.prepare('PRAGMA index_list(pain_events)').all();
|
|
266
201
|
const canonical = indexes.find((row) => pragmaField(row, 'name') === 'idx_pain_events_canonical_pain_id');
|
|
@@ -277,7 +212,7 @@ function hasCanonicalSchema(db) {
|
|
|
277
212
|
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 ?');
|
|
278
213
|
db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?');
|
|
279
214
|
db.prepare('INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at');
|
|
280
|
-
db.prepare('INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
|
|
215
|
+
db.prepare('INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, project_dir) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
281
216
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
282
217
|
return true;
|
|
283
218
|
}
|
|
@@ -357,6 +292,18 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
357
292
|
const hasToolCalls = (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tool_calls'").get() !== undefined);
|
|
358
293
|
if (!hasToolCalls)
|
|
359
294
|
applyTrajectorySchemaBase(db);
|
|
295
|
+
// GFI-COMPLETE-REMOVAL-001: the raw open path never applied the canonical
|
|
296
|
+
// migration for a pre-existing (v1) tool_calls table. Fail LOUDLY here:
|
|
297
|
+
// returning statuses that look successful while the legacy GFI columns
|
|
298
|
+
// survive would hide the bug (rc-9).
|
|
299
|
+
try {
|
|
300
|
+
migrateLegacyGfiSchema(db);
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
304
|
+
const reason = `trajectory_migration_failed:${detail}`;
|
|
305
|
+
return args.outcomes.map(() => ({ status: 'unavailable', reason }));
|
|
306
|
+
}
|
|
360
307
|
ensureToolCallsToolUseIdColumn(db);
|
|
361
308
|
ensureToolCallsHostKindColumn(db);
|
|
362
309
|
// Review R3/P2: a KNOWN host's call identity includes its attribution.
|
|
@@ -369,7 +316,7 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
369
316
|
? db.prepare('SELECT id, outcome FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ? ORDER BY id LIMIT 1')
|
|
370
317
|
: db.prepare('SELECT id, outcome FROM tool_calls WHERE session_id = ? AND tool_use_id = ? ORDER BY id LIMIT 1');
|
|
371
318
|
const upgradeUnknown = db.prepare("UPDATE tool_calls SET outcome = ?, exit_code = ?, result_preview = COALESCE(?, result_preview) WHERE id = ? AND outcome = 'unknown'");
|
|
372
|
-
const insertVerified = db.prepare('INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
|
|
319
|
+
const insertVerified = db.prepare('INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, host_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
373
320
|
const upsertSession = db.prepare('INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at');
|
|
374
321
|
const createdAt = new Date().toISOString();
|
|
375
322
|
db.transaction(() => {
|
|
@@ -395,7 +342,12 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
395
342
|
}
|
|
396
343
|
upsertSession.run(args.sessionId, createdAt, createdAt);
|
|
397
344
|
const sanitizedParams = sanitizeToolParams(input.params ?? {}, args.workspaceDir);
|
|
398
|
-
|
|
345
|
+
// GFI-COMPLETE-REMOVAL-001 follow-up: commit 62e2cab15 dropped the two
|
|
346
|
+
// retired GFI columns from this INSERT but left their placeholder
|
|
347
|
+
// arguments behind, so every verified-outcome write threw
|
|
348
|
+
// "Too many parameter values were provided". Keep the values aligned
|
|
349
|
+
// with the 12 remaining columns.
|
|
350
|
+
const info = insertVerified.run(args.sessionId, input.toolName, finalOutcome, null, input.exitCode, null, null, stable(sanitizedParams), boundedPreview, createdAt, input.toolUseId, args.hostKind ?? null);
|
|
399
351
|
results.push({ status: 'inserted', id: Number(info.lastInsertRowid) });
|
|
400
352
|
}
|
|
401
353
|
})();
|
|
@@ -415,6 +367,13 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
415
367
|
return results;
|
|
416
368
|
}
|
|
417
369
|
/**
|
|
370
|
+
* Shared production tool-call evidence handler.
|
|
371
|
+
*
|
|
372
|
+
* Records the real host tool call in `trajectory.db` (tool_calls) and emits the
|
|
373
|
+
* receipt event. Phase A retired the legacy automatic Pain admission that used
|
|
374
|
+
* to ride on this path: a technical tool failure is trajectory + health
|
|
375
|
+
* evidence, never an Owner-pain by itself.
|
|
376
|
+
*
|
|
418
377
|
* PRI-640: host attribution is supplied by the host adapter that constructs
|
|
419
378
|
* this shared handler (OpenClaw / Codex adapters) — never guessed inside the
|
|
420
379
|
* writer. Omitted -> NULL (unknown).
|
|
@@ -445,7 +404,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
445
404
|
}
|
|
446
405
|
const dbPath = path.join(event.context.workspaceDir, '.state', 'trajectory.db');
|
|
447
406
|
if (!fs.existsSync(dbPath)) {
|
|
448
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_db_not_found'], metadata: { outcome: 'unavailable',
|
|
407
|
+
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
408
|
}
|
|
450
409
|
let db;
|
|
451
410
|
try {
|
|
@@ -454,10 +413,22 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
454
413
|
ensureToolCallsToolUseIdColumn(db);
|
|
455
414
|
ensureToolCallsProjectDirColumn(db);
|
|
456
415
|
ensureToolCallsHostKindColumn(db);
|
|
416
|
+
// GFI-COMPLETE-REMOVAL-001: v1 databases are migrated before the canonical
|
|
417
|
+
// verdict; a failed migration is reported by name and never downgraded
|
|
418
|
+
// into "canonical" (rc-9 — no silent fallback).
|
|
419
|
+
try {
|
|
420
|
+
migrateLegacyGfiSchema(db);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
424
|
+
db.close();
|
|
425
|
+
db = undefined;
|
|
426
|
+
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_migration_failed:${detail}`], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'repair the selected PD trajectory database (legacy GFI columns could not be dropped), then retry' } };
|
|
427
|
+
}
|
|
457
428
|
if (!hasCanonicalSchema(db)) {
|
|
458
429
|
db.close();
|
|
459
430
|
db = undefined;
|
|
460
|
-
return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_schema_invalid'], metadata: { outcome: 'unavailable',
|
|
431
|
+
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
432
|
}
|
|
462
433
|
}
|
|
463
434
|
catch (error) {
|
|
@@ -465,7 +436,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
465
436
|
db?.close();
|
|
466
437
|
}
|
|
467
438
|
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',
|
|
439
|
+
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
440
|
}
|
|
470
441
|
const warnings = [];
|
|
471
442
|
let enrichment;
|
|
@@ -481,49 +452,12 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
481
452
|
db.close();
|
|
482
453
|
}
|
|
483
454
|
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',
|
|
455
|
+
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
456
|
}
|
|
486
457
|
const outcome = normalizeOutcome(event);
|
|
487
458
|
const sanitizedParams = sanitizeToolParams(outcome.params, event.context.workspaceDir);
|
|
488
459
|
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({
|
|
460
|
+
const { eventId } = ids({
|
|
527
461
|
workspaceDir: event.context.workspaceDir,
|
|
528
462
|
sessionId: event.context.sessionId,
|
|
529
463
|
...(event.context.turnId !== undefined ? { turnId: event.context.turnId } : {}),
|
|
@@ -542,7 +476,6 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
542
476
|
const paramsJson = stable(sanitizedParams);
|
|
543
477
|
const resultPreview = preview({ eventId, result: sanitizeValue(outcome.result, 0, event.context.workspaceDir) });
|
|
544
478
|
let duplicate = false;
|
|
545
|
-
let duplicateAdmitted = false;
|
|
546
479
|
try {
|
|
547
480
|
db.transaction(() => {
|
|
548
481
|
// CR-01: the host tool-call id is the stable join key for the
|
|
@@ -557,7 +490,6 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
557
490
|
? 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
491
|
: db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId)) !== undefined) {
|
|
559
492
|
duplicate = true;
|
|
560
|
-
duplicateAdmitted = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) !== undefined;
|
|
561
493
|
return;
|
|
562
494
|
}
|
|
563
495
|
// Review R3/P2: the content-shape fallback dedup is host-scoped the
|
|
@@ -566,40 +498,15 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
566
498
|
? 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
499
|
: 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
500
|
duplicate = true;
|
|
569
|
-
duplicateAdmitted = db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(painId) !== undefined;
|
|
570
501
|
return;
|
|
571
502
|
}
|
|
572
503
|
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
|
-
db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
|
|
574
|
-
.run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? 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
|
-
}
|
|
504
|
+
db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
505
|
+
.run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, paramsJson, resultPreview, createdAt, event.context.toolCallId ?? null, path.resolve(options.projectDir ?? event.context.workspaceDir), options.hostKind ?? null);
|
|
587
506
|
})();
|
|
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
507
|
}
|
|
601
508
|
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,
|
|
509
|
+
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
510
|
}
|
|
604
511
|
finally {
|
|
605
512
|
try {
|
|
@@ -607,24 +514,14 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
607
514
|
}
|
|
608
515
|
catch { /* write result already determined; cleanup is best-effort */ }
|
|
609
516
|
}
|
|
610
|
-
const effectiveAdmitted = admitted || duplicateAdmitted;
|
|
611
517
|
return {
|
|
612
518
|
decision: 'observe',
|
|
613
519
|
source: event.source,
|
|
614
520
|
...(emissionWarning ? { warnings: [emissionWarning] } : {}),
|
|
615
521
|
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 ?? [],
|
|
522
|
+
eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate,
|
|
620
523
|
}
|
|
621
524
|
};
|
|
622
525
|
};
|
|
623
526
|
}
|
|
624
|
-
export function resetProductionPainCooldownForTest() {
|
|
625
|
-
cooldowns.clear();
|
|
626
|
-
}
|
|
627
|
-
export function productionPainCooldownEntryCountForTest() {
|
|
628
|
-
return cooldowns.size;
|
|
629
|
-
}
|
|
630
527
|
export { hasCanonicalSchema as hasProductionPainSchema };
|
|
@@ -10,7 +10,6 @@ export interface ProductionRuleContextRequest {
|
|
|
10
10
|
}
|
|
11
11
|
export type RuleContextProvider = (request: ProductionRuleContextRequest) => unknown | Promise<unknown>;
|
|
12
12
|
export interface RuleInputEnrichment {
|
|
13
|
-
currentGfi: number;
|
|
14
13
|
epTier: number;
|
|
15
14
|
bashRisk: 'safe' | 'normal' | 'dangerous' | 'unknown';
|
|
16
15
|
}
|
|
@@ -114,7 +114,6 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
114
114
|
// so no approval-gate rule could ever exempt read-only investigation.
|
|
115
115
|
// A wired provider remains the host truth and overrides the default.
|
|
116
116
|
let enrichment = {
|
|
117
|
-
currentGfi: 0,
|
|
118
117
|
epTier: 0,
|
|
119
118
|
bashRisk: classifyBashRisk(canonicalKind === 'execute', input.params),
|
|
120
119
|
};
|
|
@@ -125,10 +124,10 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
125
124
|
if (options.ruleInputEnrichmentProvider) {
|
|
126
125
|
try {
|
|
127
126
|
const candidate = await withinGateDeadline(options.ruleInputEnrichmentProvider(request), startedAt);
|
|
128
|
-
if (isRecord(candidate)
|
|
127
|
+
if (isRecord(candidate)
|
|
129
128
|
&& typeof candidate.epTier === 'number' && Number.isFinite(candidate.epTier)
|
|
130
129
|
&& (candidate.bashRisk === 'safe' || candidate.bashRisk === 'normal' || candidate.bashRisk === 'dangerous' || candidate.bashRisk === 'unknown')) {
|
|
131
|
-
enrichment = {
|
|
130
|
+
enrichment = { epTier: candidate.epTier, bashRisk: candidate.bashRisk };
|
|
132
131
|
}
|
|
133
132
|
else
|
|
134
133
|
addWarning(warnings, 'rule_input_enrichment_invalid', 'repair the host enrichment provider');
|
|
@@ -490,7 +489,7 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
490
489
|
const hostInput = {
|
|
491
490
|
action,
|
|
492
491
|
workspace: { isRiskPath: isSensitiveSystemPath(action.normalizedPath) },
|
|
493
|
-
session: { sessionId: event.context.sessionId
|
|
492
|
+
session: { sessionId: event.context.sessionId },
|
|
494
493
|
evolution: { epTier: enrichment.epTier },
|
|
495
494
|
derived: { estimatedLineChanges: estimateLineChanges({ toolName: input.toolName, params: input.params }), bashRisk: enrichment.bashRisk },
|
|
496
495
|
...(context ? { context } : {}),
|
|
@@ -23,6 +23,14 @@ export interface CreateSignalClassifierOptions {
|
|
|
23
23
|
readonly log?: SignalClassifierLog;
|
|
24
24
|
readonly timeoutMs?: number;
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* The Stage-2 structured-output contract this classifier requests. It MUST stay
|
|
28
|
+
* in sync with the registry key in
|
|
29
|
+
* packages/principles-core/src/runtime-v2/adapter/output-schema-registry.ts:
|
|
30
|
+
* the adapter fails loud (`output_invalid`) on an unregistered ref, and the
|
|
31
|
+
* catch below would silently degrade Stage 2 to "no classification".
|
|
32
|
+
*/
|
|
33
|
+
export declare const SIGNAL_CLASSIFICATION_SCHEMA_REF = "signal-classification-output-v2";
|
|
26
34
|
/** Build the classifier from an already-resolved profile (no config I/O). */
|
|
27
35
|
export declare function createSignalLlmClassifier(profile: SignalClassifierProfile, workspaceDir: string, options?: CreateSignalClassifierOptions): SignalLlmClassifier;
|
|
28
36
|
export type SignalClassifierResolution = {
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* consume this instead of re-implementing startRun/pollRun/fetchOutput.
|
|
7
7
|
*
|
|
8
8
|
* The classifier contract is core-owned: `buildLlmPrompt`,
|
|
9
|
-
* `signal-classification-output-
|
|
9
|
+
* `signal-classification-output-v2` and `resolveLlmClassificationPayload`
|
|
10
10
|
* come from `@principles/core/runtime-v2`. This module only owns acquisition:
|
|
11
11
|
* reading the signalCollector runtime profile and calling the adapter.
|
|
12
12
|
*
|
|
@@ -15,6 +15,14 @@
|
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import { PiAiRuntimeAdapter, SIGNAL_CLASSIFIER_SYSTEM_PROMPT, buildLlmPrompt, resolveLlmClassificationPayload, safeStringifyPreview, } from '@principles/core/runtime-v2';
|
|
17
17
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
18
|
+
/**
|
|
19
|
+
* The Stage-2 structured-output contract this classifier requests. It MUST stay
|
|
20
|
+
* in sync with the registry key in
|
|
21
|
+
* packages/principles-core/src/runtime-v2/adapter/output-schema-registry.ts:
|
|
22
|
+
* the adapter fails loud (`output_invalid`) on an unregistered ref, and the
|
|
23
|
+
* catch below would silently degrade Stage 2 to "no classification".
|
|
24
|
+
*/
|
|
25
|
+
export const SIGNAL_CLASSIFICATION_SCHEMA_REF = 'signal-classification-output-v2';
|
|
18
26
|
/** Build the classifier from an already-resolved profile (no config I/O). */
|
|
19
27
|
export function createSignalLlmClassifier(profile, workspaceDir, options = {}) {
|
|
20
28
|
const timeoutMs = options.timeoutMs ?? profile.timeoutMs;
|
|
@@ -42,7 +50,7 @@ export function createSignalLlmClassifier(profile, workspaceDir, options = {}) {
|
|
|
42
50
|
inputPayload: { prompt },
|
|
43
51
|
contextItems: [],
|
|
44
52
|
timeoutMs: effectiveTimeoutMs,
|
|
45
|
-
outputSchemaRef:
|
|
53
|
+
outputSchemaRef: SIGNAL_CLASSIFICATION_SCHEMA_REF,
|
|
46
54
|
systemPrompt: SIGNAL_CLASSIFIER_SYSTEM_PROMPT,
|
|
47
55
|
});
|
|
48
56
|
let status = await adapter.pollRun(handle.runId);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "2.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": "^4.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": "48ab9505979feb0cb13757e30d41d8567715efe1"
|
|
53
53
|
}
|