@principles/host-runtime 4.9.4 → 4.10.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.
@@ -0,0 +1,12 @@
1
+ /** Allow-listed environment facts an adapter can prove for after-tool-call capture. */
2
+ export interface AfterToolCallEnvironmentFacts {
3
+ hostVersion?: string | null;
4
+ runtimeVersion?: string | null;
5
+ agentConfigDigest?: string | null;
6
+ modelConfigDigest?: string | null;
7
+ repoCommit?: string | null;
8
+ workspaceStateDigest?: string | null;
9
+ featureFlagsDigest?: string | null;
10
+ }
11
+ /** Missing facts stay NULL; present facts are represented only by their digest. */
12
+ export declare function environmentFactDigestOrNull(value: unknown): string | null;
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalStringify } from '@principles/core/runtime';
3
+ /**
4
+ * Digest one already allow-listed environment fact object. The input is never
5
+ * persisted; only the digest leaves the process. canonicalStringify keeps key
6
+ * order deterministic and marks oversized input explicitly inside the hashed
7
+ * canonical form.
8
+ */
9
+ function digestEnvironmentFact(value) {
10
+ const canonical = canonicalStringify(value);
11
+ return `sha256:${createHash('sha256').update(canonical.text, 'utf8').digest('hex')}`;
12
+ }
13
+ /** Missing facts stay NULL; present facts are represented only by their digest. */
14
+ export function environmentFactDigestOrNull(value) {
15
+ return value === undefined || value === null ? null : digestEnvironmentFact(value);
16
+ }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { buildActivePrinciplePromptContext } from './active-principle-prompt.js'
4
4
  import { type RuleContextProvider, type RuleInputEnrichmentProvider } from './production-rulehost-gate.js';
5
5
  import type { RuleImplementationRuntime } from './rule-implementation-runtime.js';
6
6
  import { type PainDatabaseFactory, type PainEnrichmentProvider } from './production-pain-evidence.js';
7
+ import type { AfterToolCallEnvironmentFacts } from './environment-facts.js';
7
8
  import type { GovernanceHostKind, ToolSemanticRegistry } from '@principles/core/runtime';
8
9
  export * from './active-principle-prompt.js';
9
10
  export * from './prompt-activation-authority.js';
@@ -18,6 +19,7 @@ export { resolvePdHome } from '@principles/install-layout';
18
19
  export * from './production-rulehost-gate.js';
19
20
  export * from './rule-implementation-runtime.js';
20
21
  export * from './production-pain-evidence.js';
22
+ export * from './environment-facts.js';
21
23
  export * from './governance-observation-store.js';
22
24
  export * from './governance-trajectory-turn-reader.js';
23
25
  export * from './plugin-trajectory-turn-store.js';
@@ -100,15 +102,7 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
100
102
  * it and the row records NULL (unknown), never a guess and never a
101
103
  * secret-bearing value.
102
104
  */
103
- afterToolCallEnvironment?: {
104
- hostVersion?: string | null;
105
- runtimeVersion?: string | null;
106
- agentConfigDigest?: string | null;
107
- modelConfigDigest?: string | null;
108
- repoCommit?: string | null;
109
- workspaceStateDigest?: string | null;
110
- featureFlagsDigest?: string | null;
111
- };
105
+ afterToolCallEnvironment?: AfterToolCallEnvironmentFacts | ((event: HostEvent) => AfterToolCallEnvironmentFacts);
112
106
  /** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
113
107
  toolSemantics?: ToolSemanticRegistry;
114
108
  /**
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ export { resolvePdHome } from '@principles/install-layout';
31
31
  export * from './production-rulehost-gate.js';
32
32
  export * from './rule-implementation-runtime.js';
33
33
  export * from './production-pain-evidence.js';
34
+ export * from './environment-facts.js';
34
35
  export * from './governance-observation-store.js';
35
36
  // PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
36
37
  // pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
@@ -262,7 +263,11 @@ export function createProductionHostRuntime(options = {}) {
262
263
  ...(options.events ? { events: options.events } : {}),
263
264
  // PD Phase 1.5 (SPEC R10): adapter-supplied environment facts for the
264
265
  // forward evidence capture; fields the adapter omits stay NULL.
265
- ...(afterToolCallEnvironment ? { environmentProvider: () => afterToolCallEnvironment } : {}),
266
+ ...(afterToolCallEnvironment ? {
267
+ environmentProvider: typeof afterToolCallEnvironment === 'function'
268
+ ? afterToolCallEnvironment
269
+ : () => afterToolCallEnvironment,
270
+ } : {}),
266
271
  }),
267
272
  beforeToolCall: options.beforeToolCall ?? productionGate,
268
273
  async beforePromptBuild(event) {
@@ -23,7 +23,7 @@
23
23
  * gateDeps / hostToolCatalog / hostSemanticContext 必需显式提供,不存在缺省
24
24
  * 掩盖 (类型层面不可缺失)。
25
25
  */
26
- import { type PDRuntimeAdapter, type RuntimeStateManager, type TelemetryEvent, type PIArtifactStore, type EffectivePdConfig, type OutputLanguage, type RefinerRuleHostGateDeps, type RolloutAutoDispatchInput, type RolloutAutoDispatchOutcome, type RolloutRevisionRoutingInput, type SeedArtificerRepairParams, type BehaviorExamplePack, type ArtificerTrustedFactsPort, type ArtificerHostSemanticContext, type DreamerRunnerResult, type PhilosopherRunnerResult, type ScribeRunnerResult, type ArtificerRunnerResult, type EvaluatorRunnerResult, type EvaluatorRunnerOptions, type RolloutReviewerRunnerResult } from '@principles/core/runtime';
26
+ import { type PDRuntimeAdapter, type RuntimeStateManager, type TelemetryEvent, type PIArtifactStore, type EffectivePdConfig, type OutputLanguage, type RefinerRuleHostGateDeps, type RolloutAutoDispatchInput, type RolloutAutoDispatchOutcome, type RolloutRevisionRoutingInput, type SeedArtificerRepairParams, type BehaviorExamplePack, type ArtificerTrustedFactsPort, type ArtificerHostSemanticContext, type DreamerRunnerResult, type PhilosopherRunnerResult, type ScribeRunnerResult, type ArtificerRunnerResult, type EvaluatorRunnerResult, type EvaluatorRunnerOptions, type RolloutReviewerRunnerResult, type SourceMaterialAuthorizationPort } from '@principles/core/runtime';
27
27
  /**
28
28
  * Runner 遥测窄端口 — 与 core `PeerRunnerTelemetryEmitter` 结构等价
29
29
  * (该类型不在 core 冻结 barrel 上,此处按结构声明,零新增导出)。
@@ -44,6 +44,11 @@ export interface SelectedInternalizationTaskBaseDeps {
44
44
  readonly artifactStore: PIArtifactStore;
45
45
  /** Workspace 根 — ledgerIdentity 装配的唯一事实来源。 */
46
46
  readonly workspaceDir: string;
47
+ /**
48
+ * Step 3 (Exp-2): optional model-boundary source-material authorization port.
49
+ * Defaults to the live consent-ledger port for `workspaceDir`.
50
+ */
51
+ readonly sourceMaterialAuthorization?: SourceMaterialAuthorizationPort;
47
52
  }
48
53
  /** Runner 构造/执行选项 — 原样转发 (各入口既有语义保持)。 */
49
54
  export interface SelectedInternalizationTaskRunnerOptions {
@@ -24,6 +24,7 @@
24
24
  * 掩盖 (类型层面不可缺失)。
25
25
  */
26
26
  import { DreamerRunner, PhilosopherRunner, ScribeRunner, ArtificerRunner, EvaluatorRunner, RolloutReviewerRunner, DefaultDreamerValidator, DefaultPhilosopherValidator, DefaultScribeValidator, DefaultArtificerValidator, DefaultEvaluatorValidator, DefaultRolloutReviewerValidator, PrincipleTreeLedgerAdapter, } from '@principles/core/runtime';
27
+ import { createConsentLedgerSourceMaterialAuthorization } from './source-material-authorization.js';
27
28
  /**
28
29
  * Scribe/Artificer/Evaluator 共用的 ledger 身份装配 — 与两个入口此前内联的
29
30
  * 闭包逐字等价 (每次调用新开 PrincipleTreeLedgerAdapter 读盘,无跨周期缓存)。
@@ -62,11 +63,13 @@ export async function executeSelectedInternalizationTask(input) {
62
63
  // Scribe 另需 listForCandidate (chain stamping);Artificer 只读解析。
63
64
  // 一次装配、按 kind 结构化满足各自 deps 形状。
64
65
  const ledgerIdentity = buildWorkspaceLedgerIdentity(workspaceDir, stateManager);
66
+ const sourceMaterialAuthorization = input.sourceMaterialAuthorization
67
+ ?? createConsentLedgerSourceMaterialAuthorization(workspaceDir);
65
68
  switch (input.taskKind) {
66
69
  case 'dreamer':
67
- return new DreamerRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore, validator: new DefaultDreamerValidator() }, runnerOptions).run(taskId);
70
+ return new DreamerRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore, validator: new DefaultDreamerValidator(), sourceMaterialAuthorization }, runnerOptions).run(taskId);
68
71
  case 'philosopher':
69
- return new PhilosopherRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore, validator: new DefaultPhilosopherValidator() }, runnerOptions).run(taskId);
72
+ return new PhilosopherRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore, validator: new DefaultPhilosopherValidator(), sourceMaterialAuthorization }, runnerOptions).run(taskId);
70
73
  case 'scribe':
71
74
  return new ScribeRunner({
72
75
  stateManager, runtimeAdapter, eventEmitter, artifactStore,
@@ -74,6 +77,7 @@ export async function executeSelectedInternalizationTask(input) {
74
77
  // I2 — CHAIN STAMPING (Owner review of PR #1856, P1): 完整三元身份
75
78
  // (resolveForCandidate / isAvailable / listForCandidate)。
76
79
  ledgerIdentity,
80
+ sourceMaterialAuthorization,
77
81
  }, runnerOptions).run(taskId);
78
82
  case 'artificer':
79
83
  return new ArtificerRunner({
@@ -89,6 +89,6 @@ export declare function createProductionPainEvidenceHandler(options?: {
89
89
  hostKind?: GovernanceHostKind;
90
90
  projectDir?: string;
91
91
  events?: HostEventEmitter;
92
- environmentProvider?: () => Pick<NonNullable<Parameters<typeof recordEnvironmentSnapshot>[1]>, 'hostVersion' | 'runtimeVersion' | 'agentConfigDigest' | 'modelConfigDigest' | 'repoCommit' | 'workspaceStateDigest' | 'featureFlagsDigest'>;
92
+ environmentProvider?: (event: HostEvent) => Pick<NonNullable<Parameters<typeof recordEnvironmentSnapshot>[1]>, 'hostVersion' | 'runtimeVersion' | 'agentConfigDigest' | 'modelConfigDigest' | 'repoCommit' | 'workspaceStateDigest' | 'featureFlagsDigest'>;
93
93
  }): (event: HostEvent) => Promise<HostEventResult>;
94
94
  export { hasCanonicalSchema as hasProductionPainSchema };
@@ -442,6 +442,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
442
442
  const paramsJson = stable(sanitizedParams);
443
443
  const resultPreview = preview({ eventId, result: sanitizeValue(outcome.result, 0, event.context.workspaceDir) });
444
444
  let duplicate = false;
445
+ let identityConflict = false;
445
446
  try {
446
447
  db.transaction(() => {
447
448
  // CR-01: the host tool-call id is the stable join key for the
@@ -451,18 +452,48 @@ export function createProductionPainEvidenceHandler(options = {}) {
451
452
  // colliding row from ANOTHER host (or an unattributed legacy row) is
452
453
  // NOT this delivery's duplicate, so both hosts keep independent
453
454
  // records instead of the second being swallowed.
454
- if (event.context.toolCallId !== undefined
455
- && (options.hostKind !== undefined
456
- ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(event.context.sessionId, event.context.toolCallId, options.hostKind)
457
- : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId)) !== undefined) {
458
- duplicate = true;
459
- return;
455
+ if (event.context.toolCallId !== undefined) {
456
+ const existingRow = options.hostKind !== undefined
457
+ ? db.prepare('SELECT tool_name, outcome, duration_ms, exit_code, error_message, params_json, result_preview, turn_id FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(event.context.sessionId, event.context.toolCallId, options.hostKind)
458
+ : db.prepare('SELECT tool_name, outcome, duration_ms, exit_code, error_message, params_json, result_preview, turn_id FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId);
459
+ const existing = isRecord(existingRow) ? existingRow : undefined;
460
+ if (existing !== undefined) {
461
+ duplicate = true;
462
+ // Same physical host-call identity is idempotent only when the
463
+ // evidence content agrees. A same-id/different-content delivery is
464
+ // a conflict: preserve the first evidence and surface the anomaly
465
+ // rather than splitting the call or overwriting history.
466
+ // CR-01 upgrades a live `unknown` row in place when verified
467
+ // transcript evidence arrives. Receiving that same original
468
+ // low-confidence live observation again must not be misclassified
469
+ // as a conflict merely because the durable row is now final. The
470
+ // schema has no separate first-delivery fingerprint, so this
471
+ // direction ignores mutable outcome/exit/preview finalization
472
+ // facts while still comparing immutable call facts below.
473
+ const verifiedUpgradeReplay = outcome.outcome === 'unknown' && existing.outcome !== 'unknown';
474
+ identityConflict = existing.tool_name !== toolName
475
+ || (existing.duration_ms ?? null) !== (outcome.durationMs ?? null)
476
+ || existing.params_json !== paramsJson
477
+ || (existing.turn_id ?? null) !== (event.context.turnId ?? null)
478
+ || (!verifiedUpgradeReplay && (existing.outcome !== outcome.outcome
479
+ || (existing.exit_code ?? null) !== (outcome.exitCode ?? null)
480
+ || (existing.error_message ?? null) !== (outcome.error ?? null)
481
+ || existing.result_preview !== resultPreview));
482
+ if (identityConflict) {
483
+ warnings.push('tool_call_identity_conflict:same host toolCallId delivered with different evidence content; original row preserved');
484
+ }
485
+ return;
486
+ }
460
487
  }
461
488
  // Review R3/P2: the content-shape fallback dedup is host-scoped the
462
- // same way — identical content from two hosts is two records.
463
- if ((options.hostKind !== undefined
464
- ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, options.hostKind)
465
- : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
489
+ // same way — identical content from two hosts is two records. It is
490
+ // only a fallback for hosts WITHOUT a physical call id: once the host
491
+ // supplies toolCallId, a different id is a different physical call even
492
+ // when the bounded content fingerprint happens to match.
493
+ if (event.context.toolCallId === undefined
494
+ && (options.hostKind !== undefined
495
+ ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, options.hostKind)
496
+ : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
466
497
  duplicate = true;
467
498
  return;
468
499
  }
@@ -476,9 +507,8 @@ export function createProductionPainEvidenceHandler(options = {}) {
476
507
  // Capture failure degrades to a warning and never blocks the tool
477
508
  // evidence write (rc-9).
478
509
  if (!envCapturedSessions.has(event.context.sessionId)) {
479
- envCapturedSessions.add(event.context.sessionId);
480
510
  try {
481
- const env = options.environmentProvider?.();
511
+ const env = options.environmentProvider?.(event);
482
512
  recordEnvironmentSnapshot(db, {
483
513
  sessionId: event.context.sessionId,
484
514
  captureKind: 'after_tool_call',
@@ -494,12 +524,17 @@ export function createProductionPainEvidenceHandler(options = {}) {
494
524
  capturedAt: createdAt,
495
525
  payload: {},
496
526
  });
527
+ envCapturedSessions.add(event.context.sessionId);
497
528
  }
498
529
  catch (envError) {
499
530
  warnings.push(`environment_snapshot_failed:${envError instanceof Error ? envError.message.slice(0, 200) : String(envError).slice(0, 200)}`);
500
531
  }
501
532
  }
502
- })();
533
+ // The dedupe probes above must hold the write lock before reading:
534
+ // otherwise two processes can both observe no row and both insert the
535
+ // same physical redelivery. `.immediate()` serializes that check-write
536
+ // critical section without introducing a second writer mechanism.
537
+ }).immediate();
503
538
  }
504
539
  catch (error) {
505
540
  return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_write_failed:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: outcome.outcome, duplicate: false, nextAction: 'inspect the workspace trajectory database and retry' } };
@@ -515,7 +550,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
515
550
  source: event.source,
516
551
  ...(emissionWarning || warnings.length > 0 ? { warnings: [...(emissionWarning ? [emissionWarning] : []), ...warnings] } : {}),
517
552
  metadata: {
518
- eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate,
553
+ eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate, ...(identityConflict ? { identityConflict: true } : {}),
519
554
  }
520
555
  };
521
556
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.9.4",
3
+ "version": "4.10.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": "^8.6.0",
42
+ "@principles/core": "^8.7.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": "2d34c8c2614e1b84e4ea2b4c0bb56bab173da97c"
60
+ "gitHead": "1da1cdfe14b3c0a471e2b990a2aa376bbefe840b"
61
61
  }