@principles/host-runtime 4.9.4 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,7 +35,7 @@ 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, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
38
+ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, parsePainIngressV1Payload, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
39
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
40
  import { convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
41
41
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
@@ -580,7 +580,7 @@ function parsePendingReviewMeta(value) {
580
580
  return null;
581
581
  const verdict = own(reviewRaw, 'verdict');
582
582
  if (verdict !== 'correction' && verdict !== 'none'
583
- && verdict !== 'pending_low_confidence' && verdict !== 'pending_llm_error')
583
+ && verdict !== 'inbox_candidate' && verdict !== 'pending_low_confidence' && verdict !== 'pending_llm_error')
584
584
  return null;
585
585
  const confidence = own(reviewRaw, 'confidence');
586
586
  if (confidence !== null && (typeof confidence !== 'number' || !Number.isFinite(confidence)))
@@ -1416,7 +1416,9 @@ export function recordPendingCorrectionReview(input) {
1416
1416
  if (currentClaimToken === undefined || currentClaimToken !== input.claimToken) {
1417
1417
  return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: parsed.payload.review.attempts, reason: 'claim_not_owned' };
1418
1418
  }
1419
- const gate = evaluateStage2ConfidenceGate(input.llmResult);
1419
+ const gate = evaluateStage2ConfidenceGate(input.llmResult, undefined, input.priorAssistantTurnCount !== undefined
1420
+ ? { priorAssistantTurnCount: input.priorAssistantTurnCount }
1421
+ : undefined);
1420
1422
  const attempts = parsed.payload.review.attempts + 1;
1421
1423
  const reviewResult = { verdict: gate.verdict, confidence: gate.confidence, reason: gate.reason };
1422
1424
  const nextPayload = {
@@ -1509,6 +1511,41 @@ export async function settlePendingCorrection(input) {
1509
1511
  }
1510
1512
  return { ok: true, disposition: 'abandoned', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'ttl_expired' };
1511
1513
  }
1514
+ if (review.verdict === 'inbox_candidate') {
1515
+ const capRow = db.prepare(`
1516
+ SELECT COUNT(*) AS n
1517
+ FROM governance_signal_admissions
1518
+ WHERE host_kind = ?
1519
+ AND root_session_id = ?
1520
+ AND signal_kind = 'user_correction'
1521
+ AND decision IN ('inbox_candidate', 'inbox_approving')
1522
+ `).get(hostKind, rootSessionId);
1523
+ if ((capRow?.n ?? 0) >= 2) {
1524
+ const { changes } = db.prepare(`UPDATE governance_signal_admissions SET decision = 'abandoned', reason = ?, task_payload_json = ?, updated_at = ?
1525
+ WHERE logical_observation_key = ? AND decision = 'pending_llm_review' AND task_payload_json = ?`)
1526
+ .run('inbox_cap_reached', pendingTerminalPayload({ decision: 'abandoned', reason: 'inbox_cap_reached', attempts: payload.review.attempts, confidence: review.confidence, nowIso }), nowIso, input.logicalObservationKey, payloadText);
1527
+ if (changes !== 1) {
1528
+ return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'cas_lost' };
1529
+ }
1530
+ return { ok: true, disposition: 'abandoned', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'inbox_cap_reached' };
1531
+ }
1532
+ const inboxPayload = {
1533
+ ...payload,
1534
+ inbox: {
1535
+ signalKind: 'mid_confidence_correction',
1536
+ confidence: review.confidence,
1537
+ reason: review.reason.slice(0, MAX_REASON_BOUND),
1538
+ routedAt: nowIso,
1539
+ },
1540
+ };
1541
+ const { changes } = db.prepare(`UPDATE governance_signal_admissions SET decision = 'inbox_candidate', reason = ?, task_payload_json = ?, updated_at = ?
1542
+ WHERE logical_observation_key = ? AND decision = 'pending_llm_review' AND task_payload_json = ?`)
1543
+ .run(review.reason.slice(0, MAX_REASON_BOUND) || 'stage2_inbox_candidate', JSON.stringify(inboxPayload), nowIso, input.logicalObservationKey, payloadText);
1544
+ if (changes !== 1) {
1545
+ return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'cas_lost' };
1546
+ }
1547
+ return { ok: true, disposition: 'inbox_candidate', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: review.reason };
1548
+ }
1512
1549
  if (review.verdict !== 'correction' && review.verdict !== 'none') {
1513
1550
  if (payload.review.attempts >= STAGE2_MAX_ATTEMPTS) {
1514
1551
  const reason = review.verdict === 'pending_llm_error' ? 'llm_error' : 'low_confidence';
@@ -1773,7 +1810,7 @@ function isGovernanceTaskPayload(value) {
1773
1810
  if (!isRecord(value))
1774
1811
  return false;
1775
1812
  const painType = own(value, 'painType');
1776
- if (painType !== 'user_frustration' && painType !== 'tool_failure')
1813
+ if (painType !== 'user_frustration' && painType !== 'tool_failure' && painType !== 'principle_deviation')
1777
1814
  return false;
1778
1815
  for (const key of ['source', 'reason', 'sessionId']) {
1779
1816
  const candidate = own(value, key);
@@ -1841,6 +1878,9 @@ function isGovernanceTaskPayload(value) {
1841
1878
  if (typeof note !== 'string' || note.length > MAX_SANITIZED_NOTE_CHARS)
1842
1879
  return false;
1843
1880
  }
1881
+ const painIngress = own(value, 'painIngress');
1882
+ if (painIngress !== undefined && !parsePainIngressV1Payload(painIngress).ok)
1883
+ return false;
1844
1884
  return true;
1845
1885
  }
1846
1886
  /**
@@ -1967,10 +2007,11 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1967
2007
  // from trajectory.db with the full lineage tuple. A marker that references a
1968
2008
  // non-existent observation (or a WorkBuddy automatic correction) evaluates
1969
2009
  // to observation_only and fails closed below.
1970
- // A tool_failure pain is its own persisted evidence (the pain row), not a
1971
- // correction claim about behavior — the correction re-derivation must not
1972
- // run for it. Only corrections are gated on a real observation.
1973
- const isCorrectionPayload = payloadParsed.painType !== 'tool_failure';
2010
+ // A tool_failure or principle_deviation pain carries its own validated
2011
+ // ingress evidence; neither is a user-correction claim about behavior.
2012
+ // Only user-frustration corrections are gated on re-derived observation
2013
+ // evidence.
2014
+ const isCorrectionPayload = payloadParsed.painType === 'user_frustration';
1974
2015
  const ingressEvidence = isCorrectionPayload && (markerHostKind === 'codex' || markerHostKind === 'workbuddy')
1975
2016
  ? (sourceMaterialReadable
1976
2017
  ? correctionIngressEvidence({
@@ -2142,6 +2183,7 @@ export async function ensureGovernanceDiagnosticianTask(input) {
2142
2183
  // workbuddy markers attribute 'workbuddy').
2143
2184
  hostKind: payloadParsed.hostKind,
2144
2185
  evidence: [...ingressEvidence],
2186
+ ...(payloadParsed.painIngress !== undefined ? { painIngress: payloadParsed.painIngress } : {}),
2145
2187
  // CR-02: replay the explicit Owner statement verbatim (classified,
2146
2188
  // channel-disclosed) so re-created tasks keep the same input basis.
2147
2189
  ...(payloadParsed.correctionEvidence !== undefined
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Idle Turn Lightweight Audit — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R5 (W6).
3
+ *
4
+ * Performs a bounded, budget-protected post-turn review of idle sessions
5
+ * (`>= 5` turns and idle `>= 5` minutes after true turn completion) and routes
6
+ * verified principle deviations strictly to Pain Inbox
7
+ * (`governance_signal_admissions`, `signal_kind = 'idle_audit_deviation'`,
8
+ * `decision = 'inbox_candidate'`). Never writes directly to `pain_events`.
9
+ *
10
+ * Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.6 / W6):
11
+ * 1. Accurate turn-end trigger (zero new background services):
12
+ * - Codex / WorkBuddy update `idle_audit_session_activity` on `Stop`.
13
+ * - OpenClaw registers native `agent_end` (never relying solely on
14
+ * `llm_output`). Legacy hosts without `agent_end` require `has_active_run = 0`.
15
+ * 2. Real prompt injection evidence + immutable artifact version + lifecycle:
16
+ * - Visibility is proved ONLY from `runtime_v2_prompt_activations_injected`
17
+ * events (`principleIds`, `activationIds`, `artifactIds`, `runId`,
18
+ * `hostKind`, `eventId`) — never from `environment_snapshots`.
19
+ * - `principleVersion` is resolved strictly from immutable `pi_artifacts`
20
+ * via `artifactIds`.
21
+ * - Because `activations` uses `INSERT OR REPLACE` and `PRI-932`
22
+ * (`activation_lifecycle_events`) is still DRAFT, if `activations` shows
23
+ * reactivation overwrite (`activated_at > observedAt`), missing lifecycle
24
+ * bounds, or missing immutable `principleVersion`, MUST return
25
+ * `verdict: 'INCONCLUSIVE'` — never infer historical state from current
26
+ * state and never fabricate a `deviationAnchor`.
27
+ * 3. Atomic daily budget persistence (`idle_audit_daily_budgets`):
28
+ * - Stored inside existing `trajectory.db`.
29
+ * - Reserved via `BEGIN IMMEDIATE` transaction BEFORE calling the LLM
30
+ * (default 10 calls / workspace / UTC day). Timeouts (`<= 25s`) keep the
31
+ * 1 consumed unit (never refunded or double-charged).
32
+ */
33
+ import Database from 'better-sqlite3';
34
+ import type { ObservationDatabaseFactory } from './governance-observation-store.js';
35
+ export declare const DEFAULT_IDLE_AUDIT_MIN_TURNS = 5;
36
+ export declare const DEFAULT_IDLE_AUDIT_IDLE_MS: number;
37
+ export declare const DEFAULT_IDLE_AUDIT_DAILY_LIMIT = 10;
38
+ export declare const DEFAULT_IDLE_AUDIT_TIMEOUT_MS = 25000;
39
+ export type IdleAuditHostKind = 'codex' | 'workbuddy' | 'openclaw';
40
+ export type IdleTurnEndSource = 'agent_end' | 'stop_hook' | 'legacy_idle_check';
41
+ export interface RecordTurnCompletedInput {
42
+ readonly workspaceDir: string;
43
+ readonly hostKind: IdleAuditHostKind;
44
+ readonly sessionId: string;
45
+ readonly turnEndSource: IdleTurnEndSource;
46
+ readonly completedAt?: Date;
47
+ readonly hasActiveRun?: boolean;
48
+ readonly databaseFactory?: ObservationDatabaseFactory;
49
+ }
50
+ export interface ReserveDailyBudgetInput {
51
+ readonly workspaceDir: string;
52
+ readonly dailyLimit?: number;
53
+ readonly now?: Date;
54
+ readonly databaseFactory?: ObservationDatabaseFactory;
55
+ }
56
+ export interface ReserveDailyBudgetResult {
57
+ readonly reserved: boolean;
58
+ readonly workspaceKey: string;
59
+ readonly utcDay: string;
60
+ readonly usedCount: number;
61
+ readonly dailyLimit: number;
62
+ readonly reason?: 'daily_budget_exhausted' | 'db_error';
63
+ }
64
+ export interface VerifiedDeviationAnchor {
65
+ readonly principleId: string;
66
+ readonly principleVersion: string;
67
+ readonly activationId: string;
68
+ readonly artifactId: string;
69
+ readonly eventId: string | null;
70
+ }
71
+ export type PrincipleVisibilityVerdict = {
72
+ readonly verdict: 'PROVEN';
73
+ readonly deviationAnchor: VerifiedDeviationAnchor;
74
+ } | {
75
+ readonly verdict: 'INCONCLUSIVE';
76
+ readonly reason: 'no_logs' | 'missing_injection_event' | 'missing_state_db' | 'missing_immutable_principle_version' | 'activation_lifecycle_overwritten_or_out_of_window' | 'verification_error';
77
+ };
78
+ export interface VerifyPrincipleVisibilityInput {
79
+ readonly workspaceDir: string;
80
+ readonly stateDir?: string;
81
+ readonly eventLogStateDir?: string;
82
+ readonly hostKind: IdleAuditHostKind;
83
+ readonly sessionId: string;
84
+ readonly principleId: string;
85
+ readonly observedAt: string;
86
+ readonly runId?: string;
87
+ readonly stateDbFactory?: ObservationDatabaseFactory;
88
+ }
89
+ export interface IdleAuditSessionCandidate {
90
+ readonly hostKind: IdleAuditHostKind;
91
+ readonly sessionId: string;
92
+ readonly rolloutIdentity: string;
93
+ readonly turnCount: number;
94
+ readonly lastObservationId: string;
95
+ readonly lastTurnCompletedAt: string;
96
+ readonly turnEndSource: string;
97
+ }
98
+ export interface IdleAuditLlmFinding {
99
+ readonly detected: boolean;
100
+ readonly principleId?: string;
101
+ readonly observedAt?: string;
102
+ readonly runId?: string;
103
+ readonly excerpt?: string;
104
+ readonly confidence?: number;
105
+ readonly reasoning?: string;
106
+ }
107
+ export type IdleTurnAuditor = (candidate: IdleAuditSessionCandidate) => Promise<IdleAuditLlmFinding | null>;
108
+ export interface RunIdleTurnAuditCycleInput {
109
+ readonly workspaceDir: string;
110
+ readonly stateDir?: string;
111
+ readonly eventLogStateDir?: string;
112
+ readonly auditor: IdleTurnAuditor | null;
113
+ readonly minTurns?: number;
114
+ readonly idleThresholdMs?: number;
115
+ readonly dailyLimit?: number;
116
+ readonly auditTimeoutMs?: number;
117
+ readonly now?: Date;
118
+ readonly databaseFactory?: ObservationDatabaseFactory;
119
+ readonly stateDbFactory?: ObservationDatabaseFactory;
120
+ }
121
+ export interface RunIdleTurnAuditCycleReport {
122
+ readonly ok: boolean;
123
+ readonly auditedSessions: number;
124
+ readonly admittedInboxCandidates: number;
125
+ readonly inconclusiveCount: number;
126
+ readonly timedOutCount: number;
127
+ readonly budgetReserved: boolean;
128
+ readonly skippedReason?: string;
129
+ readonly idempotencyKey?: string;
130
+ }
131
+ export declare function ensureIdleAuditSchema(db: Database.Database): void;
132
+ /**
133
+ * Record an accurate turn-end timestamp (`agent_end` for OpenClaw, `stop_hook`
134
+ * for Codex/WorkBuddy) into `idle_audit_session_activity`.
135
+ */
136
+ export declare function recordIdleAuditTurnCompleted(input: RecordTurnCompletedInput): {
137
+ ok: boolean;
138
+ reason?: string;
139
+ };
140
+ /**
141
+ * Atomically reserve 1 daily LLM audit slot for `(workspace_key, utc_day)`
142
+ * using a SQLite `BEGIN IMMEDIATE` transaction (W6).
143
+ */
144
+ export declare function reserveIdleAuditDailyBudget(input: ReserveDailyBudgetInput): ReserveDailyBudgetResult;
145
+ /**
146
+ * Verify that `principleId` was genuinely injected into the turn, resolve its
147
+ * immutable `principleVersion` via `artifactIds`, and verify `activations`
148
+ * lifecycle contains `observedAt` without overwrite (W6).
149
+ */
150
+ export declare function verifyPrincipleVisibilityForAudit(input: VerifyPrincipleVisibilityInput): PrincipleVisibilityVerdict;
151
+ /**
152
+ * Run one bounded Idle Turn Audit cycle (at most 1 eligible idle session per
153
+ * worker tick, zero new background daemons).
154
+ */
155
+ export declare function runIdleTurnAuditCycle(input: RunIdleTurnAuditCycleInput): Promise<RunIdleTurnAuditCycleReport>;