@principles/host-runtime 0.9.1 → 0.9.2

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.
@@ -20,7 +20,7 @@
20
20
  * Hosts inject: a logger, a structured-event sink, their tool catalog, and an
21
21
  * env getter. Everything else is the existing production path.
22
22
  */
23
- import { type ToolSemanticRegistry } from '@principles/core/runtime-v2';
23
+ import { type ToolSemanticRegistry, type BehaviorEvidencePort } from '@principles/core/runtime-v2';
24
24
  import { type ConsumerGovernanceLogger } from './internalization-consumer-governance.js';
25
25
  export declare const INTERNALIZATION_AUTO_CONSUMER_FLAG_ID = "internalization_auto_consumer";
26
26
  /** Structural logger port — OpenClaw PluginLogger and worker loggers satisfy this. */
@@ -60,6 +60,17 @@ export interface InternalizationConsumerCyclePorts {
60
60
  * omitted → the artificer prompt is built without host context.
61
61
  */
62
62
  readonly hostKinds?: readonly string[];
63
+ /**
64
+ * PRI-982 (SPEC-PD-IAER-001 FR-02/FR-03): host-injected Owner evidence
65
+ * assembly for code_tool_hook artificer tasks. The production
66
+ * implementation (openclaw-plugin) wraps `BehaviorExamplePackAssembler`;
67
+ * hosts that cannot assemble evidence (Codex worker as of PRI-982) omit it.
68
+ * Absent port + a code-channel task degrades OBSERVABLY
69
+ * (evidence_source_unavailable) and the task STAYS PENDING — a host
70
+ * assembly gap must never read as "Owner has not labeled" (SPEC §6.2),
71
+ * and the runner is never constructed evidence-less.
72
+ */
73
+ readonly behaviorEvidence?: BehaviorEvidencePort;
63
74
  /** Log label used in human log prefixes ('AutoConsumer' | 'CodexWorker' | …). */
64
75
  readonly logLabel: string;
65
76
  readonly envGetter?: (name: string) => string | undefined;
@@ -23,7 +23,7 @@
23
23
  import { createRuntimeStateHandle, InternalizationOrchestrator, DreamerRunner, PhilosopherRunner, ScribeRunner, ArtificerRunner, buildArtificerHostSemanticContext, EvaluatorRunner, RolloutReviewerRunner, DefaultDreamerValidator, DefaultPhilosopherValidator, DefaultScribeValidator, DefaultArtificerValidator, DefaultEvaluatorValidator, DefaultRolloutReviewerValidator, PiAiRuntimeAdapter, L2AgentLoopAdapter, ArtificerL2Adapter, buildL2PrincipleReaderFromLedger, OpenClawCliRuntimeAdapter, storeEmitter, createProductionGateDeps, resolveRuntimeConfigFromPdConfig, resolveRuntimeConfigForAgent, AGENT_NAME_FOR_TASK_KIND, isRuntimeConfigError, computeConsumerDecision, FULL_CHAIN_CONSUMER_RUNNER_KINDS, DEFAULT_CONSUMER_RUNNER_KINDS, InternalizationQueueReadModel, MVP_CORE_TASK_KINDS, SqliteConnection, SqliteReconciliationCursorStore, SUCCEEDED_TRANSITIONS_SCOPE, PrincipleTreeLedgerAdapter,
24
24
  // PRI-714: resolve outputLanguage from the same effective config the
25
25
  // runners already receive (EP-07: canonical resolved value, not raw input).
26
- resolveOutputLanguage, } from '@principles/core/runtime-v2';
26
+ resolveOutputLanguage, hydratePITaskRecord, preflightArtificerOwnerEvidence, } from '@principles/core/runtime-v2';
27
27
  import { loadLedger } from '@principles/core/principle-tree-ledger';
28
28
  import { loadPdConfigForPlugin, loadFeatureFlagFromConfig } from './pd-config.js';
29
29
  import { createEvaluatorRepairDeps, createRolloutGovernanceDeps } from './internalization-consumer-governance.js';
@@ -296,6 +296,22 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
296
296
  // without touching leases, idempotency, dependency order, or the
297
297
  // single-task-per-cycle semantics. Ties keep the original priority order.
298
298
  const orderedRunnerKinds = orderKindsByOldestReadyStage(decision.runnerKinds, snapshot.readyTasks);
299
+ // PRI-634 A3: workspace-scoped telemetry sink. Constructed here (per-wake,
300
+ // workspaceDir in scope) so events from THIS workspace's runners are
301
+ // attributable to THIS workspace — a global subscriber on the storeEmitter
302
+ // singleton cannot (multi-workspace isolation, see
303
+ // workspace-telemetry-emitter.ts). Persist failures degrade through the
304
+ // host's structured event port, never break the runner.
305
+ // PRI-795 review P1: shared by the EvaluatorRunner AND the ArtificerL2
306
+ // adapter so `artificer_l2_complete` evidence (abortOwner/budget/elapsed/
307
+ // stopReason/tokenUsage) persists durably instead of vanishing with the
308
+ // process (the EP002-R3 "nothing recoverable after a failure" class).
309
+ const workspaceEmitter = new WorkspaceTelemetryEmitter(storeEmitter, workspaceDir, (detail) => {
310
+ emitEvent('WORKSPACE_TELEMETRY_PERSIST_FAILED', detail);
311
+ });
312
+ let artificerEvidence = null;
313
+ let authoritativeChannel = null;
314
+ let preflightSkipReason;
299
315
  for (const kind of orderedRunnerKinds) {
300
316
  const agentName = AGENT_NAME_FOR_TASK_KIND[kind];
301
317
  if (agentName === undefined) {
@@ -327,6 +343,109 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
327
343
  }
328
344
  const candidate = await orchestrator.wakeOnce(kind);
329
345
  if (candidate.decision === 'would_lease') {
346
+ // PRI-982 (SPEC-PD-IAER-001 §4.2 / FR-02): authoritative channel routing
347
+ // for artificer tasks. The channel is written deterministically by the
348
+ // intake bridge at seed time (pi_metadata.channel — the SINGLE authority,
349
+ // inherited along the chain) and is read from the leased task's hydrated
350
+ // metadata here; the cycle NEVER guesses it from task names or model text.
351
+ // - code_tool_hook → RuleCode sub-chain: evidence preflight FIRST, then
352
+ // L2 (flag permitting) with the assembled pack injected;
353
+ // - prompt → the legal non-L2 pipeline (PiAi), evidence-exempt
354
+ // (production: 40 successes on that pipeline);
355
+ // - unresolvable → refuse to guess: observable skip, no run (T08).
356
+ const leasedTaskForChannel = await stateManager.getTask(candidate.taskId);
357
+ const leasedPiTask = leasedTaskForChannel ? hydratePITaskRecord(leasedTaskForChannel) : null;
358
+ authoritativeChannel = leasedPiTask?.channel ?? null;
359
+ if (candidate.taskKind === 'artificer') {
360
+ if (authoritativeChannel === null || leasedPiTask === null) {
361
+ // Defensive: wakeOnce never leases non-hydratable tasks, so reaching
362
+ // here means the metadata corrupted between wake and read. Fail closed
363
+ // — never route an artificer task without an authoritative channel.
364
+ const channelInfo = JSON.stringify({
365
+ reason: 'artificer_channel_unresolvable',
366
+ taskId: candidate.taskId,
367
+ nextAction: 'Inspect and repair the task metadata (pi_metadata.channel); the consumer refuses to route an artificer task without an authoritative channel (SPEC-PD-IAER-001 §4.2, T08).',
368
+ });
369
+ emitEvent('INTERNALIZATION_CONSUMER_SKIP', channelInfo);
370
+ logger.warn(`[PD:${logLabel}] Artificer task ${candidate.taskId} skipped: authoritative channel unresolvable.`);
371
+ preflightSkipReason = 'artificer_channel_unresolvable';
372
+ continue;
373
+ }
374
+ if (authoritativeChannel === 'code_tool_hook') {
375
+ // Capability OFF must block generation, not merely select L1.
376
+ if (!loadFeatureFlagFromConfig(workspaceDir, 'code_rule_capability').enabled) {
377
+ emitEvent('INTERNALIZATION_CONSUMER_SKIP', JSON.stringify({
378
+ reason: 'code_rule_capability_disabled',
379
+ taskId: candidate.taskId,
380
+ taskKind: candidate.taskKind,
381
+ nextAction: 'Owner must enable code_rule_capability before Code Rule generation.',
382
+ }));
383
+ logger.warn('[PD:' + logLabel + '] Code Rule task ' + candidate.taskId + ' paused: capability disabled.');
384
+ preflightSkipReason = 'code_rule_capability_disabled';
385
+ continue;
386
+ }
387
+ artificerEvidence = await preflightArtificerOwnerEvidence({
388
+ taskId: candidate.taskId,
389
+ piTask: leasedPiTask,
390
+ owner,
391
+ workspaceDir, // FR-08 run-correlation telemetry (PRI-984)
392
+ stateManager,
393
+ eventEmitter: workspaceEmitter,
394
+ behaviorEvidence: ports.behaviorEvidence,
395
+ });
396
+ if (artificerEvidence.decision === 'evidence_source_unavailable') {
397
+ // SPEC §6.2: a host assembly gap is NOT "Owner has not labeled".
398
+ // The task stays pending (re-observable next cycle, zero model
399
+ // cost); the runner is never constructed evidence-less.
400
+ const gapInfo = JSON.stringify({
401
+ reason: 'evidence_source_unavailable',
402
+ taskId: candidate.taskId,
403
+ taskKind: candidate.taskKind,
404
+ nextAction: 'Host must wire the behaviorEvidence port (BehaviorExamplePackAssembler) into the consumer cycle ports; the task stays pending until then.',
405
+ });
406
+ emitEvent('INTERNALIZATION_CONSUMER_SKIP', gapInfo);
407
+ logger.warn(`[PD:${logLabel}] Artificer task ${candidate.taskId} skipped: evidence source unavailable (host must wire the behaviorEvidence port).`);
408
+ preflightSkipReason = 'evidence_source_unavailable';
409
+ continue;
410
+ }
411
+ if (artificerEvidence.decision === 'evidence_source_error') {
412
+ // PRI-980 review P2-1 — SPEC §6.2 case 3: a trajectory-store I/O
413
+ // fault is preserved AS a storage fault. Same family as the absent
414
+ // port: the task stays wake-eligible (the next cycle retries the
415
+ // assembly at zero model cost), the runner is never constructed,
416
+ // and the preflight already emitted the structured degradation
417
+ // telemetry (reason=evidence_source_error, reviewPersisted=false).
418
+ const storageInfo = JSON.stringify({
419
+ reason: 'evidence_source_error',
420
+ taskId: candidate.taskId,
421
+ taskKind: candidate.taskKind,
422
+ nextAction: artificerEvidence.nextAction,
423
+ ...(artificerEvidence.detail !== undefined ? { detail: artificerEvidence.detail } : {}),
424
+ });
425
+ emitEvent('INTERNALIZATION_CONSUMER_SKIP', storageInfo);
426
+ logger.warn(`[PD:${logLabel}] Artificer task ${candidate.taskId} skipped: evidence source error (storage fault preserved; task stays wake-eligible).`);
427
+ preflightSkipReason = 'evidence_source_error';
428
+ continue;
429
+ }
430
+ if (artificerEvidence.decision === 'blocked') {
431
+ // FR-04: the preflight already moved the task atomically into
432
+ // needs_human_review — outside the wake scan (pending/retry_wait
433
+ // only), so it is never auto-rewoken (FR-05/T02). reviewPersisted
434
+ // = false means a concurrent writer won the CAS; still no run.
435
+ emitEvent('INTERNALIZATION_CONSUMER_EVIDENCE_BLOCKED', JSON.stringify({
436
+ taskId: candidate.taskId,
437
+ reasonCode: artificerEvidence.reasonCode,
438
+ nextAction: artificerEvidence.nextAction,
439
+ ...(artificerEvidence.missingFields !== undefined ? { missingFields: [...artificerEvidence.missingFields] } : {}),
440
+ ...(artificerEvidence.detail !== undefined ? { detail: artificerEvidence.detail } : {}),
441
+ reviewPersisted: artificerEvidence.reviewPersisted,
442
+ }));
443
+ logger.warn(`[PD:${logLabel}] Artificer task ${candidate.taskId} blocked on Owner evidence (${artificerEvidence.reasonCode}, reviewPersisted=${artificerEvidence.reviewPersisted}).`);
444
+ preflightSkipReason = 'artificer_blocked_on_owner_evidence';
445
+ continue;
446
+ }
447
+ }
448
+ }
330
449
  wakeResult = candidate;
331
450
  taskRuntimeConfig = kindRuntime;
332
451
  break;
@@ -337,6 +456,10 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
337
456
  lastSkipReason = candidate.decision === 'no_ready_tasks' ? candidate.reason : undefined;
338
457
  }
339
458
  if (!wakeResult || taskRuntimeConfig === null) {
459
+ if (preflightSkipReason !== undefined) {
460
+ lastSkipDecision = preflightSkipReason;
461
+ lastSkipReason = undefined;
462
+ }
340
463
  // A: 预算由周期 finally 统一执行 (每周期恰一次,含 backlog 场景)
341
464
  const skipPayload = { decision: lastSkipDecision };
342
465
  if (lastSkipReason) {
@@ -349,19 +472,6 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
349
472
  // PRI-719: everything downstream reads the LEASED TASK's resolved config —
350
473
  // the kind-specific profile, not the shared gate resolution.
351
474
  const taskRuntimeKind = taskRuntimeConfig.runtimeKind;
352
- // PRI-634 A3: workspace-scoped telemetry sink. Constructed here (per-wake,
353
- // workspaceDir in scope) so events from THIS workspace's runners are
354
- // attributable to THIS workspace — a global subscriber on the storeEmitter
355
- // singleton cannot (multi-workspace isolation, see
356
- // workspace-telemetry-emitter.ts). Persist failures degrade through the
357
- // host's structured event port, never break the runner.
358
- // PRI-795 review P1: shared by the EvaluatorRunner AND the ArtificerL2
359
- // adapter so `artificer_l2_complete` evidence (abortOwner/budget/elapsed/
360
- // stopReason/tokenUsage) persists durably instead of vanishing with the
361
- // process (the EP002-R3 "nothing recoverable after a failure" class).
362
- const workspaceEmitter = new WorkspaceTelemetryEmitter(storeEmitter, workspaceDir, (detail) => {
363
- emitEvent('WORKSPACE_TELEMETRY_PERSIST_FAILED', detail);
364
- });
365
475
  let adapter;
366
476
  if (taskRuntimeKind === 'pi-ai') {
367
477
  // PRI-419: when l2_dreamer flag is on AND this is a dreamer task, route
@@ -372,9 +482,15 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
372
482
  // so the model can self-iterate before submitting. Honors the
373
483
  // code_rule_capability emergency-disable flag (PR #1661 CodeRabbit P1).
374
484
  const codeRuleFlag = loadFeatureFlagFromConfig(workspaceDir, 'code_rule_capability');
485
+ // PRI-982 (SPEC-PD-IAER-001 §4.2): the authoritative TARGET CHANNEL is
486
+ // part of the L2 selection — `pi_metadata.channel === 'code_tool_hook'`
487
+ // (the seed-time bridge authority). prompt-channel artificer tasks are
488
+ // misroutes on L2 (production: 54 failures) and keep the legal non-L2
489
+ // PiAi pipeline below; unresolvable channels never enter L2.
375
490
  if (wakeResult.taskKind === 'artificer'
376
491
  && taskRuntimeKind === 'pi-ai'
377
- && codeRuleFlag.enabled) {
492
+ && codeRuleFlag.enabled
493
+ && authoritativeChannel === 'code_tool_hook') {
378
494
  adapter = new ArtificerL2Adapter({
379
495
  // Profile readiness check guarantees these are non-undefined for
380
496
  // pi-ai runtime kind (validatePdLocalProfile enforces provider/model/apiKeyEnv).
@@ -518,7 +634,16 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
518
634
  }, runnerOptions);
519
635
  break;
520
636
  case 'artificer':
521
- runner = new ArtificerRunner({ stateManager, runtimeAdapter: adapter, eventEmitter: storeEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultArtificerValidator() },
637
+ runner = new ArtificerRunner({
638
+ stateManager, runtimeAdapter: adapter, eventEmitter: storeEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultArtificerValidator(),
639
+ // PRI-982 (SPEC-PD-IAER-001 FR-02): the preflight-assembled Owner
640
+ // evidence pack — present only when the authoritative channel is
641
+ // code_tool_hook AND the readiness gate returned ready (same
642
+ // ArtificerRunnerDeps shape as the run-rulehost CLI pipeline).
643
+ ...(artificerEvidence !== null && artificerEvidence.decision === 'ready'
644
+ ? { behaviorExamplePack: artificerEvidence.pack }
645
+ : {}),
646
+ },
522
647
  // PRI-741: thread the host semantic projection into generation.
523
648
  { ...runnerOptions, ...(artificerHostSemanticContext !== undefined ? { hostSemanticContext: artificerHostSemanticContext } : {}) });
524
649
  break;
@@ -25,6 +25,14 @@ import { StoreEventEmitter } from '@principles/core/runtime-v2';
25
25
  * - artificer_l2_complete(PRI-795 review P1:Artificer L2 的 completion
26
26
  * 证据 — abortOwner/budgetMs/elapsedMs/stopReason/tokenUsage — 必须
27
27
  * crash 前落盘,否则 EP002-R3 的「失败后什么都查不到」重演)
28
+ * - artificer_blocked_on_owner_evidence(PRI-982 / SPEC-PD-IAER-001
29
+ * FR-04:consumer evidence preflight 把任务原子转入 needs_human_review
30
+ * 时的 Owner 恢复证据 — 稳定 reasonCode + nextAction + reviewPersisted。
31
+ * 与 artificer_l2_complete 同理必须 crash 前落盘:进程内 storeEmitter
32
+ * 生产装配零订阅者,事件丢失会让 NHR 任务变成「为什么被挡」的无头案
33
+ * (EP002-R3 类)。注意 readiness_checked 刻意不入列:它对每个 gate
34
+ * verdict 都发(含 ready),落盘会形成高频第二日志;blocked 才是
35
+ * Owner 必须能事后取证的判定点)
28
36
  * - reuse_gate_triggered(PRI-939 Option A:Reuse Review Gate 挂起观察,
29
37
  * Owner 复用闭环的入口证据)
30
38
  * - reuse_evaluation_unavailable(PRI-939 Option A:语义评估降级信号 —
@@ -44,6 +52,11 @@ const CRITICAL_EVENT_ALLOWLIST = new Set([
44
52
  'evaluator_rule_assembled',
45
53
  'evaluator_rule_assembly_failed',
46
54
  'artificer_l2_complete',
55
+ // PRI-982 (SPEC-PD-IAER-001 FR-04): Owner-recovery evidence for a task the
56
+ // consumer evidence preflight just blocked into needs_human_review — stable
57
+ // reasonCode + nextAction must survive a crash (same EP002-R3 class as
58
+ // artificer_l2_complete above; justification in the header comment).
59
+ 'artificer_blocked_on_owner_evidence',
47
60
  'reuse_gate_triggered',
48
61
  'reuse_evaluation_unavailable',
49
62
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -23,7 +23,7 @@
23
23
  "lint": "eslint \"src/**/*.ts\""
24
24
  },
25
25
  "dependencies": {
26
- "@principles/core": "^1.292.1",
26
+ "@principles/core": "^1.292.2",
27
27
  "@principles/install-layout": "^0.3.1",
28
28
  "better-sqlite3": "^13.0.3",
29
29
  "js-yaml": "^5.4.3"