@principles/host-runtime 4.9.2 → 4.9.4

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.
@@ -1,11 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { computeBehaviorFacts, } from '@principles/core/runtime';
3
+ import { extractFileHeaderPatchTargets } from '@principles/core/runtime/internalization/rule-host-input-builder';
3
4
  import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
4
5
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
6
  import { readLatestCodexDesignGateDeclaration, resolveCodexDesignGateFact } from './design-gate-facts.js';
6
7
  const HISTORY_LIMIT = 100;
7
8
  const MAX_REASON_LENGTH = 240;
8
- const MAX_PATCH_BYTES = 1024 * 1024;
9
9
  const APPROVED_READONLY_COMMANDS = new Set([
10
10
  'git status',
11
11
  'git status --short',
@@ -18,27 +18,11 @@ function isRecord(value) {
18
18
  function patchTargets(params, projectDir) {
19
19
  if (params === null)
20
20
  return undefined;
21
- // Native Codex sends the patch body under `tool_input.command`
22
- // (`{"command":"*** Begin Patch..."}`); older/embedded callers use
23
- // `patch` or `input`. All three carry the same `*** <op> File:` headers.
24
- const patch = typeof params.patch === 'string'
25
- ? params.patch
26
- : typeof params.input === 'string'
27
- ? params.input
28
- : typeof params.command === 'string' ? params.command : null;
29
- if (patch === null || Buffer.byteLength(patch, 'utf8') > MAX_PATCH_BYTES)
30
- return undefined;
31
- const targets = [];
32
- for (const line of patch.split(/\r?\n/)) {
33
- const match = /^\*\*\* (?:Add|Update|Delete) File: (.+)$|^\*\*\* Move (?:from|to): (.+)$/.exec(line);
34
- if (!match)
35
- continue;
36
- const value = (match[1] ?? match[2] ?? '').trim();
37
- if (value.length === 0 || value.includes('\0'))
38
- return undefined;
39
- targets.push(path.resolve(projectDir, value));
40
- }
41
- return targets.length > 0 ? targets : undefined;
21
+ // The core input builder owns the payload parser/carrier precedence so the
22
+ // design-gate projection and evaluator replay cannot drift into two parsers.
23
+ // This host-layer caller retains only workspace resolution (an I/O-boundary
24
+ // concern) of the lexical header paths.
25
+ return extractFileHeaderPatchTargets(params)?.map((target) => path.resolve(projectDir, target));
42
26
  }
43
27
  function safeReadonlyCommand(params) {
44
28
  if (params === null)
@@ -76,7 +76,7 @@ export async function runPendingDiagnosticianOnce(options) {
76
76
  nextAction: capability.nextAction,
77
77
  };
78
78
  }
79
- const handle = await createRuntimeStateHandle({ workspaceDir: options.workspaceDir, readonly: false });
79
+ const handle = await createRuntimeStateHandle({ workspaceDir: options.workspaceDir, readonly: false, bootstrapIfMissing: false });
80
80
  try {
81
81
  const now = options.now ?? new Date().toISOString();
82
82
  const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.limit ?? DEFAULT_CANDIDATE_LIMIT, now);
@@ -35,8 +35,9 @@ 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, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
- import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, ensureForwardEvidenceSchema, } from './production-pain-evidence.js';
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';
39
+ import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
+ import { convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
40
41
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
42
  import { readSourceMaterialAuthorization } from './source-material-authorization.js';
42
43
  import { readConversationIngestionConsent } from './conversation-ingestion/consent.js';
@@ -360,18 +361,11 @@ function openAdmissionStore(workspaceDir, factory) {
360
361
  let db;
361
362
  try {
362
363
  db = factory ? factory(dbPath) : new Database(dbPath);
364
+ // Clean-Slate: prove the baseline before WAL/DDL can mutate the file.
365
+ convergeTrajectorySchemaVersion(db);
363
366
  db.pragma('busy_timeout = 5000');
364
367
  db.pragma('journal_mode = WAL');
365
368
  ensureGovernanceAdmissionSchema(db);
366
- // GFI-COMPLETE-REMOVAL-001: the additive governance open does not retire
367
- // the GFI columns, so a v1 workspace would be judged non-canonical by
368
- // hasProductionPainSchema and refused. Converge it here with the SAME
369
- // migration the other raw open paths use (idempotent, no-op on v2).
370
- migrateLegacyGfiSchema(db);
371
- // PD Phase 1.5: the canonical readiness probe now also proves the
372
- // forward-evidence schema (tool_calls.turn_id + environment_snapshots);
373
- // converge it here like every other raw open path.
374
- ensureForwardEvidenceSchema(db);
375
369
  // The reconciliation pass reads observation-owned tables (promotion
376
370
  // tails): one open makes the whole governance schema ready.
377
371
  ensureGovernanceSchema(db);
@@ -1934,7 +1928,7 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1934
1928
  if (!ownerManual && sourceAuthorization?.status === 'blocked'
1935
1929
  && (sourceAuthorization.reason !== 'consent_missing' || agentAssistedExplicit)) {
1936
1930
  const taskId = createDiagnosticianTaskId(input.canonicalPainId);
1937
- const stateManager = new RuntimeStateManager({ workspaceDir });
1931
+ const stateManager = new RuntimeStateManager({ bootstrapIfMissing: false, workspaceDir });
1938
1932
  try {
1939
1933
  await stateManager.initialize();
1940
1934
  const existing = await stateManager.getTask(taskId);
@@ -2078,7 +2072,7 @@ export async function ensureGovernanceDiagnosticianTask(input) {
2078
2072
  // PRI-624: the state manager MUST be closed on every exit — the Slice C
2079
2073
  // worker calls this seam every cycle, and a leaked handle would pin the
2080
2074
  // workspace state.db for the life of the worker process.
2081
- const stateManager = new RuntimeStateManager({ workspaceDir });
2075
+ const stateManager = new RuntimeStateManager({ bootstrapIfMissing: false, workspaceDir });
2082
2076
  try {
2083
2077
  await stateManager.initialize();
2084
2078
  let existing = await stateManager.getTask(taskId);
package/dist/index.d.ts CHANGED
@@ -53,7 +53,6 @@ export * from './codex-disclosure.js';
53
53
  export * from './codex-ingestion-consent.js';
54
54
  export * from './codex-worker-status.js';
55
55
  export * from './workbuddy-worker-status.js';
56
- export * from './codex-legacy-registration.js';
57
56
  export * from './codex-transcript-locate.js';
58
57
  export * from './intervention-evidence-ingress.js';
59
58
  export * from './degraded-enforcement-marker.js';
package/dist/index.js CHANGED
@@ -119,9 +119,6 @@ export * from './codex-worker-status.js';
119
119
  // authority for the WorkBuddy governance workspace — same one-semantics
120
120
  // placement as the Codex evaluation above, no ingestion step to gate.
121
121
  export * from './workbuddy-worker-status.js';
122
- // PRI-625 Slice D: ONE legacy-registration predicate (installer refusal,
123
- // health dualRegistration, and future setup flows all read the same fact).
124
- export * from './codex-legacy-registration.js';
125
122
  // PRI-625 Slice D: transcript locator moved here so the §15 health service
126
123
  // computes per-rollout lag with the SAME locator the catch-up path uses.
127
124
  export * from './codex-transcript-locate.js';
@@ -37,11 +37,8 @@ export interface ConsumerHostToolCatalog {
37
37
  }
38
38
  export interface InternalizationConsumerCyclePorts {
39
39
  /**
40
- * Runner-owner label recorded on leases ('auto-consumer' |
41
- * 'service-host-worker' | …). PRI-1278 Phase 5: 'service-host-worker' is
42
- * the current workspace-worker identity; leases persisted before the
43
- * Companion-runtime removal may still carry the retired 'companion-worker'
44
- * label — historical records are never migrated.
40
+ * Runner-owner label recorded on leases. The current workspace-worker
41
+ * identity is 'service-host-worker'.
45
42
  */
46
43
  readonly owner: string;
47
44
  readonly logger: ConsumerCycleLogger;
@@ -151,7 +151,7 @@ export function oldestReadyAgeMs(readyTasks, nowMs) {
151
151
  async function runReconciliationBudget(workspaceDir, orchestrator, ports) {
152
152
  const { logger, emitEvent, logLabel } = ports;
153
153
  try {
154
- const conn = new SqliteConnection(workspaceDir);
154
+ const conn = new SqliteConnection({ workspaceDir, bootstrapIfMissing: false });
155
155
  try {
156
156
  const cursorStore = new SqliteReconciliationCursorStore(conn);
157
157
  const stored = cursorStore.get(SUCCEEDED_TRANSITIONS_SCOPE);
@@ -298,7 +298,7 @@ async function executeConsumerCycle(workspaceDir, ports, signals) {
298
298
  }
299
299
  let handle = null;
300
300
  try {
301
- handle = await createRuntimeStateHandle({ workspaceDir, readonly: false });
301
+ handle = await createRuntimeStateHandle({ workspaceDir, readonly: false, bootstrapIfMissing: false });
302
302
  const { stateManager } = handle;
303
303
  // A (最终复核): orchestrator 必须在所有队列状态相关的早退之前创建 —
304
304
  // 纯 orphan 场景 (succeeded 后 crash、队列全空 → readyTaskCount=0) 恰恰
@@ -39,7 +39,7 @@ function makeFlagProbe(workspaceDir) {
39
39
  }
40
40
  /** rollout → ActivationDispatcher 的生产接线 (per dispatch 打开短连接, 与 Console 模式一致) */
41
41
  export async function dispatchRolloutActivation(workspaceDir, input, options = {}) {
42
- const connection = new SqliteConnection(workspaceDir);
42
+ const connection = new SqliteConnection({ workspaceDir, bootstrapIfMissing: false });
43
43
  try {
44
44
  const piArtifactStore = new SqlitePIArtifactStore(connection);
45
45
  const artifactReadModel = {
@@ -151,9 +151,6 @@ export function createEvaluatorRepairDeps(workspaceDir, stateManager, logger) {
151
151
  return result.task.taskId;
152
152
  }
153
153
  if (result.outcome === 'adopted_existing') {
154
- if (result.backfilled) {
155
- logger?.info?.(`[PD:Consumer] repair task ${result.task.taskId} lineage backfilled before reuse`);
156
- }
157
154
  logger?.info?.(`[PD:Consumer] repair task ${result.task.taskId} already exists (in-flight ${result.task.status}); reusing (idempotent seed)`);
158
155
  return result.task.taskId;
159
156
  }
@@ -107,7 +107,7 @@ export function createInterventionEvidenceIngress() {
107
107
  }
108
108
  let connection = null;
109
109
  try {
110
- connection = new SqliteConnection({ workspaceDir: input.workspaceDir, busyTimeoutMs: 0 });
110
+ connection = new SqliteConnection({ bootstrapIfMissing: false, workspaceDir: input.workspaceDir, busyTimeoutMs: 0 });
111
111
  const store = new SqliteInterventionEvidenceStore(connection);
112
112
  const expectedScope = store.getEvidenceScope()?.scopeId ?? scopeIdCandidateFor(input.workspaceDir);
113
113
  if (input.batch.evidenceScopeId !== expectedScope) {
@@ -31,13 +31,6 @@ export declare function deriveProductionCorrectionPainIdentity(fields: {
31
31
  painId: string;
32
32
  };
33
33
  declare function hasCanonicalSchema(db: Database.Database): boolean;
34
- /**
35
- * PD Phase 1.5 (review round 2 — single migration authority): the local
36
- * turn_id / environment_snapshots ensures were REMOVED — the migration lives
37
- * only in @principles/core/runtime/trajectory-schema. Re-exported here so
38
- * the governance admission store's existing import keeps working.
39
- */
40
- export { ensureForwardEvidenceSchema } from '@principles/core/runtime/trajectory-schema';
41
34
  /** One host-verified tool outcome (SPEC-CODEX-PAIN-CLOSURE-001 CR-01). */
42
35
  export interface VerifiedToolOutcomeInput {
43
36
  /** Host tool-call id — the join key written by the live PostToolUse path. */
@@ -2,11 +2,11 @@ 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, migrateLegacyGfiSchema, sanitizeToolParams, sanitizeValue, } from '@principles/core/runtime';
5
+ import { applyTrajectorySchemaBase, sanitizeToolParams, sanitizeValue, } from '@principles/core/runtime';
6
6
  // PRI-1135: the canonical column declaration lives with the DDL owner. Import
7
7
  // the subpath directly so the public runtime barrel surface stays unchanged.
8
- import { TRAJECTORY_REQUIRED_COLUMNS } from '@principles/core/runtime/trajectory-schema';
9
- import { ensureForwardEvidenceSchema, recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
8
+ import { TRAJECTORY_REQUIRED_COLUMNS, convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
9
+ import { recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
10
10
  import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
11
11
  const MAX_PREVIEW = 500;
12
12
  function isRecord(value) {
@@ -221,7 +221,7 @@ function hasCanonicalSchema(db) {
221
221
  // snapshot analysis, golden fixtures) legitimately read pre-Phase-1.5
222
222
  // databases whose rows carry NULL turn_id, and demanding the new columns
223
223
  // there would degrade every honest read-only analysis path. Writable opens
224
- // converge the schema first (ensureForwardEvidenceSchema), so a failure
224
+ // converge the schema first (convergeTrajectorySchemaVersion), so a failure
225
225
  // here still means the column is truly absent.
226
226
  if (!db.readonly) {
227
227
  db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND turn_id = ?');
@@ -230,62 +230,6 @@ function hasCanonicalSchema(db) {
230
230
  }
231
231
  return true;
232
232
  }
233
- /**
234
- * SPEC-CODEX-PAIN-CLOSURE-001 CR-01: additive migration for the host
235
- * tool-call id join column. The schema-owning modules (trajectory-schema.ts
236
- * applyTrajectorySchemaBase) add it for every fresh/managed open; this local
237
- * ensure covers the raw production-handler open, which historically opens
238
- * trajectory.db without running the schema apply.
239
- */
240
- function ensureToolCallsToolUseIdColumn(db) {
241
- const columns = db.prepare('PRAGMA table_info(tool_calls)').all();
242
- if (columns.some((row) => pragmaField(row, 'name') === 'tool_use_id'))
243
- return;
244
- try {
245
- db.exec('ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT');
246
- db.exec('CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)');
247
- }
248
- catch {
249
- // A concurrent writer may have added it between the check and the ALTER;
250
- // the prepared-statement readiness check below fails loud if it is truly absent.
251
- }
252
- }
253
- /** Additive migration for verified host cwd binding; legacy rows stay NULL. */
254
- function ensureToolCallsProjectDirColumn(db) {
255
- const columns = db.prepare('PRAGMA table_info(tool_calls)').all();
256
- if (columns.some((row) => pragmaField(row, 'name') === 'project_dir'))
257
- return;
258
- try {
259
- db.exec('ALTER TABLE tool_calls ADD COLUMN project_dir TEXT');
260
- }
261
- catch {
262
- // A concurrent writer may have added it between the check and the ALTER;
263
- // the prepared-statement readiness check below fails loud if absent.
264
- }
265
- }
266
- /**
267
- * SPEC-RULECODE-HOST-PROMOTION-001 R2: additive migration for producer host
268
- * attribution. Legacy rows stay NULL — the WorkBuddy rule-context reader
269
- * treats a NULL stamp as unprovable (never guessed), so no backfill exists.
270
- */
271
- function ensureToolCallsHostKindColumn(db) {
272
- const columns = db.prepare('PRAGMA table_info(tool_calls)').all();
273
- if (columns.some((row) => pragmaField(row, 'name') === 'host_kind'))
274
- return;
275
- try {
276
- db.exec('ALTER TABLE tool_calls ADD COLUMN host_kind TEXT');
277
- }
278
- catch {
279
- // Same concurrent-writer contract as the sibling migrations above.
280
- }
281
- }
282
- /**
283
- * PD Phase 1.5 (review round 2 — single migration authority): the local
284
- * turn_id / environment_snapshots ensures were REMOVED — the migration lives
285
- * only in @principles/core/runtime/trajectory-schema. Re-exported here so
286
- * the governance admission store's existing import keeps working.
287
- */
288
- export { ensureForwardEvidenceSchema } from '@principles/core/runtime/trajectory-schema';
289
233
  /**
290
234
  * SPEC-CODEX-PAIN-CLOSURE-001 CR-01: upgrade the live-hook observation of a
291
235
  * tool call with the host-verified final result (exit code) read through the
@@ -318,15 +262,13 @@ export function recordVerifiedToolOutcomes(args) {
318
262
  // returning statuses that look successful while the legacy GFI columns
319
263
  // survive would hide the bug (rc-9).
320
264
  try {
321
- migrateLegacyGfiSchema(db);
265
+ convergeTrajectorySchemaVersion(db);
322
266
  }
323
267
  catch (error) {
324
268
  const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
325
269
  const reason = `trajectory_migration_failed:${detail}`;
326
270
  return args.outcomes.map(() => ({ status: 'unavailable', reason }));
327
271
  }
328
- ensureToolCallsToolUseIdColumn(db);
329
- ensureToolCallsHostKindColumn(db);
330
272
  // Review R3/P2: a KNOWN host's call identity includes its attribution.
331
273
  // The lookup matches ONLY rows of the same host — a colliding row from
332
274
  // another host (or an unattributed legacy row) is a DIFFERENT record: the
@@ -434,24 +376,20 @@ export function createProductionPainEvidenceHandler(options = {}) {
434
376
  try {
435
377
  db = options.painDatabaseFactory ? options.painDatabaseFactory(dbPath) : new Database(dbPath);
436
378
  db.pragma('busy_timeout = 5000');
437
- ensureToolCallsToolUseIdColumn(db);
438
- ensureToolCallsProjectDirColumn(db);
439
- ensureToolCallsHostKindColumn(db);
440
- // PD Phase 1.5 (review round 2 — single migration authority): the
441
- // turn_id column + environment_snapshots table come from the ONE core
442
- // ensure (re-exported below).
443
- ensureForwardEvidenceSchema(db);
444
- // GFI-COMPLETE-REMOVAL-001: v1 databases are migrated before the canonical
445
- // verdict; a failed migration is reported by name and never downgraded
446
- // into "canonical" (rc-9 — no silent fallback).
379
+ // Clean-Slate: pre-baseline databases fail closed before any write.
380
+ // Corruption remains a database-availability failure rather than a
381
+ // schema-version refusal.
447
382
  try {
448
- migrateLegacyGfiSchema(db);
383
+ convergeTrajectorySchemaVersion(db);
449
384
  }
450
385
  catch (error) {
451
386
  const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
452
387
  db.close();
453
388
  db = undefined;
454
- 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' } };
389
+ if (!detail.includes('schema_version_incompatible')) {
390
+ return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_database_unavailable:${detail}`], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'inspect or repair the selected PD trajectory database' } };
391
+ }
392
+ return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_schema_incompatible:${detail}`], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'back up the workspace if needed, then run pd runtime init --confirm to initialize a new baseline database' } };
455
393
  }
456
394
  if (!hasCanonicalSchema(db)) {
457
395
  db.close();
@@ -289,6 +289,9 @@ function sweepTrajectoryDb(args) {
289
289
  const counts = emptyCounts();
290
290
  const failures = [];
291
291
  const notApplicable = [];
292
+ if (apply && !fs.existsSync(dbPath)) {
293
+ return { error: 'trajectory_db_not_found: apply sweep will not create the database implicitly' };
294
+ }
292
295
  let db;
293
296
  try {
294
297
  // Directive E2: a dry run opens trajectory.db READ-ONLY (fileMustExist —
@@ -593,16 +596,25 @@ async function sweepStateDb(args) {
593
596
  // (schema init / migrations / WAL pragmas are writes). Open state.db with a
594
597
  // plain readonly connection instead — the dry run only SELECTs. Applying
595
598
  // keeps the manager so task rows go through its CAS authority.
596
- const stateManager = apply ? new RuntimeStateManager({ workspaceDir }) : null;
599
+ const stateManager = apply ? new RuntimeStateManager({ bootstrapIfMissing: false, workspaceDir }) : null;
597
600
  let db;
598
- if (stateManager !== null) {
599
- await stateManager.initialize();
600
- db = stateManager.connection.getDb();
601
+ try {
602
+ if (stateManager !== null) {
603
+ await stateManager.initialize();
604
+ db = stateManager.connection.getDb();
605
+ }
606
+ else {
607
+ db = new Database(stateDbPath, { readonly: true, fileMustExist: true });
608
+ db.pragma('busy_timeout = 5000');
609
+ db.pragma('query_only = ON');
610
+ }
601
611
  }
602
- else {
603
- db = new Database(stateDbPath, { readonly: true, fileMustExist: true });
604
- db.pragma('busy_timeout = 5000');
605
- db.pragma('query_only = ON');
612
+ catch (error) {
613
+ if (stateManager !== null) {
614
+ await stateManager.close().catch(() => undefined);
615
+ }
616
+ failures.push(`state_db_open_failed: ${(error instanceof Error ? error.message : String(error)).slice(0, 160)}`);
617
+ return { counts, failures, notApplicable };
606
618
  }
607
619
  try {
608
620
  const likePattern = `%${GOVERNANCE_OBSERVATION_SOURCE_REF_PREFIX}${logicalKeyPrefix}%`;
@@ -922,6 +934,30 @@ function mergeCounts(target, source) {
922
934
  target[key] += value;
923
935
  }
924
936
  }
937
+ async function validateApplyStateDbBaseline(workspaceDir) {
938
+ const stateDbPath = resolveStateDbPath(workspaceDir);
939
+ if (!fs.existsSync(stateDbPath))
940
+ return { ok: true };
941
+ const manager = new RuntimeStateManager({ workspaceDir, bootstrapIfMissing: false });
942
+ try {
943
+ await manager.initialize();
944
+ manager.connection.getDb();
945
+ return { ok: true };
946
+ }
947
+ catch (error) {
948
+ const details = typeof error === 'object' && error !== null && 'details' in error
949
+ ? error.details
950
+ : undefined;
951
+ return {
952
+ ok: false,
953
+ message: (error instanceof Error ? error.message : String(error)).slice(0, 240),
954
+ ...(typeof details?.nextAction === 'string' ? { nextAction: details.nextAction } : {}),
955
+ };
956
+ }
957
+ finally {
958
+ await manager.close().catch(() => undefined);
959
+ }
960
+ }
925
961
  export async function runSourceRevocationSweep(options) {
926
962
  const workspaceDir = path.resolve(options.workspaceDir);
927
963
  const apply = options.apply === true;
@@ -977,6 +1013,21 @@ export async function runSourceRevocationSweep(options) {
977
1013
  checkedOnly: CHECKED_ONLY_LOCATIONS,
978
1014
  };
979
1015
  }
1016
+ if (apply) {
1017
+ const stateBaseline = await validateApplyStateDbBaseline(workspaceDir);
1018
+ if (!stateBaseline.ok) {
1019
+ return {
1020
+ outcome: 'failed',
1021
+ workspaceDir,
1022
+ ranAt,
1023
+ apply,
1024
+ hosts: [],
1025
+ reason: `state_db_baseline_incompatible: ${stateBaseline.message}`,
1026
+ nextAction: stateBaseline.nextAction ?? 'Inspect or repair the selected PD state database, then rerun the sweep. No revocation cleanup was started.',
1027
+ checkedOnly: CHECKED_ONLY_LOCATIONS,
1028
+ };
1029
+ }
1030
+ }
980
1031
  const trajectoryDbPath = path.join(stateDir, 'trajectory.db');
981
1032
  let outcome = 'completed';
982
1033
  for (const target of toSweep) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.9.2",
3
+ "version": "4.9.4",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -39,7 +39,7 @@
39
39
  "lint": "eslint \"src/**/*.ts\""
40
40
  },
41
41
  "dependencies": {
42
- "@principles/core": "^8.5.2",
42
+ "@principles/core": "^8.6.0",
43
43
  "@principles/install-layout": "^0.12.0",
44
44
  "better-sqlite3": "^13.0.3",
45
45
  "js-yaml": "^5.4.3"
@@ -57,5 +57,5 @@
57
57
  "url": "git+https://github.com/csuzngjh/principles.git"
58
58
  },
59
59
  "license": "Apache-2.0",
60
- "gitHead": "6fd9c6576df0b5a891a5b6a25e7d8041dbf826b4"
60
+ "gitHead": "2d34c8c2614e1b84e4ea2b4c0bb56bab173da97c"
61
61
  }
@@ -1,18 +0,0 @@
1
- /**
2
- * Legacy Codex global-hook registration detection — Codex Governance Closure
3
- * Slice D (PRI-625; SPEC rev 2 §17 legacy-installer retirement).
4
- *
5
- * ONE authority for the "is a PD-owned legacy global registration present"
6
- * fact: the pure parser lives in @principles/core/host
7
- * (parseLegacyCodexHooksRegistration); this wrapper is the FS edge for
8
- * host-runtime consumers (health/setup surfaces). The retired installer uses
9
- * the same core parser at its own edge.
10
- */
11
- import { type LegacyCodexRegistration } from '@principles/core/host';
12
- /**
13
- * Detect a PD-owned legacy global hook registration in ~/.codex/hooks.json.
14
- * Unreadable/malformed/absent ⇒ detected:false (nothing provably ours to
15
- * migrate); the health surface reports the unreadable state separately via
16
- * its own hooks.json presence check.
17
- */
18
- export declare function detectLegacyCodexHookRegistration(hooksJsonPathOverride?: string): LegacyCodexRegistration;
@@ -1,42 +0,0 @@
1
- /**
2
- * Legacy Codex global-hook registration detection — Codex Governance Closure
3
- * Slice D (PRI-625; SPEC rev 2 §17 legacy-installer retirement).
4
- *
5
- * ONE authority for the "is a PD-owned legacy global registration present"
6
- * fact: the pure parser lives in @principles/core/host
7
- * (parseLegacyCodexHooksRegistration); this wrapper is the FS edge for
8
- * host-runtime consumers (health/setup surfaces). The retired installer uses
9
- * the same core parser at its own edge.
10
- */
11
- import fs from 'node:fs';
12
- import * as path from 'node:path';
13
- import { parseLegacyCodexHooksRegistration } from '@principles/core/host';
14
- import { resolvePdHome } from '@principles/install-layout';
15
- function getCodexHooksJsonPath() {
16
- // The Codex home follows the shared PD Home authority (CODEX_HOME override,
17
- // PD_EXPERIMENT_ROOT isolation). A refused resolution fails loud — reading a
18
- // production hooks.json from inside a misconfigured lab would silently
19
- // report foreign governance state.
20
- const home = resolvePdHome();
21
- if (!home.ok) {
22
- throw new Error(`PD home resolution refused (${home.reason}): ${home.message} Next action: ${home.nextAction}`);
23
- }
24
- return path.join(home.codexHome, 'hooks.json');
25
- }
26
- /**
27
- * Detect a PD-owned legacy global hook registration in ~/.codex/hooks.json.
28
- * Unreadable/malformed/absent ⇒ detected:false (nothing provably ours to
29
- * migrate); the health surface reports the unreadable state separately via
30
- * its own hooks.json presence check.
31
- */
32
- export function detectLegacyCodexHookRegistration(hooksJsonPathOverride) {
33
- const hooksJsonPath = hooksJsonPathOverride ?? getCodexHooksJsonPath();
34
- let parsed;
35
- try {
36
- parsed = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
37
- }
38
- catch {
39
- return { detected: false, legacyAsyncPostToolUse: false };
40
- }
41
- return parseLegacyCodexHooksRegistration(parsed);
42
- }