@principles/host-runtime 4.7.2 → 4.9.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.
@@ -6,10 +6,12 @@
6
6
  * manifest registration). codex-adapter re-exports it for compatibility.
7
7
  *
8
8
  * SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
9
- * LLM, no transcript I/O). `manual_action_required` means no
10
- * Companion-registered worker serves this workspace — the manual CLI path
11
- * (catch-up / diagnose / run-once) is the recovery route. 'ready' here means
12
- * "an automatic worker would run and hold the workspace task leases";
9
+ * LLM, no transcript I/O). `manual_action_required` means this workspace is
10
+ * not registered in the canonical install manifest, so the PD Service Host —
11
+ * the only background runtime, triggered by the OS scheduler — never
12
+ * discovers it and no automatic worker cycles run for it. The manual CLI
13
+ * path (catch-up / diagnose / run-once) is the recovery route. 'ready' here
14
+ * means "an automatic worker would run and hold the workspace task leases";
13
15
  * live-worker liveness surfacing belongs to the Slice D health surface.
14
16
  */
15
17
  export type CodexWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
@@ -6,10 +6,12 @@
6
6
  * manifest registration). codex-adapter re-exports it for compatibility.
7
7
  *
8
8
  * SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
9
- * LLM, no transcript I/O). `manual_action_required` means no
10
- * Companion-registered worker serves this workspace — the manual CLI path
11
- * (catch-up / diagnose / run-once) is the recovery route. 'ready' here means
12
- * "an automatic worker would run and hold the workspace task leases";
9
+ * LLM, no transcript I/O). `manual_action_required` means this workspace is
10
+ * not registered in the canonical install manifest, so the PD Service Host —
11
+ * the only background runtime, triggered by the OS scheduler — never
12
+ * discovers it and no automatic worker cycles run for it. The manual CLI
13
+ * path (catch-up / diagnose / run-once) is the recovery route. 'ready' here
14
+ * means "an automatic worker would run and hold the workspace task leases";
13
15
  * live-worker liveness surfacing belongs to the Slice D health surface.
14
16
  */
15
17
  import * as fs from 'node:fs';
@@ -45,7 +47,7 @@ export function computeCodexWorkerStatusMode(input) {
45
47
  return {
46
48
  mode: 'manual_action_required',
47
49
  reason: 'workspace_not_in_install_manifest',
48
- nextAction: `No Companion worker is registered for this workspace. Manual path: pd codex ingest catch-up --workspace "${workspaceDir}", then pd diagnose / pd runtime internalization run-once.`,
50
+ nextAction: `This workspace is not registered in the canonical install manifest, so the PD Service Host does not manage automatic worker cycles for it. Re-run the Codex setup flow to register it. Manual path: pd codex ingest catch-up --workspace "${workspaceDir}", then pd diagnose / pd runtime internalization run-once.`,
49
51
  };
50
52
  }
51
53
  return { mode: 'ready' };
@@ -53,8 +53,8 @@ export async function runPendingDiagnosticianOnce(options) {
53
53
  return {
54
54
  served: false,
55
55
  reason: 'service_not_running',
56
- message: 'the internalization_auto_consumer service is not running',
57
- nextAction: 'Start the OpenClaw service, or diagnose from Console (L2) which does not need a timer.',
56
+ message: 'the internalization consumer cycle is not running in this workspace',
57
+ nextAction: 'Verify the PD Service Host is enabled (pd service status), or diagnose from Console (L2) which does not need a worker cycle.',
58
58
  };
59
59
  }
60
60
  const config = loadPdConfigForPlugin(options.workspaceDir);
@@ -463,7 +463,8 @@ export interface ReconcileGovernanceContinuationResult {
463
463
  * while conversation-ingestion consent is enabled;
464
464
  * - Case D: promotion started → pending tail → retry completion once; stale
465
465
  * tails are reported (never silently dropped).
466
- * Not a background worker — Slice C's Companion worker and the CLI call this.
466
+ * Not a background worker — the Service-Host-spawned workspace workers and
467
+ * the CLI call this.
467
468
  */
468
469
  export declare function reconcileGovernanceContinuation(input: ReconcileGovernanceContinuationInput): Promise<ReconcileGovernanceContinuationResult>;
469
470
  export interface GovernanceAdmissionCounts {
@@ -36,7 +36,7 @@ import path from 'node:path';
36
36
  import { randomUUID } from 'node:crypto';
37
37
  import Database from 'better-sqlite3';
38
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, } from './production-pain-evidence.js';
39
+ import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, ensureForwardEvidenceSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
41
  import { readSourceMaterialAuthorization } from './source-material-authorization.js';
42
42
  import { readConversationIngestionConsent } from './conversation-ingestion/consent.js';
@@ -368,6 +368,10 @@ function openAdmissionStore(workspaceDir, factory) {
368
368
  // hasProductionPainSchema and refused. Converge it here with the SAME
369
369
  // migration the other raw open paths use (idempotent, no-op on v2).
370
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);
371
375
  // The reconciliation pass reads observation-owned tables (promotion
372
376
  // tails): one open makes the whole governance schema ready.
373
377
  ensureGovernanceSchema(db);
@@ -2278,7 +2282,8 @@ export async function ensureGovernanceContinuation(input) {
2278
2282
  * while conversation-ingestion consent is enabled;
2279
2283
  * - Case D: promotion started → pending tail → retry completion once; stale
2280
2284
  * tails are reported (never silently dropped).
2281
- * Not a background worker — Slice C's Companion worker and the CLI call this.
2285
+ * Not a background worker — the Service-Host-spawned workspace workers and
2286
+ * the CLI call this.
2282
2287
  */
2283
2288
  export async function reconcileGovernanceContinuation(input) {
2284
2289
  const workspaceDir = path.resolve(input.workspaceDir);
@@ -1,24 +1,57 @@
1
1
  import { denyAllSourceMaterialAuthorization, } from '@principles/core/runtime';
2
2
  import { listGovernanceConversationTextsForHostTurn, listGovernanceTurnTexts } from './governance-observation-store.js';
3
+ import { listPluginTurnTexts } from './plugin-trajectory-turn-store.js';
3
4
  /** Bound on turns per list call — the assembler bounds the window again. */
4
5
  const MAX_TURNS_PER_SESSION = 200;
5
6
  /** The governance-observation hosts whose turns this reader can serve. */
6
7
  const GOVERNANCE_TURN_HOSTS = ['codex', 'workbuddy'];
8
+ /** Map a plugin-store row into the governance row shape the reader serves. */
9
+ function pluginRowToGovernanceRow(row) {
10
+ return { id: row.id, sourceOrdinal: -1, visibleText: row.text, observedAt: row.observedAt };
11
+ }
12
+ function readGovernanceRows(input) {
13
+ const { workspaceDir, kind, sessionId, hostFilter } = input;
14
+ const result = 'hostKind' in hostFilter
15
+ ? listGovernanceTurnTexts({ workspaceDir, kind, sessionId, hostKind: hostFilter.hostKind, limit: MAX_TURNS_PER_SESSION })
16
+ : listGovernanceTurnTexts({ workspaceDir, kind, sessionId, authorizedHostKinds: hostFilter.authorizedHostKinds, limit: MAX_TURNS_PER_SESSION });
17
+ // Unreadable store: the empty result surfaces as an assembler ambiguity
18
+ // note ("no turns found"), never as a fabricated window.
19
+ return result.ok ? result.turns : [];
20
+ }
21
+ /**
22
+ * PRI-1319: read turn rows for one session. `hostKind` scopes the read:
23
+ * - codex/workbuddy → governance rows of THAT host only (unchanged legacy
24
+ * behavior when hostKind is omitted: all authorized governance hosts);
25
+ * - openclaw → the named host's governance rows (live target-turn capture)
26
+ * first, then the plugin's OWN user_turns/assistant_turns tables in the
27
+ * SAME workspace trajectory.db (audit B-2: verbatim turns the CLI reader
28
+ * could never see). Both surfaces sit behind the SAME openclaw consent
29
+ * decision; no other host's session can ever match.
30
+ */
7
31
  function readTurnRows(workspaceDir, kind, query) {
8
32
  const { sessionId, port } = query;
9
33
  if (sessionId.trim().length === 0)
10
34
  return [];
35
+ if (query.hostKind !== undefined) {
36
+ if (!port.isHostSourceMaterialAuthorized(query.hostKind).authorized) {
37
+ // Consent-blocked host: zero rows, and the caller's rc-9 note covers
38
+ // the degradation — consent text must never enter the window.
39
+ return [];
40
+ }
41
+ const governanceRows = readGovernanceRows({ workspaceDir, kind, sessionId, hostFilter: { hostKind: query.hostKind } });
42
+ if (query.hostKind !== 'openclaw' || governanceRows.length > 0)
43
+ return governanceRows;
44
+ const pluginResult = listPluginTurnTexts({ workspaceDir, kind, sessionId, limit: MAX_TURNS_PER_SESSION });
45
+ if (pluginResult.ok)
46
+ return pluginResult.turns.map(pluginRowToGovernanceRow);
47
+ // Plugin store unreadable: surface the failure shape through the same
48
+ // empty-row channel the assembler annotates — a query failure is never
49
+ // fabricated into a successful empty window at THIS layer either, so
50
+ // callers that need the distinction can consult the store directly.
51
+ return [];
52
+ }
11
53
  const authorizedHostKinds = GOVERNANCE_TURN_HOSTS.filter((host) => port.isHostSourceMaterialAuthorized(host).authorized);
12
- const result = listGovernanceTurnTexts({
13
- workspaceDir,
14
- kind,
15
- sessionId,
16
- authorizedHostKinds,
17
- limit: MAX_TURNS_PER_SESSION,
18
- });
19
- // Unreadable store: the empty result surfaces as an assembler ambiguity
20
- // note ("no turns found"), never as a fabricated window.
21
- return result.ok ? result.turns : [];
54
+ return readGovernanceRows({ workspaceDir, kind, sessionId, hostFilter: { authorizedHostKinds } });
22
55
  }
23
56
  /**
24
57
  * Build the governance-observation-backed turn reader for a workspace. The
@@ -31,8 +64,8 @@ function readTurnRows(workspaceDir, kind, query) {
31
64
  export function createGovernanceTrajectoryTurnReader(args) {
32
65
  const port = args.sourceMaterialAuthorization ?? denyAllSourceMaterialAuthorization;
33
66
  return {
34
- listUserTurnsForSession(sessionId) {
35
- return readTurnRows(args.workspaceDir, 'user_turn', { sessionId, port }).map((row, index) => ({
67
+ listUserTurnsForSession(sessionId, hostKind) {
68
+ return readTurnRows(args.workspaceDir, 'user_turn', { sessionId, port, ...(hostKind !== undefined ? { hostKind } : {}) }).map((row, index) => ({
36
69
  id: row.id,
37
70
  turnIndex: row.sourceOrdinal >= 0 ? row.sourceOrdinal : index,
38
71
  rawExcerpt: row.visibleText,
@@ -41,8 +74,8 @@ export function createGovernanceTrajectoryTurnReader(args) {
41
74
  createdAt: row.observedAt,
42
75
  }));
43
76
  },
44
- listAssistantTurns(sessionId) {
45
- return readTurnRows(args.workspaceDir, 'assistant_turn', { sessionId, port }).map((row) => ({
77
+ listAssistantTurns(sessionId, hostKind) {
78
+ return readTurnRows(args.workspaceDir, 'assistant_turn', { sessionId, port, ...(hostKind !== undefined ? { hostKind } : {}) }).map((row) => ({
46
79
  id: row.id,
47
80
  sessionId,
48
81
  runId: '',
@@ -66,12 +99,17 @@ export function createGovernanceTrajectoryTurnReader(args) {
66
99
  return { userTurns: [], assistantTurns: [] };
67
100
  }
68
101
  // Exact-turn reads are a separate entry point from the session-level
69
- // list methods above. Require an explicit supported host and consult
102
+ // reads above. Require an explicit supported host and consult
70
103
  // the latest consent decision on EVERY call before opening the store.
71
104
  // An omitted/unsupported host must never become an unscoped read.
72
- const authorizedHostKind = GOVERNANCE_TURN_HOSTS.find((candidate) => candidate === hostKind);
73
- if (authorizedHostKind === undefined
74
- || !port.isHostSourceMaterialAuthorized(authorizedHostKind).authorized) {
105
+ // PRI-1319: openclaw joins the supported set — its consent decision is
106
+ // consulted the same way, and its turns may live in governance
107
+ // observations (live capture) OR the plugin's own tables.
108
+ const supportedHost = hostKind !== undefined
109
+ && (hostKind === 'openclaw' || GOVERNANCE_TURN_HOSTS.includes(hostKind))
110
+ ? hostKind
111
+ : undefined;
112
+ if (supportedHost === undefined || !port.isHostSourceMaterialAuthorized(supportedHost).authorized) {
75
113
  return { userTurns: [], assistantTurns: [] };
76
114
  }
77
115
  // PRI-1273 (devin BUG_0002): the shared exact-turn selection rule —
@@ -81,13 +119,41 @@ export function createGovernanceTrajectoryTurnReader(args) {
81
119
  // old generic `ORDER BY id LIMIT 64` window cut it).
82
120
  const result = listGovernanceConversationTextsForHostTurn({
83
121
  workspaceDir: args.workspaceDir,
84
- hostKind: authorizedHostKind,
122
+ hostKind: supportedHost,
85
123
  rolloutIdentity: sessionId,
86
124
  hostTurnId,
87
125
  limit: 32,
88
126
  });
89
127
  if (!result.ok)
90
128
  return { userTurns: [], assistantTurns: [] };
129
+ // PRI-1319: an openclaw target turn the live capture did not mirror
130
+ // into governance observations may still exist as the plugin's own
131
+ // user_turns row (the capture's fallback identity is literally
132
+ // `user-turn-row:<rowid>`). Read THAT exact row — never a nearby one.
133
+ const emptyResult = result.rows.length === 0;
134
+ if (emptyResult && supportedHost === 'openclaw' && hostTurnId.startsWith('user-turn-row:')) {
135
+ const rowIdText = hostTurnId.slice('user-turn-row:'.length).trim();
136
+ const rowId = Number.parseInt(rowIdText, 10);
137
+ if (Number.isInteger(rowId) && rowId > 0) {
138
+ const pluginResult = listPluginTurnTexts({ workspaceDir: args.workspaceDir, kind: 'user_turn', sessionId, limit: MAX_TURNS_PER_SESSION });
139
+ if (pluginResult.ok) {
140
+ const matched = pluginResult.turns.find((turn) => turn.id === rowId);
141
+ if (matched !== undefined) {
142
+ return {
143
+ userTurns: [{
144
+ id: matched.id,
145
+ turnIndex: matched.id,
146
+ rawExcerpt: matched.text,
147
+ correctionDetected: matched.correctionDetected,
148
+ correctionCue: null,
149
+ createdAt: matched.observedAt,
150
+ }],
151
+ assistantTurns: [],
152
+ };
153
+ }
154
+ }
155
+ }
156
+ }
91
157
  return {
92
158
  userTurns: result.rows.flatMap((row, index) => row.kind === 'user_turn' ? [{
93
159
  id: row.id,
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export * from './rule-implementation-runtime.js';
20
20
  export * from './production-pain-evidence.js';
21
21
  export * from './governance-observation-store.js';
22
22
  export * from './governance-trajectory-turn-reader.js';
23
+ export * from './plugin-trajectory-turn-store.js';
23
24
  export * from './trajectory-retention.js';
24
25
  export * from './conversation-ingestion/index.js';
25
26
  export * from './source-material-authorization.js';
@@ -32,8 +33,10 @@ export * from './adaptive-background-append.js';
32
33
  export * from './signal-stage2-cycle.js';
33
34
  export * from './host-liveness-contract.js';
34
35
  export * from './internalization-consumer-governance.js';
35
- export { INTERNALIZATION_AUTO_CONSUMER_FLAG_ID, orderKindsByOldestReadyStage, oldestReadyAgeMs, executeSelectedInternalizationTask, runInternalizationConsumerCycle, } from './internalization-consumer-cycle.js';
36
- export type { ConsumerCycleLogger, ConsumerHostToolCatalog, InternalizationConsumerCyclePorts, InternalizationConsumerCycleOutcome, InternalizationConsumerCycleSignals, ExecuteSelectedInternalizationTaskInput, SelectedInternalizationTaskRunResult, SelectedInternalizationTaskRunnerOptions, } from './internalization-consumer-cycle.js';
36
+ export { INTERNALIZATION_AUTO_CONSUMER_FLAG_ID, orderKindsByOldestReadyStage, oldestReadyAgeMs, runInternalizationConsumerCycle, } from './internalization-consumer-cycle.js';
37
+ export type { ConsumerCycleLogger, ConsumerHostToolCatalog, InternalizationConsumerCyclePorts, InternalizationConsumerCycleOutcome, InternalizationConsumerCycleSignals, } from './internalization-consumer-cycle.js';
38
+ export { executeSelectedInternalizationTask, } from './internalization-task-executor.js';
39
+ export type { ExecuteSelectedInternalizationTaskInput, SelectedInternalizationTaskRunResult, SelectedInternalizationTaskRunnerOptions, } from './internalization-task-executor.js';
37
40
  export * from './adaptive-consumer-schedule.js';
38
41
  export * from './diagnostician-auto-run.js';
39
42
  export * from './workspace-pipeline-host-deps.js';
@@ -91,6 +94,22 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
91
94
  hostKind?: GovernanceHostKind;
92
95
  /** Host project cwd, distinct from the workspace owning shared PD state. */
93
96
  projectDir?: string;
97
+ /**
98
+ * PD Phase 1.5 (SPEC R10): adapter-known environment facts captured ONCE
99
+ * per session into trajectory.db::environment_snapshots. Only these
100
+ * allow-listed fields exist — an adapter that does not know a fact omits
101
+ * it and the row records NULL (unknown), never a guess and never a
102
+ * secret-bearing value.
103
+ */
104
+ afterToolCallEnvironment?: {
105
+ hostVersion?: string | null;
106
+ runtimeVersion?: string | null;
107
+ agentConfigDigest?: string | null;
108
+ modelConfigDigest?: string | null;
109
+ repoCommit?: string | null;
110
+ workspaceStateDigest?: string | null;
111
+ featureFlagsDigest?: string | null;
112
+ };
94
113
  /** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
95
114
  toolSemantics?: ToolSemanticRegistry;
96
115
  /**
package/dist/index.js CHANGED
@@ -35,6 +35,10 @@ export * from './governance-observation-store.js';
35
35
  // PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
36
36
  // pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
37
37
  export * from './governance-trajectory-turn-reader.js';
38
+ // PRI-1319: read-only access to the OpenClaw plugin's own user_turns/
39
+ // assistant_turns tables (same canonical workspace trajectory.db) — closes
40
+ // the audit's B-2 read gap for CLI/worker diagnosis paths.
41
+ export * from './plugin-trajectory-turn-store.js';
38
42
  // SPEC-PD-TR-001: trajectory retention I/O boundary (lock + marker + export
39
43
  // list + explicit VACUUM). The policy/batch engine is pure and lives in
40
44
  // `@principles/core/runtime`.
@@ -62,7 +66,7 @@ export * from './adaptive-background-append.js';
62
66
  export * from './signal-stage2-cycle.js';
63
67
  export * from './host-liveness-contract.js';
64
68
  // PRI-624 Slice C: shared internalization consumer execution (OpenClaw
65
- // auto-consumer + Companion workspace worker call the same cycle).
69
+ // auto-consumer + Service-Host-spawned workspace workers call the same cycle).
66
70
  export * from './internalization-consumer-governance.js';
67
71
  // PRI-1293 R3 (export surface tightening): explicit whitelist instead of
68
72
  // `export *` — the public API is the consumer cycle entry, the selected-task
@@ -74,7 +78,11 @@ export * from './internalization-consumer-governance.js';
74
78
  // of the input union, and callers construct them structurally.
75
79
  // SelectedInternalizationTaskRunnerOptions IS public — pd-cli run-once
76
80
  // constructs it directly (verified cross-package consumer).
77
- export { INTERNALIZATION_AUTO_CONSUMER_FLAG_ID, orderKindsByOldestReadyStage, oldestReadyAgeMs, executeSelectedInternalizationTask, runInternalizationConsumerCycle, } from './internalization-consumer-cycle.js';
81
+ // PRI-1301: the executor entries re-export from the executor module
82
+ // (pure move — identical symbol names/types; the cycle entries stay
83
+ // sourced from the consumer cycle module).
84
+ export { INTERNALIZATION_AUTO_CONSUMER_FLAG_ID, orderKindsByOldestReadyStage, oldestReadyAgeMs, runInternalizationConsumerCycle, } from './internalization-consumer-cycle.js';
85
+ export { executeSelectedInternalizationTask, } from './internalization-task-executor.js';
78
86
  // SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4: pure adaptive schedule
79
87
  // policy for the existing consumer timer chain (no new background service).
80
88
  export * from './adaptive-consumer-schedule.js';
@@ -247,6 +255,7 @@ export function createProductionHostRuntime(options = {}) {
247
255
  ...(options.ruleImplementationRuntime ? { implementationRuntime: options.ruleImplementationRuntime } : {}),
248
256
  ...(options.toolSemantics ? { toolSemantics: options.toolSemantics } : {}),
249
257
  });
258
+ const { afterToolCallEnvironment } = options;
250
259
  return createHostRuntime({
251
260
  afterToolCall: options.afterToolCall ?? createProductionPainEvidenceHandler({
252
261
  ...(options.painEnrichmentProvider ? { painEnrichmentProvider: options.painEnrichmentProvider } : {}),
@@ -254,6 +263,9 @@ export function createProductionHostRuntime(options = {}) {
254
263
  ...(options.hostKind ? { hostKind: options.hostKind } : {}),
255
264
  ...(options.projectDir ? { projectDir: options.projectDir } : {}),
256
265
  ...(options.events ? { events: options.events } : {}),
266
+ // PD Phase 1.5 (SPEC R10): adapter-supplied environment facts for the
267
+ // forward evidence capture; fields the adapter omits stay NULL.
268
+ ...(afterToolCallEnvironment ? { environmentProvider: () => afterToolCallEnvironment } : {}),
257
269
  }),
258
270
  beforeToolCall: options.beforeToolCall ?? productionGate,
259
271
  async beforePromptBuild(event) {
@@ -3,9 +3,10 @@
3
3
  *
4
4
  * Extracted verbatim from openclaw-plugin's
5
5
  * `internalization-auto-consumer-service.ts` `runConsumerCycle` so that the
6
- * OpenClaw auto-consumer scheduler and the Companion workspace worker call
6
+ * OpenClaw auto-consumer scheduler and the Service-Host-spawned workspace
7
+ * workers call
7
8
  * ONE downstream execution implementation (SPEC §13: "reusing existing
8
- * downstream consumer logic" — the Companion must not copy it):
9
+ * downstream consumer logic" — no host worker may copy it):
9
10
  *
10
11
  * flag gate → config/runtime config → state handle → orchestrator(dryRun)
11
12
  * → queue read model → consumer decision → wakeOnce loop → adapter
@@ -14,13 +15,14 @@
14
15
  *
15
16
  * The lease is acquired INSIDE runner.run by the Runtime lease manager
16
17
  * (persisted in `<workspace>/.pd/state.db`, cross-process safe) — this cycle
17
- * never leases by itself, so two schedulers (OpenClaw + Companion) racing on
18
+ * never leases by itself, so two schedulers (OpenClaw + Service Host worker)
19
+ * racing on
18
20
  * one workspace converge to exactly-once execution via lease_conflict.
19
21
  *
20
22
  * Hosts inject: a logger, a structured-event sink, their tool catalog, and an
21
23
  * env getter. Everything else is the existing production path.
22
24
  */
23
- import { type PDRuntimeAdapter, type RuntimeStateManager, type ToolSemanticRegistry, type BehaviorEvidencePort, type ArtificerTrustedFactsPort, type TelemetryEvent, type PIArtifactStore, type EffectivePdConfig, type OutputLanguage, type RefinerRuleHostGateDeps, type RolloutAutoDispatchInput, type RolloutAutoDispatchOutcome, type RolloutRevisionRoutingInput, type SeedArtificerRepairParams, type BehaviorExamplePack, type ArtificerHostSemanticContext, type DreamerRunnerResult, type PhilosopherRunnerResult, type ScribeRunnerResult, type ArtificerRunnerResult, type EvaluatorRunnerResult, type RolloutReviewerRunnerResult } from '@principles/core/runtime';
25
+ import { type ToolSemanticRegistry, type BehaviorEvidencePort, type ArtificerTrustedFactsPort } from '@principles/core/runtime';
24
26
  import { type ConsumerGovernanceLogger } from './internalization-consumer-governance.js';
25
27
  export declare const INTERNALIZATION_AUTO_CONSUMER_FLAG_ID = "internalization_auto_consumer";
26
28
  /** Structural logger port — OpenClaw PluginLogger and worker loggers satisfy this. */
@@ -34,7 +36,13 @@ export interface ConsumerHostToolCatalog {
34
36
  readonly writeTools: readonly string[];
35
37
  }
36
38
  export interface InternalizationConsumerCyclePorts {
37
- /** Runner-owner label recorded on leases ('auto-consumer' | 'companion-worker' | …). */
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.
45
+ */
38
46
  readonly owner: string;
39
47
  readonly logger: ConsumerCycleLogger;
40
48
  /** Structured event sink (OpenClaw: SystemLogger.log; worker: its own log). */
@@ -133,107 +141,6 @@ export declare function orderKindsByOldestReadyStage<T extends string>(runnerKin
133
141
  export declare function oldestReadyAgeMs(readyTasks: readonly {
134
142
  createdAt?: string;
135
143
  }[], nowMs: number): number | null;
136
- /**
137
- * Runner 遥测窄端口 — 与 core `PeerRunnerTelemetryEmitter` 结构等价
138
- * (该类型不在 core 冻结 barrel 上,此处按结构声明,零新增导出)。
139
- * StoreEventEmitter 与 WorkspaceTelemetryEmitter 均满足。
140
- */
141
- export interface SelectedTaskTelemetryEmitter {
142
- readonly emitTelemetry: (event: TelemetryEvent) => unknown;
143
- }
144
- /** 全部 kind 共享的调用方依赖。 */
145
- export interface SelectedInternalizationTaskBaseDeps {
146
- /** 要执行的已**选中**任务 — 执行租约由 Runner 在 run() 内自行获取, 调用方不在本层租约。 */
147
- readonly taskId: string;
148
- readonly stateManager: RuntimeStateManager;
149
- /** 入口自建的 runtime adapter (含 L2 / test-double 路由决策)。 */
150
- readonly runtimeAdapter: PDRuntimeAdapter;
151
- /** 入口选择的遥测口 (consumer evaluator 用 workspace-scoped emitter)。 */
152
- readonly eventEmitter: SelectedTaskTelemetryEmitter;
153
- readonly artifactStore: PIArtifactStore;
154
- /** Workspace 根 — ledgerIdentity 装配的唯一事实来源。 */
155
- readonly workspaceDir: string;
156
- }
157
- /** Runner 构造/执行选项 — 原样转发 (各入口既有语义保持)。 */
158
- export interface SelectedInternalizationTaskRunnerOptions {
159
- readonly owner: string;
160
- readonly runtimeKind: string;
161
- readonly timeoutMs: number;
162
- readonly effectiveConfig?: EffectivePdConfig;
163
- readonly outputLanguage?: OutputLanguage;
164
- readonly pollIntervalMs?: number;
165
- }
166
- /** Evaluator repair 轮的宿主接线 (来自既有 governance deps 工厂,不造第三套)。 */
167
- export interface SelectedEvaluatorRepairDeps {
168
- readonly isRepairLoopEnabled: () => boolean;
169
- readonly seedArtificerRepairTask: (params: SeedArtificerRepairParams) => Promise<string>;
170
- }
171
- /** rollout 治理接线 (来自 createRolloutGovernanceDeps)。 */
172
- export interface SelectedRolloutGovernanceDeps {
173
- readonly dispatchActivation: (input: RolloutAutoDispatchInput) => Promise<RolloutAutoDispatchOutcome>;
174
- readonly reopenRevisionTarget: (input: RolloutRevisionRoutingInput) => Promise<{
175
- ok: boolean;
176
- reason: string;
177
- reopenedTaskId?: string;
178
- }>;
179
- }
180
- /**
181
- * 按 taskKind 收窄的判别联合输入 — 必需依赖在类型层面不可缺失;
182
- * optional 仅限两个入口现状真实可选的字段 (artificer 的 evidence pack /
183
- * trustedFacts / hostSemanticContext、evaluator 的宿主目录与语义投影)。
184
- */
185
- export type ExecuteSelectedInternalizationTaskInput = ({
186
- readonly taskKind: 'dreamer';
187
- } & SelectedInternalizationTaskBaseDeps & {
188
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
189
- }) | ({
190
- readonly taskKind: 'philosopher';
191
- } & SelectedInternalizationTaskBaseDeps & {
192
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
193
- }) | ({
194
- readonly taskKind: 'scribe';
195
- } & SelectedInternalizationTaskBaseDeps & {
196
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
197
- }) | ({
198
- readonly taskKind: 'artificer';
199
- /** 仅 preflight 通过的入口传入 (consumer evidence ready);run-once 无此能力则缺省。 */
200
- readonly behaviorExamplePack?: BehaviorExamplePack;
201
- /** 仅 consumer 传入 — 与 intent preflight 同源的 trusted-facts 端口。 */
202
- readonly trustedFacts?: ArtificerTrustedFactsPort;
203
- readonly hostSemanticContext?: ArtificerHostSemanticContext;
204
- } & SelectedInternalizationTaskBaseDeps & {
205
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
206
- }) | ({
207
- readonly taskKind: 'evaluator';
208
- /** repair 轮宿主接线 — 缺失即是装配错误,不允许缺省掩盖。 */
209
- readonly repairDeps: SelectedEvaluatorRepairDeps;
210
- /** 对抗重放 gate — 两个入口都必须显式提供各自权威解析结果。 */
211
- readonly gateDeps: RefinerRuleHostGateDeps;
212
- readonly hostToolCatalog?: ConsumerHostToolCatalog;
213
- readonly hostSemanticContext?: ArtificerHostSemanticContext;
214
- } & SelectedInternalizationTaskBaseDeps & {
215
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
216
- }) | ({
217
- readonly taskKind: 'rollout_reviewer';
218
- readonly governanceDeps: SelectedRolloutGovernanceDeps;
219
- } & SelectedInternalizationTaskBaseDeps & {
220
- readonly runnerOptions: SelectedInternalizationTaskRunnerOptions;
221
- });
222
- export type SelectedInternalizationTaskRunResult = DreamerRunnerResult | PhilosopherRunnerResult | ScribeRunnerResult | ArtificerRunnerResult | EvaluatorRunnerResult | RolloutReviewerRunnerResult;
223
- /**
224
- * Execute ONE selected internalization task with the kind-selected runner.
225
- * Constructs the runner from the typed input and returns the raw run result.
226
- *
227
- * Lease ownership contract (CodeRabbit review fix): the caller is responsible
228
- * for SELECTING the task (e.g. a dry-run `wakeOnce` `would_lease` candidate);
229
- * the runner itself acquires the execution lease inside `run()` — callers must
230
- * NOT lease at this layer. The doc previously demanded an already-leased task,
231
- * which would lead new callers to acquire the lease at the wrong layer.
232
- *
233
- * Runner crashes propagate to the caller (each entry keeps its own crash
234
- * semantics: consumer rethrows without state writes; run-once logs + rethrows).
235
- */
236
- export declare function executeSelectedInternalizationTask(input: ExecuteSelectedInternalizationTaskInput): Promise<SelectedInternalizationTaskRunResult>;
237
144
  /**
238
145
  * Run ONE bounded consumer cycle for a workspace. At most one downstream task
239
146
  * is leased and executed per cycle (DEFAULT_CONSUMER_MAX_TASKS_PER_CYCLE=1);