@principles/host-runtime 4.5.1 → 4.7.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.
@@ -23,6 +23,7 @@ import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js
23
23
  import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
24
24
  import { createHostIntentDocReader } from './intent-doc-reader.js';
25
25
  import { createGovernanceTrajectoryTurnReader } from './governance-trajectory-turn-reader.js';
26
+ import { createConsentLedgerSourceMaterialAuthorization } from './source-material-authorization.js';
26
27
  /** Quiet flag that owns the L3 half of the ladder. */
27
28
  export const DIAGNOSTICIAN_AUTO_RUN_FLAG = 'openclaw_diagnostician_consumer';
28
29
  /** Owner string used for the diagnostics this module starts. */
@@ -102,36 +103,44 @@ export async function runPendingDiagnosticianOnce(options) {
102
103
  }
103
104
  const stateDir = path.join(options.workspaceDir, '.state');
104
105
  try {
105
- const bridge = await createPainSignalBridge({
106
- workspaceDir: options.workspaceDir,
107
- stateDir,
108
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
109
- owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
110
- effectiveConfig: config.effective,
111
- getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
112
- // PRI-1233 / SPEC §9.2: the L3 consumer executes admitted tasks, so it
113
- // is where Stage A actually runs for governance-admitted pains — the
114
- // neutral host reader must ride along or admission would never capture
115
- // a snapshot on this path. Flag-off keeps zero filesystem access.
116
- intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
117
- // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
118
- // like every other diagnosis entry.
119
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir }),
120
- // SPEC §9.6: lazy probe — a flag revoked between candidate pick and
121
- // execution still stops the run at the bridge boundary.
122
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(options.workspaceDir),
123
- });
124
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
125
- if (executed.status === 'failed') {
126
- return {
127
- served: false,
128
- taskId: candidate.taskId,
129
- reason: 'execution_failed',
130
- ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
131
- nextAction: 'Inspect the workspace runtime profile; the task keeps its pending/retry state for the next tick or Console (L2).',
132
- };
106
+ let releaseBridge;
107
+ try {
108
+ const bridge = await createPainSignalBridge({
109
+ workspaceDir: options.workspaceDir,
110
+ stateDir,
111
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
112
+ owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
113
+ effectiveConfig: config.effective,
114
+ getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
115
+ // PRI-1233 / SPEC §9.2: the L3 consumer executes admitted tasks, so it
116
+ // is where Stage A actually runs for governance-admitted pains — the
117
+ // neutral host reader must ride along or admission would never capture
118
+ // a snapshot on this path. Flag-off keeps zero filesystem access.
119
+ intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
120
+ // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
121
+ // like every other diagnosis entry.
122
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir) }),
123
+ // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
124
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir),
125
+ // SPEC §9.6: lazy probe — a flag revoked between candidate pick and
126
+ // execution still stops the run at the bridge boundary.
127
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(options.workspaceDir),
128
+ }, (release) => { releaseBridge = release; });
129
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
130
+ if (executed.status === 'failed') {
131
+ return {
132
+ served: false,
133
+ taskId: candidate.taskId,
134
+ reason: 'execution_failed',
135
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
136
+ nextAction: 'Inspect the workspace runtime profile; the task keeps its pending/retry state for the next tick or Console (L2).',
137
+ };
138
+ }
139
+ return { served: true, taskId: candidate.taskId };
140
+ }
141
+ finally {
142
+ await releaseBridge?.();
133
143
  }
134
- return { served: true, taskId: candidate.taskId };
135
144
  }
136
145
  catch (error) {
137
146
  // A missing/!invalid runtime profile must not throw out of the timer that
@@ -282,6 +282,13 @@ export interface ListGovernanceTurnTextsInput {
282
282
  readonly sessionId: string;
283
283
  /** Restrict to ONE host's observations — session ids are only unique per `(host_kind, rollout_identity)`. */
284
284
  readonly hostKind?: 'codex' | 'openclaw' | 'workbuddy';
285
+ /**
286
+ * PRI-1283 R2: restrict to this SET of hosts' observations (empty = no
287
+ * rows). Mutually exclusive with `hostKind`; used by the turn-reader gate to
288
+ * exclude hosts whose conversation-ingestion consent is no longer granted
289
+ * AT THE QUERY BOUNDARY.
290
+ */
291
+ readonly authorizedHostKinds?: readonly ('codex' | 'openclaw' | 'workbuddy')[];
285
292
  readonly limit?: number;
286
293
  readonly databaseFactory?: ObservationDatabaseFactory;
287
294
  }
@@ -311,6 +318,44 @@ export type ListGovernanceObservationsResult = {
311
318
  observations: readonly GovernanceObservationRecord[];
312
319
  } | Degradation;
313
320
  export declare function listGovernanceObservations(input: ListGovernanceObservationsInput): ListGovernanceObservationsResult;
321
+ /** A retained conversational row for an exact (host, rollout, turn). */
322
+ export interface GovernanceConversationTextRow {
323
+ readonly id: number;
324
+ readonly kind: 'user_turn' | 'assistant_turn';
325
+ readonly logicalKey: string;
326
+ readonly visibleText: string;
327
+ readonly observedAt: string;
328
+ }
329
+ export interface ListGovernanceConversationTextsInput {
330
+ readonly workspaceDir: string;
331
+ readonly hostKind: GovernanceObservationInput['hostKind'];
332
+ readonly rolloutIdentity: string;
333
+ readonly hostTurnId: string;
334
+ /**
335
+ * The turn's LAST N readable conversational rows (a long turn whose final
336
+ * answer sits behind dozens of tool/reasoning observations must still
337
+ * surface it — the generic list's `ORDER BY id LIMIT` window would cut it).
338
+ */
339
+ readonly limit?: number;
340
+ readonly databaseFactory?: ObservationDatabaseFactory;
341
+ }
342
+ export type ListGovernanceConversationTextsResult = {
343
+ readonly ok: true;
344
+ readonly rows: readonly GovernanceConversationTextRow[];
345
+ } | {
346
+ readonly ok: false;
347
+ readonly reason: string;
348
+ readonly nextAction: string;
349
+ };
350
+ /**
351
+ * The ONE selection rule for an exact target turn's readable text, shared by
352
+ * the worker's evidence backfill, the diagnosis-time exact-turn reader and
353
+ * the submit path's opportunistic enrichment (devin BUG_0002): filter
354
+ * host/session/turn + conversational kind + retained readable text INSIDE
355
+ * the SQL, then take the LAST N by id (reversed back to capture order) —
356
+ * never a generic early window over all observation kinds.
357
+ */
358
+ export declare function listGovernanceConversationTextsForHostTurn(input: ListGovernanceConversationTextsInput): ListGovernanceConversationTextsResult;
314
359
  export declare function promoteGovernanceEvidence(input: PromoteGovernanceEvidenceInput): PromoteGovernanceEvidenceResult;
315
360
  export interface QuarantineGovernanceObservationArgs {
316
361
  readonly workspaceDir: string;
@@ -836,15 +836,26 @@ export function listGovernanceTurnTexts(input) {
836
836
  const { db, close } = opened;
837
837
  try {
838
838
  const limit = Math.min(Math.max(input.limit ?? 200, 1), 2000);
839
+ // PRI-1283 R2: host predicate — one host (hostKind) or an authorized SET
840
+ // (authorizedHostKinds; an explicitly EMPTY set matches nothing, which is
841
+ // the correct "every host revoked" outcome, not invalid SQL).
842
+ if (input.hostKind !== undefined && input.authorizedHostKinds !== undefined) {
843
+ return { ok: false, reason: 'governance_turn_texts_invalid_input:host_kind_and_authorized_host_kinds_exclusive', nextAction: 'Pass exactly one of hostKind / authorizedHostKinds.' };
844
+ }
845
+ const hostPredicate = input.hostKind !== undefined
846
+ ? { sql: ' AND host_kind = ?', params: [input.hostKind] }
847
+ : input.authorizedHostKinds !== undefined
848
+ ? input.authorizedHostKinds.length === 0
849
+ ? { sql: ' AND 1 = 0', params: [] }
850
+ : { sql: ` AND host_kind IN (${input.authorizedHostKinds.map(() => '?').join(',')})`, params: [...input.authorizedHostKinds] }
851
+ : { sql: '', params: [] };
839
852
  const newestThenAsc = (identityColumn) => db.prepare('SELECT id, source_ordinal, visible_text, observed_at FROM ('
840
853
  + `SELECT id, source_ordinal, visible_text, observed_at, source_order FROM governance_observations `
841
854
  + `WHERE kind = ? AND ${identityColumn} = ? AND visible_text IS NOT NULL `
842
855
  + `AND retention_class IN ('operational', 'promoted')`
843
- + `${input.hostKind !== undefined ? ' AND host_kind = ?' : ''} `
856
+ + `${hostPredicate.sql} `
844
857
  + 'ORDER BY observed_at DESC, source_order DESC, id DESC LIMIT ?'
845
- + ') ORDER BY observed_at ASC, source_order ASC, id ASC').all(...(input.hostKind !== undefined
846
- ? [input.kind, input.sessionId, input.hostKind, limit]
847
- : [input.kind, input.sessionId, limit]));
858
+ + ') ORDER BY observed_at ASC, source_order ASC, id ASC').all(input.kind, input.sessionId, ...hostPredicate.params, limit);
848
859
  // Exact session rows first; the root_session_id fallback keeps historical
849
860
  // (pre-rollout-identity) rows readable but can no longer drag another
850
861
  // rollout's turns (e.g. a subagent's) into this session's context.
@@ -941,6 +952,47 @@ class PromotionMissingError extends Error {
941
952
  this.name = 'PromotionMissingError';
942
953
  }
943
954
  }
955
+ /**
956
+ * The ONE selection rule for an exact target turn's readable text, shared by
957
+ * the worker's evidence backfill, the diagnosis-time exact-turn reader and
958
+ * the submit path's opportunistic enrichment (devin BUG_0002): filter
959
+ * host/session/turn + conversational kind + retained readable text INSIDE
960
+ * the SQL, then take the LAST N by id (reversed back to capture order) —
961
+ * never a generic early window over all observation kinds.
962
+ */
963
+ export function listGovernanceConversationTextsForHostTurn(input) {
964
+ const opened = openStore(input.workspaceDir, input.databaseFactory);
965
+ if (!('db' in opened))
966
+ return opened;
967
+ const { db, close } = opened;
968
+ try {
969
+ const limit = Math.min(Math.max(input.limit ?? 12, 1), 64);
970
+ const rows = db.prepare([
971
+ 'SELECT id, kind, logical_key, visible_text, observed_at FROM governance_observations',
972
+ 'WHERE host_kind = ? AND rollout_identity = ? AND host_turn_id = ?',
973
+ "AND kind IN ('user_turn','assistant_turn')",
974
+ "AND completeness = 'complete'",
975
+ "AND retention_class IN ('operational','promoted')",
976
+ "AND visible_text IS NOT NULL AND TRIM(visible_text) <> ''",
977
+ 'ORDER BY id DESC LIMIT ?',
978
+ ].join(' ')).all(input.hostKind, input.rolloutIdentity, input.hostTurnId, limit);
979
+ const mapped = rows.map((row) => {
980
+ const kind = rowField(row, 'kind');
981
+ return {
982
+ id: Number(rowField(row, 'id')),
983
+ kind: kind === 'assistant_turn' ? 'assistant_turn' : 'user_turn',
984
+ logicalKey: String(rowField(row, 'logical_key')),
985
+ visibleText: String(rowField(row, 'visible_text')),
986
+ observedAt: String(rowField(row, 'observed_at')),
987
+ };
988
+ });
989
+ mapped.reverse();
990
+ return { ok: true, rows: mapped };
991
+ }
992
+ finally {
993
+ close();
994
+ }
995
+ }
944
996
  export function promoteGovernanceEvidence(input) {
945
997
  const opened = openStore(input.workspaceDir, input.databaseFactory);
946
998
  if (!('db' in opened))
@@ -87,6 +87,16 @@ export interface GovernanceCorrectionCandidate {
87
87
  * admission, rate limit and idempotency are identical either way.
88
88
  */
89
89
  readonly explicitChannel?: 'codex_explicit_prefix' | 'codex_explicit_agent' | 'workbuddy_explicit_prefix';
90
+ /**
91
+ * PRI-1283 round 3 (owner_manual ruling): set ONLY by the registration
92
+ * path after the submitted statement was verified VERBATIM against the
93
+ * current turn's host transcript — the trusted Owner interaction record.
94
+ * Never accepted from a submission payload: an agent cannot self-declare
95
+ * Owner confirmation (a payload claim is not a confirmation record).
96
+ * Agent-assisted statements without this flag persist as Agent-derived
97
+ * (no `owner_statement` classification, no ownerConfirmation block).
98
+ */
99
+ readonly ownerVerbatimConfirmed?: boolean;
90
100
  }
91
101
  export type GovernanceSignalCandidate = GovernanceCorrectionCandidate;
92
102
  export type GovernanceAdmissionOutcome = {
@@ -184,14 +194,53 @@ export type ClaimPendingCandidatesResult = {
184
194
  ok: true;
185
195
  candidates: readonly PendingCorrectionCandidate[];
186
196
  expired: number;
197
+ revoked: number;
187
198
  } | Degradation;
188
199
  /**
189
200
  * Claim bounded pending candidates with an optimistic CAS on the exact payload
190
201
  * text. Rows whose claim is younger than PENDING_REVIEW_CLAIM_TTL_MS are
191
202
  * skipped (another worker is reviewing them); TTL-expired rows become
192
203
  * `abandoned(ttl_expired)` here, before any LLM work.
204
+ *
205
+ * PRI-1283 review round 2 (directive A4): every claim re-reads the LATEST
206
+ * conversation-ingestion consent for the row's host. A host whose consent is
207
+ * no longer granted never yields a claimable candidate — the pending row is
208
+ * terminated as `abandoned('source_revoked')` right here (CAS on the exact
209
+ * payload text; the D6 terminal field set drops trigger.text /
210
+ * trigger.matchedTerms / hostTurnId / task_payload), so the revoked excerpt
211
+ * can neither be claimed nor keep living in the payload. Revocation is the
212
+ * linearization point: claims after it see the terminal row, and an
213
+ * in-flight claim is fenced by `recordPendingCorrectionReview` /
214
+ * `settlePendingCorrection` (both CAS on `decision='pending_llm_review'`).
193
215
  */
194
216
  export declare function claimPendingCorrectionCandidates(input: ClaimPendingCandidatesInput): ClaimPendingCandidatesResult;
217
+ export interface VerifyPendingClaimInput {
218
+ readonly workspaceDir: string;
219
+ readonly logicalObservationKey: string;
220
+ /** The fencing token this worker received from the claim. */
221
+ readonly claimToken: string;
222
+ readonly databaseFactory?: ObservationDatabaseFactory;
223
+ }
224
+ export type VerifyPendingClaimResult = {
225
+ ok: true;
226
+ allowed: true;
227
+ } | {
228
+ ok: true;
229
+ allowed: false;
230
+ reason: 'source_revoked' | 'consent_not_granted' | 'claim_not_owned' | 'not_pending' | 'payload_invalid';
231
+ } | Degradation;
232
+ /**
233
+ * PRI-1283 review round 2 (directive A5): the LAST authorization gate before
234
+ * `classifier(candidate.text, …)` starts a model request. Verifies, in one
235
+ * fresh read, that (a) the row is STILL `pending_llm_review`, (b) this
236
+ * worker's fencing token still owns the claim, and (c) the row's host still
237
+ * has granted consent. This is the revocation linearization boundary for NEW
238
+ * model requests: after a revocation completes (ledger decision or sweep
239
+ * termination), no fresh classifier call may start on the old source's text.
240
+ * A request already in flight cannot be recalled — its RESULT is fenced
241
+ * instead by `recordPendingCorrectionReview` (decision + claimToken CAS).
242
+ */
243
+ export declare function verifyPendingClaimForClassification(input: VerifyPendingClaimInput): VerifyPendingClaimResult;
195
244
  export interface ReleasePendingClaimInput {
196
245
  readonly workspaceDir: string;
197
246
  readonly logicalObservationKey: string;