@principles/host-runtime 0.13.4 → 0.13.5

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.
@@ -220,6 +220,8 @@ export interface EnsureGovernanceContinuationInput {
220
220
  readonly workspaceDir: string;
221
221
  readonly logicalObservationKey: string;
222
222
  readonly canonicalPainId: string;
223
+ /** Current Owner consent for Codex conversation evidence. Required to prevent reconciliation from promoting old observations after opt-out. */
224
+ readonly conversationIngestionEnabled: boolean;
223
225
  readonly databaseFactory?: ObservationDatabaseFactory;
224
226
  }
225
227
  export type EnsureGovernanceContinuationResult = {
@@ -228,18 +230,22 @@ export type EnsureGovernanceContinuationResult = {
228
230
  taskCreated: boolean;
229
231
  linkRepaired: boolean;
230
232
  promoted: number;
231
- tailState: 'completed' | 'pending';
233
+ tailState: 'completed' | 'pending' | 'skipped';
232
234
  } | {
233
235
  ok: false;
234
236
  reason: string;
235
237
  nextAction: string;
238
+ taskId?: string;
239
+ taskCreated?: boolean;
240
+ linkRepaired?: boolean;
236
241
  };
237
242
  /**
238
- * Given an admitted canonical pain (identified by its marker), ensure both
239
- * the Diagnostician task AND the evidence promotion exist idempotently.
243
+ * Given an admitted canonical pain (identified by its marker), ensure the
244
+ * Diagnostician task and, only with current conversation-ingestion consent,
245
+ * the evidence promotion exist idempotently.
240
246
  * Single ensure path for both fresh admits and crash recovery (already_admitted
241
- * redelivery). The marker row carries rollout_identity so the function is
242
- * self-contained (caller only needs workspaceDir, logicalObservationKey, painId).
247
+ * redelivery). The marker row carries rollout_identity; callers must also
248
+ * provide the current conversation-ingestion consent.
243
249
  */
244
250
  export declare function ensureGovernanceContinuation(input: EnsureGovernanceContinuationInput): Promise<EnsureGovernanceContinuationResult>;
245
251
  export interface AdmitBareHostPainsInput {
@@ -290,6 +296,8 @@ export interface AdmitBareHostPainsResult {
290
296
  export declare function admitBareHostPains(input: AdmitBareHostPainsInput): Promise<AdmitBareHostPainsResult>;
291
297
  export interface ReconcileGovernanceContinuationInput {
292
298
  readonly workspaceDir: string;
299
+ /** Current Owner consent; false means reconcile may ensure tasks/links but must not read or promote Codex session evidence. */
300
+ readonly conversationIngestionEnabled: boolean;
293
301
  /** Bounded work per pass (default 50 admitted pains). */
294
302
  readonly limit?: number;
295
303
  readonly databaseFactory?: ObservationDatabaseFactory;
@@ -308,10 +316,13 @@ export interface ReconcileGovernanceContinuationResult {
308
316
  /**
309
317
  * Narrow idempotent reconciliation between the trajectory admission markers
310
318
  * and the Runtime V2 task store (separate SQLite databases — no cross-store
311
- * transaction exists, SPEC §13). Recovers:
319
+ * transaction exists, SPEC §13). Current conversation-ingestion consent is
320
+ * mandatory because it controls whether Codex observations may be read and
321
+ * promoted; task/link recovery remains available when consent is off. Recovers:
312
322
  * - Case A: pain admitted, crash before task creation → create the task now;
313
323
  * - Case B: task exists, crash before the link write → repair the link;
314
- * - Case C: pain+task, crash before promotion → promote evidence now;
324
+ * - Case C: pain+task, crash before promotion → promote evidence now only
325
+ * while conversation-ingestion consent is enabled;
315
326
  * - Case D: promotion started → pending tail → retry completion once; stale
316
327
  * tails are reported (never silently dropped).
317
328
  * Not a background worker — Slice C's Companion worker and the CLI call this.
@@ -482,6 +482,35 @@ function insertAdmissionMarker({ db, identity, canonicalPainId, ruleVersion, rea
482
482
  VALUES (?, ?, ?, ?, ?, 'admitted', ?, NULL, ?, ?, ?, ?, ?)`)
483
483
  .run(identity.hostKind, identity.logicalObservationKey, identity.rolloutIdentity, identity.rootSessionId, identity.signalKind, canonicalPainId, ruleVersion, reason.slice(0, MAX_REASON_BOUND) || null, payloadJson, nowIso, nowIso);
484
484
  }
485
+ /**
486
+ * Convergence probe for the concurrent-redelivery race: two admission
487
+ * processes passed the pre-transaction marker probe before either committed,
488
+ * so the loser's marker INSERT hits the store UNIQUE constraint and its whole
489
+ * transaction rolls back. A marker AND its canonical pain now existing means
490
+ * the idempotency contract already WON — converge on the winner's state (the
491
+ * same semantics as the task-ensure race in ensureGovernanceDiagnosticianTask)
492
+ * instead of surfacing a governance_admission_failed that contradicts the
493
+ * durable state. The probe re-reads the store fresh (rc-7); when the durable
494
+ * facts do NOT exist it returns null and the original error propagates.
495
+ */
496
+ function convergeOnAdmittedMarker(args) {
497
+ const marker = args.db.prepare('SELECT * FROM governance_signal_admissions WHERE logical_observation_key = ?').get(args.logicalObservationKey);
498
+ if (!isRecord(marker))
499
+ return null;
500
+ const canonicalPainId = rowField(marker, 'canonical_pain_id');
501
+ const taskId = rowField(marker, 'diagnostician_task_id');
502
+ if (typeof canonicalPainId !== 'string')
503
+ return null;
504
+ if (args.db.prepare('SELECT 1 FROM pain_events WHERE canonical_pain_id = ?').get(canonicalPainId) === undefined)
505
+ return null;
506
+ return {
507
+ disposition: 'already_admitted',
508
+ kind: args.kind,
509
+ logicalObservationKey: args.logicalObservationKey,
510
+ canonicalPainId,
511
+ diagnosticianTaskId: typeof taskId === 'string' ? taskId : null,
512
+ };
513
+ }
485
514
  function admitCorrection({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDegradation }) {
486
515
  // SPEC-CODEX-PAIN-CLOSURE-001 CR-07: an EXPLICIT Owner statement
487
516
  // (`PD记录痛苦:<text>` in the current Codex message) does not pass through
@@ -672,10 +701,23 @@ function admitOne({ db, candidate, workspaceDir, now, nowIso, keywordStore, onDe
672
701
  diagnosticianTaskId: typeof taskId === 'string' ? taskId : null,
673
702
  };
674
703
  }
675
- if (candidate.kind === 'user_correction') {
676
- return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
704
+ try {
705
+ if (candidate.kind === 'user_correction') {
706
+ return admitCorrection({ db, candidate, workspaceDir, now, nowIso, ...(keywordStore ? { keywordStore } : {}), ...(onDegradation ? { onDegradation } : {}) });
707
+ }
708
+ return admitToolFailure({ db, candidate, workspaceDir, nowIso });
709
+ }
710
+ catch (error) {
711
+ // RateLimitedSignal never reaches here — admitCorrection converts it to a
712
+ // rate_limited outcome internally. A store-level failure (e.g. the loser
713
+ // of a concurrent redelivery hitting the marker UNIQUE constraint) first
714
+ // gets a fresh convergence probe; only a failure with NO durable
715
+ // idempotency facts propagates as governance_admission_failed.
716
+ const converged = convergeOnAdmittedMarker({ db, logicalObservationKey: candidate.logicalObservationKey, kind: candidate.kind });
717
+ if (converged !== null)
718
+ return converged;
719
+ throw error;
677
720
  }
678
- return admitToolFailure({ db, candidate, workspaceDir, nowIso });
679
721
  }
680
722
  /**
681
723
  * Admit governance signal candidates. Each candidate commits in its own
@@ -908,7 +950,7 @@ export async function ensureGovernanceDiagnosticianTask(input) {
908
950
  const stateManager = new RuntimeStateManager({ workspaceDir });
909
951
  try {
910
952
  await stateManager.initialize();
911
- const existing = await stateManager.getTask(taskId);
953
+ let existing = await stateManager.getTask(taskId);
912
954
  if (existing === null) {
913
955
  const stateDir = path.join(workspaceDir, '.state');
914
956
  const config = loadPdConfigForPlugin(workspaceDir);
@@ -949,7 +991,16 @@ export async function ensureGovernanceDiagnosticianTask(input) {
949
991
  // worker, so release it immediately (hook processes exit anyway).
950
992
  await disposePainSignalBridgesForWorkspace(workspaceDir).catch(() => undefined);
951
993
  if (result.status === 'failed') {
952
- return { ok: false, reason: `task_submit_failed:${(result.message ?? result.failureCategory ?? 'unknown').slice(0, 160)}`, nextAction: 'inspect the diagnostician runtime profile; reconciliation retries task creation without losing the admitted pain' };
994
+ // Concurrent-ensure race (hook redelivery × worker reconcile): both
995
+ // callers passed the getTask probe before either committed, and the
996
+ // DETERMINISTIC task id makes the loser's insert hit the store PK.
997
+ // The task existing now is the idempotency contract winning, not a
998
+ // failure — converge on it (Case-B repair semantics) instead of
999
+ // reporting a task_submit_failed that contradicts the durable state.
1000
+ existing = await stateManager.getTask(taskId);
1001
+ if (existing === null) {
1002
+ return { ok: false, reason: `task_submit_failed:${(result.message ?? result.failureCategory ?? 'unknown').slice(0, 160)}`, nextAction: 'inspect the diagnostician runtime profile; reconciliation retries task creation without losing the admitted pain' };
1003
+ }
953
1004
  }
954
1005
  }
955
1006
  db.prepare('UPDATE governance_signal_admissions SET diagnostician_task_id = ?, updated_at = ? WHERE logical_observation_key = ?')
@@ -995,11 +1046,12 @@ export function promoteAdmittedGovernanceEvidence(input) {
995
1046
  return { ok: true, promoted: result.promoted, tailState: result.tailState };
996
1047
  }
997
1048
  /**
998
- * Given an admitted canonical pain (identified by its marker), ensure both
999
- * the Diagnostician task AND the evidence promotion exist idempotently.
1049
+ * Given an admitted canonical pain (identified by its marker), ensure the
1050
+ * Diagnostician task and, only with current conversation-ingestion consent,
1051
+ * the evidence promotion exist idempotently.
1000
1052
  * Single ensure path for both fresh admits and crash recovery (already_admitted
1001
- * redelivery). The marker row carries rollout_identity so the function is
1002
- * self-contained (caller only needs workspaceDir, logicalObservationKey, painId).
1053
+ * redelivery). The marker row carries rollout_identity; callers must also
1054
+ * provide the current conversation-ingestion consent.
1003
1055
  */
1004
1056
  export async function ensureGovernanceContinuation(input) {
1005
1057
  const workspaceDir = path.resolve(input.workspaceDir);
@@ -1016,23 +1068,26 @@ export async function ensureGovernanceContinuation(input) {
1016
1068
  if (typeof rolloutIdentity !== 'string' || rolloutIdentity.length === 0) {
1017
1069
  return { ok: false, reason: 'marker_missing_rollout_identity', nextAction: 're-admit the signal' };
1018
1070
  }
1019
- // 1. Ensure task (idempotent)
1071
+ // Promote before making a runnable task visible, so a worker racing this
1072
+ // continuation cannot begin diagnosis before the eligible evidence window
1073
+ // has been promoted. A promotion failure is retained as a degradation,
1074
+ // but never prevents the task from being durably ensured.
1075
+ const promoted = input.conversationIngestionEnabled
1076
+ ? promoteAdmittedGovernanceEvidence({
1077
+ workspaceDir,
1078
+ rolloutIdentity,
1079
+ triggerLogicalKey: input.logicalObservationKey,
1080
+ canonicalPainId: input.canonicalPainId,
1081
+ })
1082
+ : undefined;
1020
1083
  const ensured = await ensureGovernanceDiagnosticianTask({ workspaceDir, logicalObservationKey: input.logicalObservationKey, canonicalPainId: input.canonicalPainId });
1021
1084
  if (!ensured.ok) {
1022
1085
  return { ok: false, reason: ensured.reason, nextAction: ensured.nextAction };
1023
1086
  }
1024
- // 2. Ensure promotion (idempotent substrate — already promoted = no-op,
1025
- // pending tail = re-complete, never started = start now).
1026
- const promoted = promoteAdmittedGovernanceEvidence({
1027
- workspaceDir,
1028
- rolloutIdentity,
1029
- triggerLogicalKey: input.logicalObservationKey,
1030
- canonicalPainId: input.canonicalPainId,
1031
- });
1032
- if (!promoted.ok) {
1033
- return { ok: false, reason: promoted.reason, nextAction: promoted.nextAction };
1087
+ if (promoted !== undefined && !promoted.ok) {
1088
+ return { ok: false, reason: promoted.reason, nextAction: promoted.nextAction, taskId: ensured.taskId, taskCreated: ensured.created, linkRepaired: ensured.linkRepaired };
1034
1089
  }
1035
- return { ok: true, taskId: ensured.taskId, taskCreated: ensured.created, linkRepaired: ensured.linkRepaired, promoted: promoted.promoted, tailState: promoted.tailState };
1090
+ return { ok: true, taskId: ensured.taskId, taskCreated: ensured.created, linkRepaired: ensured.linkRepaired, promoted: promoted?.promoted ?? 0, tailState: promoted?.tailState ?? 'skipped' };
1036
1091
  }
1037
1092
  finally {
1038
1093
  close();
@@ -1164,10 +1219,13 @@ export async function admitBareHostPains(input) {
1164
1219
  /**
1165
1220
  * Narrow idempotent reconciliation between the trajectory admission markers
1166
1221
  * and the Runtime V2 task store (separate SQLite databases — no cross-store
1167
- * transaction exists, SPEC §13). Recovers:
1222
+ * transaction exists, SPEC §13). Current conversation-ingestion consent is
1223
+ * mandatory because it controls whether Codex observations may be read and
1224
+ * promoted; task/link recovery remains available when consent is off. Recovers:
1168
1225
  * - Case A: pain admitted, crash before task creation → create the task now;
1169
1226
  * - Case B: task exists, crash before the link write → repair the link;
1170
- * - Case C: pain+task, crash before promotion → promote evidence now;
1227
+ * - Case C: pain+task, crash before promotion → promote evidence now only
1228
+ * while conversation-ingestion consent is enabled;
1171
1229
  * - Case D: promotion started → pending tail → retry completion once; stale
1172
1230
  * tails are reported (never silently dropped).
1173
1231
  * Not a background worker — Slice C's Companion worker and the CLI call this.
@@ -1194,7 +1252,8 @@ export async function reconcileGovernanceContinuation(input) {
1194
1252
  //
1195
1253
  // Recovery needed:
1196
1254
  // Case A/B: task link missing (crash before task, or before the link write)
1197
- // Case C: promotion never started (no observation carries this painRef)
1255
+ // Case C: promotion never started (no observation carries this painRef),
1256
+ // but only while current conversation-ingestion consent is on.
1198
1257
  //
1199
1258
  // Case C/D (promotion recovery) is scoped to the hosts whose evidence
1200
1259
  // substrate it exists for: the promotion rows come from transcript
@@ -1211,14 +1270,17 @@ export async function reconcileGovernanceContinuation(input) {
1211
1270
  // not retry pending tails, so pending-tail markers do not block later
1212
1271
  // markers. Stale tails are NOT auto-recoverable (substrate refuses to
1213
1272
  // re-arm them): they are counted separately below and reported.
1273
+ const promotionRecoveryClause = input.conversationIngestionEnabled
1274
+ ? `OR (a.host_kind = 'codex'
1275
+ AND NOT EXISTS (SELECT 1 FROM governance_observations o
1276
+ WHERE o.promotion_ref = a.canonical_pain_id))`
1277
+ : '';
1214
1278
  const markers = db.prepare(`SELECT a.logical_observation_key, a.canonical_pain_id, a.host_kind
1215
1279
  FROM governance_signal_admissions a
1216
1280
  WHERE a.decision = 'admitted'
1217
1281
  AND (
1218
1282
  a.diagnostician_task_id IS NULL
1219
- OR (a.host_kind = 'codex'
1220
- AND NOT EXISTS (SELECT 1 FROM governance_observations o
1221
- WHERE o.promotion_ref = a.canonical_pain_id))
1283
+ ${promotionRecoveryClause}
1222
1284
  )
1223
1285
  ORDER BY a.id LIMIT ?`).all(limit);
1224
1286
  for (const row of markers) {
@@ -1243,7 +1305,7 @@ export async function reconcileGovernanceContinuation(input) {
1243
1305
  }
1244
1306
  continue;
1245
1307
  }
1246
- const cont = await ensureGovernanceContinuation({ workspaceDir, logicalObservationKey: key, canonicalPainId: painId });
1308
+ const cont = await ensureGovernanceContinuation({ workspaceDir, logicalObservationKey: key, canonicalPainId: painId, conversationIngestionEnabled: input.conversationIngestionEnabled });
1247
1309
  if (cont.ok) {
1248
1310
  // Only count REAL actions: a task actually created, a link actually
1249
1311
  // repaired (task existed but the marker link was missing). Healthy
@@ -1259,13 +1321,19 @@ export async function reconcileGovernanceContinuation(input) {
1259
1321
  completedTails += 1;
1260
1322
  }
1261
1323
  else {
1324
+ if (cont.taskCreated)
1325
+ tasksEnsured += 1;
1326
+ if (cont.linkRepaired)
1327
+ linksRepaired += 1;
1262
1328
  degradations.push(`${key}:${cont.reason}`);
1263
1329
  }
1264
1330
  }
1265
1331
  // Also report stale tails scoped to governance admissions.
1266
- const stale = db.prepare(`SELECT COUNT(*) AS n FROM governance_pending_promotion_tails t
1267
- WHERE t.state = 'stale'
1268
- AND EXISTS (SELECT 1 FROM governance_signal_admissions a WHERE a.canonical_pain_id = t.pain_ref)`).get();
1332
+ const stale = input.conversationIngestionEnabled
1333
+ ? db.prepare(`SELECT COUNT(*) AS n FROM governance_pending_promotion_tails t
1334
+ WHERE t.state = 'stale'
1335
+ AND EXISTS (SELECT 1 FROM governance_signal_admissions a WHERE a.canonical_pain_id = t.pain_ref)`).get()
1336
+ : { n: 0 };
1269
1337
  const staleTails = typeof rowField(stale, 'n') === 'number' ? rowField(stale, 'n') : 0;
1270
1338
  return {
1271
1339
  ok: degradations.length === 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "0.13.4",
3
+ "version": "0.13.5",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",