@principles/host-runtime 4.0.0 → 4.1.1

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.
@@ -66,6 +66,7 @@ export async function readPromptActivationCandidates(input) {
66
66
  artifact_kind: artifact.artifactKind,
67
67
  content_json: artifact.contentJson,
68
68
  validation_status: artifact.validationStatus,
69
+ source_principle_id: artifact.sourcePrincipleId,
69
70
  }, activation);
70
71
  if (!resolved.ok) {
71
72
  warnings.push(resolved.warning);
@@ -8,19 +8,30 @@
8
8
  * The difference from the lab experiment is the QUESTION SET: the lab asked
9
9
  * four task-level questions, while production asks one independent
10
10
  * applicability condition per candidate plus one "insufficient context"
11
- * condition. Each answer is an independent `noul` score in [0, 1] — not a
12
- * distribution — so PD adjudicates locally instead of trusting the model to
13
- * emit a decision.
11
+ * condition. A candidate that would replace an activation answers TWO
12
+ * independent conditions instead (incoming value, outgoing safety), because a
13
+ * single blended score cannot tell "this principle does not fit" apart from
14
+ * "dropping the other principle is unsafe". Each answer is an independent
15
+ * `noul` score in [0, 1] — not a distribution — so PD adjudicates locally
16
+ * instead of trusting the model to emit a decision.
14
17
  *
15
18
  * Everything here is pure: no I/O, no clock, no transport. The caller owns
16
19
  * scheduling, cancellation and diagnostics.
17
20
  */
18
21
  export declare const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
19
22
  export declare const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = "insufficient_context";
20
- /** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
23
+ /**
24
+ * Preset applicability and context guards. Scores are model judgments, not
25
+ * calibrated probabilities.
26
+ *
27
+ * v3: a replaceable candidate is scored by TWO independent conditions
28
+ * (incoming value, outgoing safety). The append path keeps the single
29
+ * condition of v2 unchanged, which is why the version bump is required to
30
+ * tell the two evidence generations apart.
31
+ */
21
32
  export declare const ADAPTIVE_DECISION_CRITERIA: {
22
- readonly version: 'v2-20261112';
23
- /** A candidate must reach this independent score to be eligible. */
33
+ readonly version: 'v3-20261112';
34
+ /** A candidate (and, when it replaces something, its safety condition) must reach this score. */
24
35
  readonly selectThreshold: 0.7;
25
36
  /** Above this "information is insufficient" score, PD refuses to select. */
26
37
  readonly insufficientThreshold: 0.6;
@@ -67,10 +78,19 @@ export type BuildDecisionRequestResult = {
67
78
  readonly reason: DecisionProtocolError;
68
79
  };
69
80
  export declare function candidateQuestionId(ref: string): string;
81
+ /** Replaceable candidates answer the incoming-value question under this id. */
82
+ export declare function candidateValueQuestionId(ref: string): string;
83
+ /** Replaceable candidates answer the outgoing-safety question under this id. */
84
+ export declare function candidateSafetyQuestionId(ref: string): string;
70
85
  /**
71
86
  * One question per candidate (its applicability condition) plus one
72
87
  * "insufficient context" question. Instructions refer to the snapshot by ref;
73
88
  * the candidate text itself travels once, in `state`.
89
+ *
90
+ * A candidate that would REPLACE an activation answers two independent
91
+ * conditions instead of one: whether the incoming principle helps the user's
92
+ * next required step, and whether this turn can afford to drop the outgoing
93
+ * principle. Both must clear the same threshold. The append path is untouched.
74
94
  */
75
95
  export declare function buildDecisionQuestions(candidates: readonly {
76
96
  readonly ref: string;
@@ -116,14 +136,22 @@ export type DecisionOutcome = {
116
136
  } | {
117
137
  readonly status: 'none_applicable' | 'uncertain';
118
138
  readonly ref: null;
119
- readonly reason: 'below_selection_threshold' | 'candidate_tied' | 'information_insufficient';
139
+ readonly reason: 'below_selection_threshold'
140
+ /** The incoming candidate fits, but dropping the listed outgoing principle was not shown safe this turn. */
141
+ | 'replacement_unsafe' | 'candidate_tied' | 'information_insufficient';
120
142
  readonly scores: Readonly<Record<string, number>>;
121
143
  };
122
144
  /**
123
145
  * Local adjudication of the INDEPENDENT condition scores. Order matters:
124
146
  * insufficient information first (it invalidates any candidate ranking), then
125
- * the applicability threshold. An exact tie leaves no unique winner.
147
+ * eligibility, then the applicability ranking.
148
+ *
149
+ * A candidate that replaces something is eligible only when BOTH its value and
150
+ * its safety condition clear the threshold. PD never lets a high incoming
151
+ * score override an unsafe removal, and `replacement_unsafe` keeps that
152
+ * failure distinguishable from "the candidate itself did not fit".
126
153
  */
127
154
  export declare function adjudicateDecision(scores: Readonly<Record<string, number>>, candidates: readonly {
128
155
  readonly ref: string;
156
+ readonly replaces?: string;
129
157
  }[], criteria?: typeof ADAPTIVE_DECISION_CRITERIA): DecisionOutcome;
@@ -8,19 +8,30 @@
8
8
  * The difference from the lab experiment is the QUESTION SET: the lab asked
9
9
  * four task-level questions, while production asks one independent
10
10
  * applicability condition per candidate plus one "insufficient context"
11
- * condition. Each answer is an independent `noul` score in [0, 1] — not a
12
- * distribution — so PD adjudicates locally instead of trusting the model to
13
- * emit a decision.
11
+ * condition. A candidate that would replace an activation answers TWO
12
+ * independent conditions instead (incoming value, outgoing safety), because a
13
+ * single blended score cannot tell "this principle does not fit" apart from
14
+ * "dropping the other principle is unsafe". Each answer is an independent
15
+ * `noul` score in [0, 1] — not a distribution — so PD adjudicates locally
16
+ * instead of trusting the model to emit a decision.
14
17
  *
15
18
  * Everything here is pure: no I/O, no clock, no transport. The caller owns
16
19
  * scheduling, cancellation and diagnostics.
17
20
  */
18
21
  export const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
19
22
  export const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = 'insufficient_context';
20
- /** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
23
+ /**
24
+ * Preset applicability and context guards. Scores are model judgments, not
25
+ * calibrated probabilities.
26
+ *
27
+ * v3: a replaceable candidate is scored by TWO independent conditions
28
+ * (incoming value, outgoing safety). The append path keeps the single
29
+ * condition of v2 unchanged, which is why the version bump is required to
30
+ * tell the two evidence generations apart.
31
+ */
21
32
  export const ADAPTIVE_DECISION_CRITERIA = {
22
- version: 'v2-20261112',
23
- /** A candidate must reach this independent score to be eligible. */
33
+ version: 'v3-20261112',
34
+ /** A candidate (and, when it replaces something, its safety condition) must reach this score. */
24
35
  selectThreshold: 0.7,
25
36
  /** Above this "information is insufficient" score, PD refuses to select. */
26
37
  insufficientThreshold: 0.6,
@@ -28,19 +39,46 @@ export const ADAPTIVE_DECISION_CRITERIA = {
28
39
  export function candidateQuestionId(ref) {
29
40
  return `candidate_${ref}`;
30
41
  }
42
+ /** Replaceable candidates answer the incoming-value question under this id. */
43
+ export function candidateValueQuestionId(ref) {
44
+ return `candidate_${ref}_value`;
45
+ }
46
+ /** Replaceable candidates answer the outgoing-safety question under this id. */
47
+ export function candidateSafetyQuestionId(ref) {
48
+ return `candidate_${ref}_safety`;
49
+ }
31
50
  /**
32
51
  * One question per candidate (its applicability condition) plus one
33
52
  * "insufficient context" question. Instructions refer to the snapshot by ref;
34
53
  * the candidate text itself travels once, in `state`.
54
+ *
55
+ * A candidate that would REPLACE an activation answers two independent
56
+ * conditions instead of one: whether the incoming principle helps the user's
57
+ * next required step, and whether this turn can afford to drop the outgoing
58
+ * principle. Both must clear the same threshold. The append path is untouched.
35
59
  */
36
60
  export function buildDecisionQuestions(candidates) {
37
61
  const questions = {};
38
62
  for (const candidate of candidates) {
39
- questions[candidateQuestionId(candidate.ref)] = {
63
+ if (candidate.replaces === undefined) {
64
+ questions[candidateQuestionId(candidate.ref)] = {
65
+ type: 'noul',
66
+ instructions: `依据 currentInstruction 判断用户现在要做什么,并比较 state.candidates。候选 ${candidate.ref} 是否直接适用于这项任务,且最能改善下一步具体行动?`
67
+ + '能避免当前任务的具体失误或补上关键步骤时给高分。仅主题相近、重复用户已明确的要求、或对下一步没有实质帮助时给低分。没有合适候选时全部给低分。',
68
+ };
69
+ continue;
70
+ }
71
+ questions[candidateValueQuestionId(candidate.ref)] = {
40
72
  type: 'noul',
41
- instructions: `依据 currentInstruction 判断用户现在要做什么,并比较 state.candidates。候选 ${candidate.ref} 是否直接适用于这项任务,且最能改善下一步具体行动?`
42
- + '能避免当前任务的具体失误或补上关键步骤时给高分。仅主题相近、重复用户已明确的要求、或对下一步没有实质帮助时给低分。没有合适候选时全部给低分。'
43
- + (candidate.replaces === undefined ? '' : ' 此方案会移除该候选在 state 中的 replaces 原则。只有候选对当前任务明显更有帮助,且移除原原则不会丢掉当前仍需的约束时才给高分;拿不准则给低分。'),
73
+ instructions: `依据 currentInstruction 判断用户现在要求完成的下一步,并比较 state.candidates。候选 ${candidate.ref} 是否直接帮助完成这一步?`
74
+ + '为完成这一步所需的核对、验证和证据整理也算直接帮助,即使用户没有逐字说出这些动作。'
75
+ + '仅主题相近、重复用户已明确的要求、或对下一步没有实质帮助时给低分。没有合适候选时全部给低分。',
76
+ };
77
+ questions[candidateSafetyQuestionId(candidate.ref)] = {
78
+ type: 'noul',
79
+ instructions: `只判断本轮:state.candidates 中候选 ${candidate.ref} 的 replaces 记录了启用它将让位的原原则。`
80
+ + '若启用该候选,本轮能否在保留任务所需约束的前提下省掉这条原原则?'
81
+ + '原原则对本轮仍可能有用、或无法确认可以省掉时给低分;确认本轮不需要它时才给高分。只判断当前轮,不考虑以后。',
44
82
  };
45
83
  }
46
84
  questions[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION] = {
@@ -152,24 +190,45 @@ export function validateDecisionResponse(value, expected) {
152
190
  /**
153
191
  * Local adjudication of the INDEPENDENT condition scores. Order matters:
154
192
  * insufficient information first (it invalidates any candidate ranking), then
155
- * the applicability threshold. An exact tie leaves no unique winner.
193
+ * eligibility, then the applicability ranking.
194
+ *
195
+ * A candidate that replaces something is eligible only when BOTH its value and
196
+ * its safety condition clear the threshold. PD never lets a high incoming
197
+ * score override an unsafe removal, and `replacement_unsafe` keeps that
198
+ * failure distinguishable from "the candidate itself did not fit".
156
199
  */
157
200
  export function adjudicateDecision(scores, candidates, criteria = ADAPTIVE_DECISION_CRITERIA) {
158
201
  const insufficient = scores[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION];
159
202
  if (insufficient !== undefined && insufficient >= criteria.insufficientThreshold) {
160
203
  return { status: 'uncertain', ref: null, reason: 'information_insufficient', scores };
161
204
  }
162
- const ranked = candidates
163
- .map((candidate) => ({
164
- ref: candidate.ref,
165
- score: scores[candidateQuestionId(candidate.ref)] ?? 0,
166
- }))
167
- .sort((left, right) => right.score - left.score);
205
+ const evaluated = candidates.map((candidate) => {
206
+ const replaceable = candidate.replaces !== undefined;
207
+ const value = scores[replaceable
208
+ ? candidateValueQuestionId(candidate.ref)
209
+ : candidateQuestionId(candidate.ref)] ?? 0;
210
+ const safety = replaceable ? scores[candidateSafetyQuestionId(candidate.ref)] ?? 0 : null;
211
+ return {
212
+ ref: candidate.ref,
213
+ value,
214
+ eligible: value >= criteria.selectThreshold
215
+ && (safety === null || safety >= criteria.selectThreshold),
216
+ };
217
+ });
218
+ const ranked = evaluated
219
+ .filter((candidate) => candidate.eligible)
220
+ .sort((left, right) => right.value - left.value);
168
221
  const [top, runnerUp] = ranked;
169
- if (!top || top.score < criteria.selectThreshold) {
170
- return { status: 'none_applicable', ref: null, reason: 'below_selection_threshold', scores };
222
+ if (!top) {
223
+ const applicable = evaluated.some((candidate) => candidate.value >= criteria.selectThreshold);
224
+ return {
225
+ status: 'none_applicable',
226
+ ref: null,
227
+ reason: applicable ? 'replacement_unsafe' : 'below_selection_threshold',
228
+ scores,
229
+ };
171
230
  }
172
- if (runnerUp && top.score === runnerUp.score) {
231
+ if (runnerUp && top.value === runnerUp.value) {
173
232
  return { status: 'uncertain', ref: null, reason: 'candidate_tied', scores };
174
233
  }
175
234
  return { status: 'selected', ref: top.ref, reason: 'selected', scores };
@@ -386,7 +386,12 @@ export async function runAdaptiveSelection(options) {
386
386
  return {
387
387
  status: 'none',
388
388
  target: null,
389
- reason: decision.status === 'uncertain' ? 'uncertain' : 'no_increment',
389
+ // Keep "the candidate fits but dropping the outgoing principle was not
390
+ // shown safe" separate from an ordinary no-gain abstention; the bounded
391
+ // diagnostics must be able to tell them apart (rc-9).
392
+ reason: decision.status === 'uncertain'
393
+ ? 'uncertain'
394
+ : decision.reason === 'replacement_unsafe' ? 'replacement_unsafe' : 'no_increment',
390
395
  sends,
391
396
  diagnostics,
392
397
  };
@@ -1,4 +1,40 @@
1
1
  import type { RecoveryCapabilityEvidence } from '@principles/core/runtime';
2
+ /**
3
+ * SPEC-RULECODE-HOST-PROMOTION-001 review round 4 (P1): per-capability
4
+ * CLI-channel reachability probes, shared by the pd-cli readiness path and
5
+ * the pd-console readiness assembly (both packages depend on host-runtime).
6
+ *
7
+ * Every probe executes the REAL pd CLI as a bounded subprocess against the
8
+ * TARGET workspace — static command lists, no shell, output capped, timeout
9
+ * enforced. Evidence is produced fresh on every call; nothing is cached and
10
+ * nothing destructive runs:
11
+ * - `pd_status`: `pd activation list --json` (read-only status surface);
12
+ * - `rulecode_deactivate`: `pd activation deactivate --activation-id
13
+ * recovery-probe-nonexistent --dry-run --json` — the REAL deactivate entry
14
+ * through real parsing, workspace binding, and target-resolution
15
+ * preconditions, with the dry-run guard returning BEFORE any governance
16
+ * audit write or store mutation. A nonexistent probe id keeps the
17
+ * precondition honest without touching any real activation.
18
+ *
19
+ * Console-channel capabilities (`rulecode_global_pause`,
20
+ * `owner_review_access`) can never be verified from a CLI subprocess — the
21
+ * caller receives explicit NOT-VERIFIED entries for them instead of
22
+ * fabricated ok flags (fail closed; SPEC R4 §2.4.7).
23
+ */
24
+ /**
25
+ * PRI-1202 — single budget authority.
26
+ *
27
+ * The CLI recovery probes run INSIDE one Owner Console HTTP request. The
28
+ * console wrapper (`asyncHandler`) answers 504 once its request budget
29
+ * expires, so two independent literals (probe 15s, request 10s) let a single
30
+ * probe outlive the request it belongs to. The console request budget is the
31
+ * authority; the probe budget is DERIVED from it and must stay strictly
32
+ * smaller, leaving fixed headroom for the console to serialize the response.
33
+ */
34
+ export declare const CONSOLE_REQUEST_BUDGET_MS = 10000;
35
+ /** Headroom reserved inside the console request budget for response assembly. */
36
+ export declare const CLI_RECOVERY_PROBE_HEADROOM_MS = 2000;
37
+ export declare const CLI_RECOVERY_PROBE_TIMEOUT_MS: number;
2
38
  export declare const DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID = "recovery-probe-nonexistent";
3
39
  /**
4
40
  * Resolve the built pd CLI entry for the CURRENT environment. Both layouts
@@ -14,7 +50,12 @@ export interface CliRecoveryProbeOptions {
14
50
  workspaceDir: string;
15
51
  /** When supplied, the status listing must include this activation (workspace-targeting proof). */
16
52
  expectedActivationId?: string;
17
- /** Probe budget in ms (default 15s). A timeout fails the capability closed — tests on loaded machines may raise it. */
53
+ /**
54
+ * Probe budget in ms (default `CLI_RECOVERY_PROBE_TIMEOUT_MS`, derived from
55
+ * the console request budget). A timeout fails the capability closed —
56
+ * tests on loaded machines may raise it, but the default must stay strictly
57
+ * inside one console request.
58
+ */
18
59
  timeoutMs?: number;
19
60
  }
20
61
  /** `pd activation list --json` — the pd_status status surface, read-only. */
@@ -24,7 +24,20 @@ import { fileURLToPath } from 'node:url';
24
24
  * caller receives explicit NOT-VERIFIED entries for them instead of
25
25
  * fabricated ok flags (fail closed; SPEC R4 §2.4.7).
26
26
  */
27
- const PROBE_TIMEOUT_MS = 15_000;
27
+ /**
28
+ * PRI-1202 — single budget authority.
29
+ *
30
+ * The CLI recovery probes run INSIDE one Owner Console HTTP request. The
31
+ * console wrapper (`asyncHandler`) answers 504 once its request budget
32
+ * expires, so two independent literals (probe 15s, request 10s) let a single
33
+ * probe outlive the request it belongs to. The console request budget is the
34
+ * authority; the probe budget is DERIVED from it and must stay strictly
35
+ * smaller, leaving fixed headroom for the console to serialize the response.
36
+ */
37
+ export const CONSOLE_REQUEST_BUDGET_MS = 10_000;
38
+ /** Headroom reserved inside the console request budget for response assembly. */
39
+ export const CLI_RECOVERY_PROBE_HEADROOM_MS = 2_000;
40
+ export const CLI_RECOVERY_PROBE_TIMEOUT_MS = CONSOLE_REQUEST_BUDGET_MS - CLI_RECOVERY_PROBE_HEADROOM_MS;
28
41
  const MAX_STDOUT_BYTES = 1024 * 1024;
29
42
  export const DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID = 'recovery-probe-nonexistent';
30
43
  /**
@@ -109,7 +122,7 @@ function capability(capabilityId, evidence) {
109
122
  const CONSOLE_UNVERIFIABLE_DETAIL = 'console-channel control: verifying the HTTP-only recovery entry requires the Owner Console process; a CLI subprocess cannot produce this evidence';
110
123
  /** `pd activation list --json` — the pd_status status surface, read-only. */
111
124
  export async function probeCliActivationStatus(options) {
112
- const run = await runCli(options.cliEntry, ['activation', 'list', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? PROBE_TIMEOUT_MS);
125
+ const run = await runCli(options.cliEntry, ['activation', 'list', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS);
113
126
  if (!run.ok)
114
127
  return capability('pd_status', { channel: 'cli', ok: false, workspaceMatched: false, detail: `pd activation list: ${run.detail}` });
115
128
  let parsed;
@@ -138,7 +151,7 @@ export async function probeCliActivationStatus(options) {
138
151
  * an honest not-found while the entry itself is proven executable.
139
152
  */
140
153
  export async function probeCliDeactivateDryRun(options) {
141
- const run = await runCli(options.cliEntry, ['activation', 'deactivate', '--activation-id', DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID, '--dry-run', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? PROBE_TIMEOUT_MS);
154
+ const run = await runCli(options.cliEntry, ['activation', 'deactivate', '--activation-id', DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID, '--dry-run', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS);
142
155
  if (!run.ok)
143
156
  return capability('rulecode_deactivate', { channel: 'cli', ok: false, workspaceMatched: false, detail: `pd activation deactivate --dry-run: ${run.detail}` });
144
157
  let parsed;
@@ -1,32 +1,3 @@
1
- /**
2
- * Conversation-ingestion pipeline — the single orchestration entry for
3
- * unified host trajectory ingestion (PRI-1171; SPEC v0.2 §4.1).
4
- *
5
- * Five segments, host-neutral:
6
- *
7
- * gate (flag short-circuit, ZERO port calls) → consent gate → locate →
8
- * bounded window read (TOCTOU-mapped) → host decode → host contract guard →
9
- * pre-ingest host side-writes → sanitize-at-store ingest with checkpoint →
10
- * stop-classified outcome.
11
- *
12
- * Ordering invariants carried over verbatim from the Codex path (behavior
13
- * lock, fixtures in codex-adapter/tests/ingestion/ingestion.test.ts):
14
- * - flag-off / consent-not-granted short-circuit BEFORE locate — the
15
- * transcript filesystem boundary receives zero calls (SPEC §10 hard
16
- * privacy invariant, proven by a port spy);
17
- * - a host contract guard refusal (e.g. unsupported host version) ingests
18
- * NOTHING and holds the checkpoint — the next trigger retries;
19
- * - pre-ingest side-write failure (e.g. verified tool outcomes) holds the
20
- * checkpoint so the delta retries instead of silently losing facts;
21
- * - a stable malformed record commits the records BEFORE it, holds the
22
- * checkpoint at it, and degrades loudly;
23
- * - an incomplete tail commits what precedes it, parks the checkpoint at
24
- * the tail start, and reports a warning (transient by design).
25
- *
26
- * The pipeline never learns host formats: the source adapter supplies locate
27
- * + decode + rollout lineage; `degradeTexts` carries host-CLI vocabulary
28
- * (quarantine commands etc.) so Operator-facing nextActions stay exact.
29
- */
30
1
  import { type GovernanceObservationInput } from '../governance-observation-store.js';
31
2
  import { type HookHints, type SessionRef, type TranscriptDelta, type TranscriptPort, type TranscriptSourceAdapter } from './source.js';
32
3
  import type { ConversationIngestionConsentDecision } from './consent.js';
@@ -27,6 +27,8 @@
27
27
  * + decode + rollout lineage; `degradeTexts` carries host-CLI vocabulary
28
28
  * (quarantine commands etc.) so Operator-facing nextActions stay exact.
29
29
  */
30
+ import * as nodePath from 'node:path';
31
+ import { appendEventLogLine } from '@principles/core/runtime';
30
32
  import { ingestGovernanceObservations, readGovernanceCheckpoint, } from '../governance-observation-store.js';
31
33
  import { CONVERSATION_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError, createNodeTranscriptPort, } from './source.js';
32
34
  import { TEXT_POLICY_BOUNDED_MAX_CHARS } from './text-policy.js';
@@ -38,7 +40,43 @@ export function runConversationIngestion(args) {
38
40
  oversizedNextAction: 'a single transcript record exceeds the bounded-read window; inspect the transcript file.',
39
41
  ...args.degradeTexts,
40
42
  };
41
- const degraded = (reason, nextAction, warnings) => ({ status: 'degraded', reason, nextAction, warnings });
43
+ const now = args.now ?? new Date();
44
+ const eventLogStateDir = nodePath.join(args.workspaceDir, '.state');
45
+ const boundedText = (value) => {
46
+ // Code-point bounded: a log line may be rendered by an Owner-facing
47
+ // surface, so never split a surrogate pair (EP-11).
48
+ const points = Array.from(value);
49
+ return points.length > 300 ? `${points.slice(0, 300).join('')}…` : value;
50
+ };
51
+ /**
52
+ * rc-9: every refused ingest leaves a durable fact in the existing
53
+ * `events_<date>.jsonl` channel. The hook's stderr is the only other
54
+ * surface, and it is per-process — "0 rows" was previously unattributable
55
+ * after the fact. Best-effort: a failed write must not break the hook, but
56
+ * it must stay observable on the returned warnings.
57
+ */
58
+ const degraded = (reason, nextAction, warnings) => {
59
+ const observableWarnings = [...warnings];
60
+ try {
61
+ appendEventLogLine(eventLogStateDir, {
62
+ ts: now.toISOString(),
63
+ type: 'conversation_ingestion',
64
+ category: 'degraded',
65
+ sessionId: args.session.sessionId,
66
+ data: {
67
+ hostKind: args.source.hostKind,
68
+ reason: boundedText(reason),
69
+ nextAction: boundedText(nextAction),
70
+ warningCount: warnings.length,
71
+ },
72
+ });
73
+ }
74
+ catch (error) {
75
+ const detail = boundedText(error instanceof Error ? error.message : String(error));
76
+ observableWarnings.push(`degradation_event_log_failed:${detail}`);
77
+ }
78
+ return { status: 'degraded', reason, nextAction, warnings: observableWarnings };
79
+ };
42
80
  // 1. Flag short-circuit — before locate, before ANY port call (SPEC §10).
43
81
  if (!args.flags.ingestionEnabled) {
44
82
  return degraded('ingestion_disabled', 'enable the conversation-ingestion flag for this host in the workspace .pd/config.yaml to ingest transcripts.', []);
@@ -47,7 +85,6 @@ export function runConversationIngestion(args) {
47
85
  if (args.consent.decision !== 'granted') {
48
86
  return degraded(`consent_not_granted:${args.consent.decision}`, 'record a granted consent decision for this host (setup flow or Owner directive) before transcript ingestion runs.', []);
49
87
  }
50
- const now = args.now ?? new Date();
51
88
  const port = args.port ?? createNodeTranscriptPort();
52
89
  // 3. Locate (deterministic, host rules).
53
90
  const locator = args.source.locate(args.session, args.hints, args.env ?? {});
@@ -85,6 +85,18 @@ export const HIGH_PRECISION_CORRECTION_OVERLAY = [
85
85
  export const AMBIGUOUS_CORRECTION_OVERLAY = [
86
86
  ['我说的是', 0.9],
87
87
  ['都说了', 0.8],
88
+ // 2026-11-13 真实宿主回归(P1-1):Owner「这种没有数据支撑的激进改动我不
89
+ // 接受。以后改配置参数前,先说明依据和影响,等我确认后再动手。」在零命中
90
+ // 预算下被漏检。以下只作候选(precision=ambiguous),必须经 Stage2 LLM 确认,
91
+ // 不得直达 STRONG;普通否定句仍可能被 LLM 判为 none。
92
+ ['不接受', 0.6],
93
+ ['我不同意', 0.6],
94
+ ['我没让你', 0.6],
95
+ ['没有让你', 0.6],
96
+ ['未经确认', 0.5],
97
+ ['先别执行', 0.6],
98
+ ['没有依据', 0.5],
99
+ ['这不是我要求的', 0.7],
88
100
  ];
89
101
  function isValidLearnedKeyword(v) {
90
102
  if (typeof v !== 'object' || v === null)
@@ -19,6 +19,8 @@ export interface PromptDeliverabilityCandidateArtifact {
19
19
  artifactKind: string;
20
20
  contentJson: string;
21
21
  validationStatus: string;
22
+ /** Formal ledger identity column; identity never comes from content titles. */
23
+ sourcePrincipleId?: string;
22
24
  }
23
25
  export type PromptArtifactDeliverability = {
24
26
  status: 'deliverable';
@@ -24,6 +24,7 @@ export function resolvePromptCandidatePrinciple(artifact) {
24
24
  artifact_kind: artifact.artifactKind,
25
25
  content_json: artifact.contentJson,
26
26
  validation_status: artifact.validationStatus,
27
+ source_principle_id: artifact.sourcePrincipleId,
27
28
  }, syntheticPendingActivation(artifact.artifactId));
28
29
  }
29
30
  function selfReportEnabledFor(workspaceDir) {
@@ -195,6 +196,7 @@ export async function loadPromptArtifactById(workspaceDir, artifactId) {
195
196
  artifactKind: record.artifactKind,
196
197
  contentJson: record.contentJson,
197
198
  validationStatus: record.validationStatus,
199
+ sourcePrincipleId: record.sourcePrincipleId,
198
200
  },
199
201
  };
200
202
  }
@@ -56,6 +56,7 @@ export async function readPromptActivationInjectionStatuses(input) {
56
56
  artifact_kind: artifact.artifactKind,
57
57
  content_json: artifact.contentJson,
58
58
  validation_status: artifact.validationStatus,
59
+ source_principle_id: artifact.sourcePrincipleId,
59
60
  }, activation);
60
61
  if (!resolved.ok) {
61
62
  rows.push({ activationId: activation.activationId, failure: resolved.warning });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.0.0",
3
+ "version": "4.1.1",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -31,8 +31,8 @@
31
31
  "lint": "eslint \"src/**/*.ts\""
32
32
  },
33
33
  "dependencies": {
34
- "@principles/core": "^7.5.0",
35
- "@principles/install-layout": "^0.8.0",
34
+ "@principles/core": "^7.6.1",
35
+ "@principles/install-layout": "^0.8.1",
36
36
  "better-sqlite3": "^13.0.3",
37
37
  "js-yaml": "^5.4.3"
38
38
  },
@@ -49,5 +49,5 @@
49
49
  "url": "git+https://github.com/csuzngjh/principles.git"
50
50
  },
51
51
  "license": "Apache-2.0",
52
- "gitHead": "95d49f9eae5bf499fc8e4f36fecb0ad5a490f05b"
52
+ "gitHead": "8582e5dde27a582c63f3ad6804675a84c0d0c11e"
53
53
  }