@principles/host-runtime 4.12.0 → 5.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.
@@ -2,7 +2,7 @@
2
2
  * Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
3
3
  * amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
4
4
  * (2026-11-12) in:
5
- * docs/archive/superpowers/specs/2026-08-28-codex-governance-closure-g0-g2a-decision.md
5
+ * packages/host-runtime/tests/fixtures/codex-governance-closure-g0-g2a-decision.md
6
6
  * § "Frozen consent disclosure text (setup will show this verbatim)"
7
7
  *
8
8
  * That document is the language SSoT. The frozen text "must not be weakened
@@ -2,7 +2,7 @@
2
2
  * Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
3
3
  * amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
4
4
  * (2026-11-12) in:
5
- * docs/archive/superpowers/specs/2026-08-28-codex-governance-closure-g0-g2a-decision.md
5
+ * packages/host-runtime/tests/fixtures/codex-governance-closure-g0-g2a-decision.md
6
6
  * § "Frozen consent disclosure text (setup will show this verbatim)"
7
7
  *
8
8
  * That document is the language SSoT. The frozen text "must not be weakened
@@ -2,7 +2,7 @@
2
2
  export declare const DIAGNOSTICIAN_AUTO_RUN_FLAG = "openclaw_diagnostician_consumer";
3
3
  /** Owner string used for the diagnostics this module starts. */
4
4
  export declare const DIAGNOSTICIAN_AUTO_RUN_OWNER = "pd-auto-diagnostician";
5
- export type PendingDiagnosticianSkipReason = 'flag_off' | 'capability_disabled' | 'service_not_running' | 'no_candidate' | 'auto_pain_unauthorized';
5
+ export type PendingDiagnosticianSkipReason = 'flag_off' | 'capability_disabled' | 'service_not_running' | 'no_candidate' | 'auto_pain_unauthorized' | 'source_authorization_blocked' | 'candidate_changed';
6
6
  export interface PendingDiagnosticianRunResult {
7
7
  readonly served: boolean;
8
8
  readonly taskId?: string;
@@ -20,6 +20,7 @@
20
20
  import * as path from 'node:path';
21
21
  import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
22
22
  import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
23
+ import { executeQueuedDiagnosisWithInboxRecovery } from './pain-inbox.js';
23
24
  import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
24
25
  import { resolveWorkspacePipelineHostDeps } from './workspace-pipeline-host-deps.js';
25
26
  /** Quiet flag that owns the L3 half of the ladder. */
@@ -132,7 +133,20 @@ export async function runPendingDiagnosticianOnce(options) {
132
133
  // execution still stops the run at the bridge boundary.
133
134
  isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
134
135
  }, (release) => { releaseBridge = release; });
135
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
136
+ const executed = await executeQueuedDiagnosisWithInboxRecovery({
137
+ workspaceDir: options.workspaceDir, task: candidate, stateManager: handle.stateManager,
138
+ execute: () => bridge.executePendingDiagnosis({ taskId: candidate.taskId }),
139
+ });
140
+ if (executed.status === 'skipped'
141
+ && (executed.message === 'auto_pain_unauthorized' || executed.message === 'source_authorization_blocked'
142
+ || executed.message === 'candidate_changed')) {
143
+ return {
144
+ served: false, taskId: candidate.taskId, reason: executed.message,
145
+ nextAction: executed.message === 'candidate_changed'
146
+ ? 'The candidate changed during repair; the next worker cycle can retry.'
147
+ : 'The task remains queued. Review this workspace’s automatic Pain opt-in and host ingestion consent.',
148
+ };
149
+ }
136
150
  if (executed.status === 'failed') {
137
151
  return {
138
152
  served: false,
@@ -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, parsePainIngressV1Payload, 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, deriveProvenanceFromIngressFacts, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
39
  import { claimFirstWriterProvenance, invalidateSessionNoPainLabelsAfterPain } from '@principles/core/runtime/forward-evidence';
40
40
  import { forwardObservationScopeAuthorized } from '@principles/core/runtime/forward-observation-scope';
41
41
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
@@ -2101,9 +2101,31 @@ export async function ensureGovernanceDiagnosticianTask(input) {
2101
2101
  if (ingressDecision.action === 'degrade')
2102
2102
  ingressWarning = ingressDecision.warning;
2103
2103
  }
2104
+ else if (payloadParsed.painIngress !== undefined) {
2105
+ // The Inbox has already evaluated this non-correction (or OpenClaw)
2106
+ // submission. Use the same validated facts that the worker checks on
2107
+ // re-entry, rather than overwriting an automatic origin with a legacy
2108
+ // host-bound default. The automatic submission gate below still runs.
2109
+ const ingress = parsePainIngressV1Payload(payloadParsed.painIngress);
2110
+ if (!ingress.ok) {
2111
+ return { ok: false, reason: ingress.reasonCode, nextAction: 'Repair the persisted Pain ingress facts before retrying the diagnosis.' };
2112
+ }
2113
+ const { origin, correlation } = ingress.payload;
2114
+ const resolved = deriveProvenanceFromIngressFacts(origin, correlation);
2115
+ if (correlation.status !== 'bound' || correlation.hostKind !== markerHostKind
2116
+ || (correlation.hostKind === 'codex' ? correlation.rootSessionId : correlation.sessionId) !== payloadParsed.sessionId
2117
+ || (resolved !== 'automatic_hook' && resolved !== 'host_context_bound')) {
2118
+ return {
2119
+ ok: false,
2120
+ reason: 'pain_ingress_marker_attribution_mismatch',
2121
+ nextAction: 'Repair the persisted Pain marker so its validated host and source agree with the submission.',
2122
+ };
2123
+ }
2124
+ provenance = resolved;
2125
+ }
2104
2126
  else {
2105
- // OpenClaw markers do not flow through this governance seam today; keep
2106
- // the historical provenance rather than inventing an ingress report.
2127
+ // An older marker has no canonical envelope. Preserve its historical
2128
+ // provenance without manufacturing an origin or a new envelope.
2107
2129
  provenance = 'host_context_bound';
2108
2130
  }
2109
2131
  // Preserve the existing fail-closed validation for linked tasks while
@@ -28,6 +28,7 @@
28
28
  * exclude `source_revoked` rows and re-verify `readSourceMaterialAuthorization()`
29
29
  * live before admitting.
30
30
  */
31
+ import { type RuntimeStateManager, type TaskRecord, type PainSignalBridgeResult } from '@principles/core/runtime';
31
32
  import type { ObservationDatabaseFactory } from './governance-observation-store.js';
32
33
  export declare const PAIN_INBOX_TTL_MS: number;
33
34
  export declare const PAIN_INBOX_APPROVING_TTL_MS: number;
@@ -102,6 +103,13 @@ export interface ExpireStalePainInboxResult {
102
103
  readonly expiredOpenClaw: number;
103
104
  readonly reason?: string;
104
105
  }
106
+ /** All background diagnosis workers share this same narrow recovery boundary. */
107
+ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
108
+ workspaceDir: string;
109
+ task: TaskRecord;
110
+ stateManager: Pick<RuntimeStateManager, 'updateTaskIfDiagnosticJsonUnchanged'>;
111
+ execute: () => Promise<PainSignalBridgeResult>;
112
+ }): Promise<PainSignalBridgeResult>;
105
113
  /**
106
114
  * List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
107
115
  * Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
@@ -31,9 +31,11 @@
31
31
  import { createHash, randomUUID } from 'node:crypto';
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
+ import { isDeepStrictEqual } from 'node:util';
34
35
  import Database from 'better-sqlite3';
35
36
  import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
36
- import { evaluatePainIngress, } from '@principles/core/runtime';
37
+ import { checkIngressTopLevelConsistency, createDiagnosticianTaskId, evaluatePainIngress, parsePainIngressV1Payload, } from '@principles/core/runtime';
38
+ import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
37
39
  import { readSourceMaterialAuthorization } from './source-material-authorization.js';
38
40
  import { ensureGovernanceDiagnosticianTask } from './governance-signal-admission.js';
39
41
  export const PAIN_INBOX_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -246,6 +248,15 @@ function evaluateInboxCanonicalAdmission(args) {
246
248
  }
247
249
  return { ok: true, decision };
248
250
  }
251
+ function automaticInboxSubmissionRefusal(workspaceDir, provenance) {
252
+ if (provenance !== 'automatic_hook' || isAutomaticPainSubmissionAuthorized(workspaceDir))
253
+ return null;
254
+ return {
255
+ ok: false,
256
+ reason: 'auto_pain_unauthorized',
257
+ nextAction: 'Enable automatic Pain submission in this workspace before approving this item, or dismiss it. No Pain was submitted.',
258
+ };
259
+ }
249
260
  function openTrajectoryDb(workspaceDir, readonly, factory) {
250
261
  const dbPath = resolveTrajectoryDbPath(workspaceDir);
251
262
  if (!factory && !fs.existsSync(dbPath))
@@ -273,6 +284,103 @@ function deriveInboxCanonicalPainId(hostKind, key) {
273
284
  .slice(0, 16);
274
285
  return `pain_${hostKind}_inbox_${digest}`;
275
286
  }
287
+ /**
288
+ * Repair only the historical Inbox writer's contradictory mirror. The
289
+ * independent, Owner-approved marker must match the queued task; this is not
290
+ * a fallback in the general re-entry validator. It neither replays an
291
+ * approval nor reconstructs evidence from conversation material.
292
+ */
293
+ async function repairQueuedLegacyInboxProvenance(input) {
294
+ const { workspaceDir, task, stateManager } = input;
295
+ const painId = task.inputRef;
296
+ if (task.taskKind !== 'diagnostician' || (task.status !== 'pending' && task.status !== 'retry_wait')
297
+ || task.leaseOwner !== undefined
298
+ || painId === undefined || !/^pain_(codex|workbuddy|openclaw)_inbox_[0-9a-f]{16}$/.test(painId)
299
+ || task.taskId !== createDiagnosticianTaskId(painId) || task.diagnosticJson === undefined) {
300
+ return 'not_applicable';
301
+ }
302
+ const record = parseJsonSafe(task.diagnosticJson);
303
+ if (record?.provenance !== 'host_context_bound' || record.sourcePainId !== painId
304
+ || !Array.isArray(record.evidence))
305
+ return 'not_applicable';
306
+ const ingress = parsePainIngressV1Payload(record.painIngress);
307
+ if (!ingress.ok)
308
+ return 'not_applicable';
309
+ const { correlation, origin } = ingress.payload;
310
+ if (correlation.status !== 'bound' || origin.kind !== 'automatic_hook')
311
+ return 'not_applicable';
312
+ const host = correlation.hostKind;
313
+ const sessionId = host === 'codex' ? correlation.rootSessionId : correlation.sessionId;
314
+ if (origin.source !== `${host}:pain_inbox` || record.hostKind !== host || record.sessionIdHint !== sessionId
315
+ || checkIngressTopLevelConsistency({
316
+ payload: ingress.payload, topLevelProvenance: 'automatic_hook',
317
+ topLevelSessionIdHint: sessionId, topLevelEvidenceCount: record.evidence.length,
318
+ }) !== null)
319
+ return 'not_applicable';
320
+ const trajectory = openTrajectoryDb(workspaceDir, true);
321
+ if (trajectory === null)
322
+ return 'not_applicable';
323
+ try {
324
+ if (!tableExists(trajectory.db, 'governance_signal_admissions'))
325
+ return 'not_applicable';
326
+ const marker = trajectory.db.prepare(`SELECT * FROM governance_signal_admissions
327
+ WHERE canonical_pain_id = ? AND diagnostician_task_id = ? AND decision = 'inbox_approved'`).get(painId, task.taskId);
328
+ if (!isGsaAdmissionRow(marker) || marker.host_kind !== host || marker.root_session_id !== sessionId)
329
+ return 'not_applicable';
330
+ const payload = parseJsonSafe(marker.task_payload_json);
331
+ if (payload === null || payload.source !== record.source || payload.sessionId !== sessionId || payload.hostKind !== host
332
+ || payload.reason !== record.reasonSummary
333
+ || !isRecord(payload.ownerApproval) || typeof payload.ownerApproval.approvedAt !== 'string'
334
+ || !isDeepStrictEqual(payload.painIngress, record.painIngress)
335
+ || !Array.isArray(payload.evidence)
336
+ || !isDeepStrictEqual(payload.evidence.map((entry) => (isRecord(entry) ? { kind: 'behavior_trace', sourceRef: entry.sourceRef, note: entry.note } : null)), record.evidence))
337
+ return 'not_applicable';
338
+ let inboxKey = marker.logical_observation_key;
339
+ if (host === 'openclaw' && inboxKey.startsWith('openclaw:confirmation:')) {
340
+ inboxKey = inboxKey.slice('openclaw:confirmation:'.length);
341
+ if (payload.source !== 'mid_confidence_correction' || payload.ownerApproval.confirmationId !== inboxKey)
342
+ return 'not_applicable';
343
+ }
344
+ else if (payload.source !== 'trajectory_stall' && payload.source !== 'idle_audit_deviation') {
345
+ // Governed-host correction tasks were written by another branch.
346
+ return 'not_applicable';
347
+ }
348
+ if (deriveInboxCanonicalPainId(host, inboxKey) !== painId)
349
+ return 'not_applicable';
350
+ const consent = readSourceMaterialAuthorization({ workspaceDir, hostKind: host });
351
+ if (consent.status !== 'authorized' && !(host === 'openclaw' && consent.reason === 'consent_missing')) {
352
+ return 'source_authorization_blocked';
353
+ }
354
+ if (!isAutomaticPainSubmissionAuthorized(workspaceDir))
355
+ return 'auto_pain_unauthorized';
356
+ const updated = await stateManager.updateTaskIfDiagnosticJsonUnchanged(task.taskId, task.diagnosticJson, {
357
+ diagnosticJson: JSON.stringify({
358
+ ...record, provenance: 'automatic_hook', provenanceReason: 'Pain detected by automatic hook (after_tool_call)',
359
+ }),
360
+ }, {
361
+ expectedStatus: task.status, expectedAttemptCount: task.attemptCount,
362
+ expectedLeaseOwner: null, expectedLeaseExpiresAt: task.leaseExpiresAt ?? null, expectedLeaseGeneration: task.leaseGeneration ?? 0,
363
+ });
364
+ return updated === null ? 'conflict' : 'repaired';
365
+ }
366
+ finally {
367
+ trajectory.close();
368
+ }
369
+ }
370
+ /** All background diagnosis workers share this same narrow recovery boundary. */
371
+ export async function executeQueuedDiagnosisWithInboxRecovery(input) {
372
+ const repair = await repairQueuedLegacyInboxProvenance(input);
373
+ if (repair === 'not_applicable' || repair === 'repaired')
374
+ return input.execute();
375
+ return {
376
+ status: 'skipped',
377
+ taskId: input.task.taskId,
378
+ painId: input.task.inputRef ?? input.task.taskId,
379
+ candidateIds: [],
380
+ ledgerEntryIds: [],
381
+ message: repair === 'conflict' ? 'candidate_changed' : repair,
382
+ };
383
+ }
276
384
  function parseItemId(itemId) {
277
385
  if (itemId.startsWith('gsa:') && itemId.length > 4) {
278
386
  return { source: 'gsa', rawKey: itemId.slice(4) };
@@ -576,6 +684,9 @@ export async function admitOwnerApprovedInboxCandidate(input) {
576
684
  };
577
685
  }
578
686
  const canonical = ingress.decision.legacy;
687
+ const refusal = automaticInboxSubmissionRefusal(workspaceDir, canonical.provenance);
688
+ if (refusal)
689
+ return refusal;
579
690
  // W3 Step 1: CAS claim inbox_candidate -> inbox_approving
580
691
  const approvingPayload = {
581
692
  ...payload,
@@ -797,6 +908,9 @@ export async function admitOwnerApprovedInboxCandidate(input) {
797
908
  };
798
909
  }
799
910
  const canonical = ingress.decision.legacy;
911
+ const refusal = automaticInboxSubmissionRefusal(workspaceDir, canonical.provenance);
912
+ if (refusal)
913
+ return refusal;
800
914
  const claimPayload = {
801
915
  signalKind: 'mid_confidence_correction',
802
916
  excerpt: (ocRow.excerpt ?? '').slice(0, 500),
@@ -2,7 +2,6 @@ import fs from 'node:fs';
2
2
  import { buildRuleHostAction, buildToolSemanticRegistry, deriveToolHintsFromCanonicalKind, estimateLineChanges, mergeDecisions, normalizeRuleHostResult, SqliteConnection, UNAVAILABLE_RULE_CONTEXT, validateRuleContextV2, verifyPiArtifactRowDigest, RECOVERY_CONTROL_SURFACES, } from '@principles/core/runtime';
3
3
  import { buildRuleHostInput, isRuleHostEvaluableKind } from '@principles/core/runtime/internalization/rule-host-input-builder';
4
4
  import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
5
- import { scanRetiredContractSymbols } from './legacy-rule-contract-symbols.js';
6
5
  import { recordDegradedEnforcement } from './degraded-enforcement-marker.js';
7
6
  import { createNodeRuleImplementationRuntime, MAX_ACTIVE_RULES, RULE_BATCH_SOURCE_BYTES, RULE_SOURCE_BYTES, } from './rule-implementation-runtime.js';
8
7
  import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
@@ -639,24 +638,6 @@ export function createProductionRuleHostGate(options = {}) {
639
638
  }
640
639
  const ruleId = typeof content.ruleId === 'string' ? content.ruleId : typeof row.source_rule_id === 'string' ? row.source_rule_id : artifactId;
641
640
  const principleId = typeof content.principleId === 'string' ? content.principleId : typeof row.source_principle_id === 'string' ? row.source_principle_id : ruleId;
642
- // Retired-contract backstop (2026-08-19; host-liveness correction
643
- // 2026-08-21):
644
- // persisted LIVE RuleCode that references removed RuleHost
645
- // contract symbols can never run safely against the new contract
646
- // — reads silently resolve to undefined and change owner-approved
647
- // behavior. The incompatible activation is therefore skipped and
648
- // surfaced with an actionable warning. It must not turn a runtime
649
- // compatibility defect into a host-wide deny; healthy sibling
650
- // rules continue to evaluate. The scan is a local copy (see
651
- // legacy-rule-contract-symbols.ts) so the published bundle keeps
652
- // working against the currently published core.
653
- const retiredSymbols = scanRetiredContractSymbols(content.implementationCode);
654
- if (retiredSymbols.length > 0) {
655
- const nextAction = 'migrate the RuleCode off the retired contract symbols or deactivate the activation, then re-approve a migrated rule';
656
- addWarning(warnings, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
657
- addFault(evaluationFaults, 'skipped', { ...faultSource, ruleId }, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
658
- continue;
659
- }
660
641
  const fallbackMeta = { name: activationId, version: '1', ruleId, coversCondition: 'all' };
661
642
  // PRI-1187: resolved for the observation-only mismatch signal; it
662
643
  // is attached to the candidate but never filters the batch.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.12.0",
3
+ "version": "5.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",
@@ -39,7 +39,7 @@
39
39
  "lint": "eslint \"src/**/*.ts\""
40
40
  },
41
41
  "dependencies": {
42
- "@principles/core": "^9.1.0",
42
+ "@principles/core": "^10.0.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": "e14270ad721ec3a3352d629bb8254be81842cc38"
60
+ "gitHead": "293825348a6f4a40cc561f6a59fc42c64d532766"
61
61
  }
@@ -1,20 +0,0 @@
1
- /**
2
- * Retired RuleHost contract symbol scan — host-runtime local copy.
3
- *
4
- * The shared canonical scanner lives in @principles/core
5
- * (internalization/legacy-rule-contract-scanner.ts) and is used by the
6
- * plugin, console, installer, and pd-cli. This module deliberately does NOT
7
- * import it: the published codex-adapter bundle installs host-runtime
8
- * against the CURRENTLY PUBLISHED @principles/core from the npm registry,
9
- * and a new runtime import would break clean installs until the next core
10
- * release (see tests/published-codex-adapter-bundle.test.ts — it enforces
11
- * exactly this constraint). Keep the symbol patterns in sync with the core
12
- * scanner; the host-runtime tests cover the same detection behavior.
13
- */
14
- /**
15
- * Conservative scan of persisted RuleCode source for retired RuleHost
16
- * contract symbols (field reads and helper calls). A hit means the rule must
17
- * NOT execute against the current contract — its reads would silently
18
- * resolve to undefined and change owner-approved behavior.
19
- */
20
- export declare function scanRetiredContractSymbols(implementationCode: string): string[];
@@ -1,124 +0,0 @@
1
- /**
2
- * Retired RuleHost contract symbol scan — host-runtime local copy.
3
- *
4
- * The shared canonical scanner lives in @principles/core
5
- * (internalization/legacy-rule-contract-scanner.ts) and is used by the
6
- * plugin, console, installer, and pd-cli. This module deliberately does NOT
7
- * import it: the published codex-adapter bundle installs host-runtime
8
- * against the CURRENTLY PUBLISHED @principles/core from the npm registry,
9
- * and a new runtime import would break clean installs until the next core
10
- * release (see tests/published-codex-adapter-bundle.test.ts — it enforces
11
- * exactly this constraint). Keep the symbol patterns in sync with the core
12
- * scanner; the host-runtime tests cover the same detection behavior.
13
- */
14
- // Helper-call form is listed before the bare-word form; the field pattern's
15
- // negative lookahead prevents one hasPlanFile( call reporting twice.
16
- const RETIRED_SYMBOL_PATTERNS = [
17
- { symbol: 'recentThinking', pattern: /\brecentThinking\b/ },
18
- { symbol: 'planStatus', pattern: /\bplanStatus\b/ },
19
- { symbol: 'getPlanStatus', pattern: /\bgetPlanStatus\s*\(/ },
20
- { symbol: 'hasPlanFileHelper', pattern: /\bhasPlanFile\s*\(/ },
21
- { symbol: 'hasPlanFile', pattern: /\bhasPlanFile\b(?!\s*\()/ },
22
- ];
23
- function maskNonExecutableText(source) {
24
- let state = 'code';
25
- let templateExpressionDepth = 0;
26
- let masked = '';
27
- for (let index = 0; index < source.length; index += 1) {
28
- const char = source[index] ?? '';
29
- const next = source[index + 1] ?? '';
30
- if (state === 'code') {
31
- if (templateExpressionDepth > 0 && char === '{') {
32
- templateExpressionDepth += 1;
33
- masked += char;
34
- }
35
- else if (templateExpressionDepth > 0 && char === '}') {
36
- templateExpressionDepth -= 1;
37
- masked += char;
38
- if (templateExpressionDepth === 0)
39
- state = 'template';
40
- }
41
- else if (char === '/' && next === '/') {
42
- masked += ' ';
43
- index += 1;
44
- state = 'line_comment';
45
- }
46
- else if (char === '/' && next === '*') {
47
- masked += ' ';
48
- index += 1;
49
- state = 'block_comment';
50
- }
51
- else if (char === "'") {
52
- masked += ' ';
53
- state = 'single_quote';
54
- }
55
- else if (char === '"') {
56
- masked += ' ';
57
- state = 'double_quote';
58
- }
59
- else if (char === '`') {
60
- masked += ' ';
61
- state = 'template';
62
- }
63
- else {
64
- masked += char;
65
- }
66
- continue;
67
- }
68
- if (state === 'line_comment') {
69
- masked += char === '\n' || char === '\r' ? char : ' ';
70
- if (char === '\n' || char === '\r')
71
- state = 'code';
72
- continue;
73
- }
74
- if (state === 'block_comment') {
75
- if (char === '*' && next === '/') {
76
- masked += ' ';
77
- index += 1;
78
- state = 'code';
79
- }
80
- else {
81
- masked += char === '\n' || char === '\r' ? char : ' ';
82
- }
83
- continue;
84
- }
85
- if (state === 'template' && char === '$' && next === '{') {
86
- masked += ' {';
87
- index += 1;
88
- templateExpressionDepth = 1;
89
- state = 'code';
90
- continue;
91
- }
92
- if (char === '\\') {
93
- masked += ' ';
94
- if (index + 1 < source.length) {
95
- masked += source[index + 1] === '\n' || source[index + 1] === '\r' ? source[index + 1] : ' ';
96
- index += 1;
97
- }
98
- continue;
99
- }
100
- const closesLiteral = (state === 'single_quote' && char === "'") ||
101
- (state === 'double_quote' && char === '"') ||
102
- (state === 'template' && char === '`');
103
- masked += char === '\n' || char === '\r' ? char : ' ';
104
- if (closesLiteral)
105
- state = 'code';
106
- }
107
- return masked;
108
- }
109
- /**
110
- * Conservative scan of persisted RuleCode source for retired RuleHost
111
- * contract symbols (field reads and helper calls). A hit means the rule must
112
- * NOT execute against the current contract — its reads would silently
113
- * resolve to undefined and change owner-approved behavior.
114
- */
115
- export function scanRetiredContractSymbols(implementationCode) {
116
- const executableSource = maskNonExecutableText(implementationCode);
117
- const symbols = [];
118
- for (const { symbol, pattern } of RETIRED_SYMBOL_PATTERNS) {
119
- if (pattern.test(executableSource)) {
120
- symbols.push(symbol);
121
- }
122
- }
123
- return symbols;
124
- }