@principles/host-runtime 3.5.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/active-principle-prompt.d.ts +7 -2
- package/dist/active-principle-prompt.js +80 -13
- package/dist/adaptive-decision-protocol.d.ts +7 -20
- package/dist/adaptive-decision-protocol.js +10 -24
- package/dist/adaptive-priority-provider.d.ts +2 -1
- package/dist/adaptive-priority-provider.js +6 -5
- package/dist/adaptive-selection.d.ts +4 -0
- package/dist/adaptive-selection.js +6 -3
- package/dist/codex-disclosure.d.ts +12 -7
- package/dist/codex-disclosure.js +12 -7
- package/dist/conversation-ingestion/pipeline.d.ts +8 -0
- package/dist/conversation-ingestion/pipeline.js +6 -1
- package/dist/conversation-ingestion/text-policy.d.ts +3 -4
- package/dist/conversation-ingestion/text-policy.js +3 -4
- package/dist/governance-observation-store.d.ts +38 -5
- package/dist/governance-observation-store.js +63 -5
- package/dist/index.js +5 -2
- package/dist/production-rulehost-gate.d.ts +36 -1
- package/dist/production-rulehost-gate.js +91 -1
- package/package.json +3 -3
|
@@ -77,6 +77,7 @@ export interface AdaptivePackingReport {
|
|
|
77
77
|
displacedActivationIds: string[];
|
|
78
78
|
/** Internal return-boundary checks; these snapshots are not delivery evidence. */
|
|
79
79
|
targetSnapshot?: ActivatedPrinciple;
|
|
80
|
+
displacedSnapshot?: ActivatedPrinciple;
|
|
80
81
|
targetBody?: string;
|
|
81
82
|
nativeBaseline?: ActivePrinciplePromptResult;
|
|
82
83
|
deadlineAt?: number;
|
|
@@ -203,6 +204,10 @@ export declare function packSharedDirectives(input: {
|
|
|
203
204
|
/** Fair rotation continues past a non-fit; legacy FIFO stops at the first one. */
|
|
204
205
|
continueOnNonFit: boolean;
|
|
205
206
|
}): SharedDirectivePacking;
|
|
207
|
+
export interface AdaptiveGapOptions {
|
|
208
|
+
readonly excludedByBudget: boolean;
|
|
209
|
+
readonly replacementByActivationId: ReadonlyMap<string, ActivatedPrinciple>;
|
|
210
|
+
}
|
|
206
211
|
export declare function buildActivePrinciplePromptContext(input: {
|
|
207
212
|
workspaceDir: string;
|
|
208
213
|
/**
|
|
@@ -224,8 +229,8 @@ export declare function buildActivePrinciplePromptContext(input: {
|
|
|
224
229
|
artifactId: string;
|
|
225
230
|
activationId: string;
|
|
226
231
|
};
|
|
227
|
-
/** Select only from principles
|
|
228
|
-
selectNativeGap?: (candidates: readonly ActivatedPrinciple[]) => Promise<{
|
|
232
|
+
/** Select only from omitted principles with a feasible plan in the current budget. */
|
|
233
|
+
selectNativeGap?: (candidates: readonly ActivatedPrinciple[], options: AdaptiveGapOptions) => Promise<{
|
|
229
234
|
artifactId: string;
|
|
230
235
|
activationId: string;
|
|
231
236
|
signal?: AbortSignal;
|
|
@@ -7,6 +7,7 @@ import path from 'node:path';
|
|
|
7
7
|
import { escapeXml } from '@principles/core/prompt-builder';
|
|
8
8
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
9
9
|
import { readPromptActivationAuthority } from './prompt-activation-authority.js';
|
|
10
|
+
import { ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS } from './adaptive-decision-protocol.js';
|
|
10
11
|
import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
|
|
11
12
|
/** PRI-904 SPEC §10: bounded diagnostic id lists (mirrors the core selector's cap of 16). */
|
|
12
13
|
export const MAX_SHARED_DIAGNOSTIC_IDS = 16;
|
|
@@ -345,17 +346,51 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
345
346
|
};
|
|
346
347
|
const nativePacking = pack(nativeScanOrder);
|
|
347
348
|
const nativeResult = makeResult(nativePacking, principles);
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
349
|
+
let gapPriority;
|
|
350
|
+
const mandatoryIds = input.mandatoryPrincipleIds ?? [];
|
|
351
|
+
let feasible = [];
|
|
352
|
+
const replacements = new Map();
|
|
353
|
+
if (input.adaptivePriority === undefined && input.selectNativeGap && warnings.length === 0) {
|
|
354
|
+
const omitted = principles.filter((principle) => !nativeResult.principleIds.includes(principle.principleId));
|
|
355
|
+
const renderOptions = { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled };
|
|
356
|
+
const nativeChars = nativePacking.additionalContext.length || sharedDirectiveBaseChars(renderOptions);
|
|
357
|
+
const remaining = budgetChars - nativeChars;
|
|
358
|
+
const config = loadPdConfigForPlugin(input.workspaceDir);
|
|
359
|
+
const replaceableIds = new Set(config.ok ? config.effective.config.adaptiveActivation?.replaceableActivationIds : undefined);
|
|
360
|
+
// Prefer the last explicitly replaceable Native directive that can cover
|
|
361
|
+
// the shortfall. Each question scores one concrete plan, never a free-form removal.
|
|
362
|
+
const replaceable = nativePacking.included.slice().reverse()
|
|
363
|
+
.filter((p) => replaceableIds.has(p.activationId) && p.authority === 'owner'
|
|
364
|
+
&& p.artifactContentSha256 && Array.isArray(mandatoryIds) && !mandatoryIds.includes(p.principleId)
|
|
365
|
+
&& principles.filter((candidate) => candidate.principleId === p.principleId).length === 1)
|
|
366
|
+
.map((principle) => ({ principle, chars: measureSharedDirectiveBlockChars(principle, renderOptions) }));
|
|
367
|
+
feasible = omitted.filter((principle) => {
|
|
368
|
+
const shortfall = measureSharedDirectiveBlockChars(principle, renderOptions) - remaining;
|
|
369
|
+
if (shortfall <= 0)
|
|
370
|
+
return true;
|
|
371
|
+
// Compare complete directives. A truncated excerpt cannot establish
|
|
372
|
+
// that removing a constraint is appropriate for this task.
|
|
373
|
+
if (principle.authority !== 'owner' || !principle.artifactContentSha256
|
|
374
|
+
|| principle.text.trim().length > ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS)
|
|
375
|
+
return false;
|
|
376
|
+
const outgoing = replaceable.find(({ principle: p, chars }) => chars >= shortfall && p.text.trim().length <= ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS);
|
|
377
|
+
if (!outgoing)
|
|
378
|
+
return false;
|
|
379
|
+
replacements.set(principle.activationId, outgoing.principle);
|
|
380
|
+
return true;
|
|
381
|
+
});
|
|
382
|
+
gapPriority = await input.selectNativeGap(feasible, {
|
|
383
|
+
excludedByBudget: feasible.length < omitted.length,
|
|
384
|
+
replacementByActivationId: replacements,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
351
387
|
const priority = input.adaptivePriority ?? gapPriority;
|
|
352
388
|
if (priority === undefined)
|
|
353
389
|
return nativeResult;
|
|
354
390
|
const signal = gapPriority?.signal ?? input.signal ?? new AbortController().signal;
|
|
355
391
|
const deadlineAt = gapPriority?.deadlineAt ?? input.deadlineAt;
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
return nativeResult;
|
|
392
|
+
const outgoing = gapPriority ? replacements.get(priority.activationId) : undefined;
|
|
393
|
+
const additiveOnly = (gapPriority !== undefined && outgoing === undefined) || input.additiveOnly === true;
|
|
359
394
|
const report = (status, reason, displacedActivationIds = []) => ({
|
|
360
395
|
status,
|
|
361
396
|
...(gapPriority ? { source: 'native_gap' } : {}),
|
|
@@ -365,6 +400,9 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
365
400
|
...(input.hookInvocationId ? { hookInvocationId: input.hookInvocationId } : {}),
|
|
366
401
|
displacedActivationIds,
|
|
367
402
|
});
|
|
403
|
+
if (gapPriority && (signal.aborted || (deadlineAt !== undefined && Date.now() >= deadlineAt))) {
|
|
404
|
+
return { ...nativeResult, adaptivePacking: report('unavailable', 'deadline') };
|
|
405
|
+
}
|
|
368
406
|
const nativeTargetMatches = principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
369
407
|
const [nativeTarget] = nativeTargetMatches;
|
|
370
408
|
const baselineHasTarget = nativePacking.included.some((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
@@ -390,6 +428,9 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
390
428
|
if (principles.filter((principle) => principle.principleId === nativeTarget.principleId).length !== 1) {
|
|
391
429
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_ambiguous') };
|
|
392
430
|
}
|
|
431
|
+
if (gapPriority && !feasible.includes(nativeTarget)) {
|
|
432
|
+
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_not_in_feasible_gap') };
|
|
433
|
+
}
|
|
393
434
|
const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true, noBusyWait: true });
|
|
394
435
|
const authorizedMatches = authorityRead.principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
395
436
|
const [authorizedTarget] = authorizedMatches;
|
|
@@ -415,6 +456,7 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
415
456
|
const targetBody = targetRendered.slice(targetRendered.indexOf('<directive '), targetRendered.indexOf('</directive>') + '</directive>'.length);
|
|
416
457
|
const prepared = (status, displaced = []) => ({
|
|
417
458
|
...report(status, undefined, displaced), targetSnapshot: authorizedTarget, targetBody,
|
|
459
|
+
...(outgoing ? { displacedSnapshot: outgoing } : {}),
|
|
418
460
|
nativeBaseline: nativeResult, ...(deadlineAt !== undefined ? { deadlineAt } : {}),
|
|
419
461
|
});
|
|
420
462
|
if (baselineHasTarget) {
|
|
@@ -423,13 +465,21 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
423
465
|
return withoutTarget('target_changed');
|
|
424
466
|
return { ...nativeResult, adaptivePacking: prepared('target_present') };
|
|
425
467
|
}
|
|
426
|
-
|
|
427
|
-
const
|
|
428
|
-
|
|
468
|
+
// Apply only the scored plan to the exact Native selection.
|
|
469
|
+
const prioritizedPacking = gapPriority
|
|
470
|
+
? {
|
|
471
|
+
...pack([...nativePacking.included.filter((p) => p !== outgoing), nativeTarget]),
|
|
472
|
+
truncated: nativePacking.truncated,
|
|
473
|
+
dropped: [
|
|
474
|
+
...(outgoing ? [outgoing.activationId] : []),
|
|
475
|
+
...nativePacking.dropped.filter((id) => id !== nativeTarget.activationId),
|
|
476
|
+
].slice(0, MAX_SHARED_DIAGNOSTIC_IDS),
|
|
477
|
+
oversized: nativePacking.oversized,
|
|
478
|
+
}
|
|
479
|
+
: pack([nativeTarget, ...nativeScanOrder.filter((principle) => principle.principleId !== nativeTarget.principleId)]);
|
|
429
480
|
if (!prioritizedPacking.included.some((principle) => principle.principleId === nativeTarget.principleId)) {
|
|
430
481
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_does_not_fit') };
|
|
431
482
|
}
|
|
432
|
-
const mandatoryIds = input.mandatoryPrincipleIds ?? [];
|
|
433
483
|
if (!Array.isArray(mandatoryIds) || mandatoryIds.some((id) => typeof id !== 'string')
|
|
434
484
|
|| mandatoryIds.some((id) => !prioritizedPacking.included.some((principle) => principle.principleId === id))) {
|
|
435
485
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'mandatory_constraint_displaced') };
|
|
@@ -438,6 +488,9 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
438
488
|
const displacedActivationIds = nativePacking.included
|
|
439
489
|
.filter((principle) => !prioritizedActivationIds.has(principle.activationId))
|
|
440
490
|
.map((principle) => principle.activationId);
|
|
491
|
+
if (outgoing && (displacedActivationIds.length !== 1 || displacedActivationIds[0] !== outgoing.activationId)) {
|
|
492
|
+
return withoutTarget('unexpected_replacement');
|
|
493
|
+
}
|
|
441
494
|
// PRI-1140: an additive-only target may never squeeze out content the
|
|
442
495
|
// native baseline already assembled. Decided BEFORE the revalidation read so
|
|
443
496
|
// a refused placement costs no further I/O; the would-be displacement is the
|
|
@@ -448,11 +501,25 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
448
501
|
adaptivePacking: report('unavailable', 'would_displace_native_assembly', displacedActivationIds.slice(0, MAX_SHARED_DIAGNOSTIC_IDS)),
|
|
449
502
|
};
|
|
450
503
|
}
|
|
451
|
-
const stillValid = await
|
|
504
|
+
const [stillValid, outgoingValid] = await Promise.all([
|
|
505
|
+
revalidateAdaptivePrinciple(input.workspaceDir, authorizedTarget, signal),
|
|
506
|
+
outgoing ? revalidateAdaptivePrinciple(input.workspaceDir, outgoing, signal) : true,
|
|
507
|
+
]);
|
|
508
|
+
if (gapPriority && (signal.aborted || (deadlineAt !== undefined && Date.now() >= deadlineAt))) {
|
|
509
|
+
return { ...nativeResult, adaptivePacking: report('unavailable', 'deadline') };
|
|
510
|
+
}
|
|
452
511
|
if (!stillValid)
|
|
453
512
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_changed') };
|
|
454
|
-
if (
|
|
455
|
-
return
|
|
513
|
+
if (!outgoingValid)
|
|
514
|
+
return withoutTarget('replacement_changed');
|
|
515
|
+
if (outgoing) {
|
|
516
|
+
const config = loadPdConfigForPlugin(input.workspaceDir);
|
|
517
|
+
if (!config.ok || !config.effective.config.adaptiveActivation?.replaceableActivationIds?.includes(outgoing.activationId)) {
|
|
518
|
+
return withoutTarget('replacement_permission_changed');
|
|
519
|
+
}
|
|
520
|
+
if (signal.aborted || (deadlineAt !== undefined && Date.now() >= deadlineAt))
|
|
521
|
+
return withoutTarget('deadline');
|
|
522
|
+
}
|
|
456
523
|
const result = makeResult(prioritizedPacking, principles, prepared('prioritized', displacedActivationIds));
|
|
457
524
|
// Adaptive assembly is deliberately limited to the existing renderer's Native budget cap.
|
|
458
525
|
return result;
|
|
@@ -15,28 +15,13 @@
|
|
|
15
15
|
* Everything here is pure: no I/O, no clock, no transport. The caller owns
|
|
16
16
|
* scheduling, cancellation and diagnostics.
|
|
17
17
|
*/
|
|
18
|
+
export declare const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
|
|
18
19
|
export declare const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = "insufficient_context";
|
|
19
|
-
/**
|
|
20
|
-
* PRESET evaluation criteria for this acceptance batch (v1-20261111).
|
|
21
|
-
*
|
|
22
|
-
* These numbers are a deliberate preset, NOT a value derived from the old
|
|
23
|
-
* GLM task-level samples: the old batch scored four task-level questions and
|
|
24
|
-
* is not the same question set. Those samples are used ONLY to replay the
|
|
25
|
-
* adjudicator against already-recorded numbers:
|
|
26
|
-
* replay-02 .9594 .9565 .0708 insufficient .1962 → uncertain (lead below margin)
|
|
27
|
-
* replay-03 .0496 .9958 .2068 insufficient .1375 → selected
|
|
28
|
-
* replay-04 .0624 .0340 .9888 insufficient .2668 → selected
|
|
29
|
-
*
|
|
30
|
-
* Do NOT tune these per failing turn, and do not tune them while a real
|
|
31
|
-
* batch is running: changing them is a product decision that requires a new
|
|
32
|
-
* version string and a new frozen batch.
|
|
33
|
-
*/
|
|
20
|
+
/** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
|
|
34
21
|
export declare const ADAPTIVE_DECISION_CRITERIA: {
|
|
35
|
-
readonly version: '
|
|
22
|
+
readonly version: 'v2-20261112';
|
|
36
23
|
/** A candidate must reach this independent score to be eligible. */
|
|
37
24
|
readonly selectThreshold: 0.7;
|
|
38
|
-
/** The winner must lead the runner-up by this much, or the turn is ambiguous. */
|
|
39
|
-
readonly leadMargin: 0.25;
|
|
40
25
|
/** Above this "information is insufficient" score, PD refuses to select. */
|
|
41
26
|
readonly insufficientThreshold: 0.6;
|
|
42
27
|
};
|
|
@@ -68,6 +53,7 @@ export interface BuildDecisionRequestInput {
|
|
|
68
53
|
readonly ref: string;
|
|
69
54
|
readonly text: string;
|
|
70
55
|
readonly digest: string;
|
|
56
|
+
readonly replaces?: string;
|
|
71
57
|
}[];
|
|
72
58
|
/** Bounded by the caller; a request larger than this is refused locally. */
|
|
73
59
|
readonly maxPayloadChars: number;
|
|
@@ -89,6 +75,7 @@ export declare function candidateQuestionId(ref: string): string;
|
|
|
89
75
|
export declare function buildDecisionQuestions(candidates: readonly {
|
|
90
76
|
readonly ref: string;
|
|
91
77
|
readonly text: string;
|
|
78
|
+
readonly replaces?: string;
|
|
92
79
|
}[]): DecisionQuestions;
|
|
93
80
|
export declare function buildDecisionRequest(input: BuildDecisionRequestInput): BuildDecisionRequestResult;
|
|
94
81
|
/**
|
|
@@ -129,13 +116,13 @@ export type DecisionOutcome = {
|
|
|
129
116
|
} | {
|
|
130
117
|
readonly status: 'none_applicable' | 'uncertain';
|
|
131
118
|
readonly ref: null;
|
|
132
|
-
readonly reason: 'below_selection_threshold' | '
|
|
119
|
+
readonly reason: 'below_selection_threshold' | 'candidate_tied' | 'information_insufficient';
|
|
133
120
|
readonly scores: Readonly<Record<string, number>>;
|
|
134
121
|
};
|
|
135
122
|
/**
|
|
136
123
|
* Local adjudication of the INDEPENDENT condition scores. Order matters:
|
|
137
124
|
* insufficient information first (it invalidates any candidate ranking), then
|
|
138
|
-
* the
|
|
125
|
+
* the applicability threshold. An exact tie leaves no unique winner.
|
|
139
126
|
*/
|
|
140
127
|
export declare function adjudicateDecision(scores: Readonly<Record<string, number>>, candidates: readonly {
|
|
141
128
|
readonly ref: string;
|
|
@@ -15,28 +15,13 @@
|
|
|
15
15
|
* Everything here is pure: no I/O, no clock, no transport. The caller owns
|
|
16
16
|
* scheduling, cancellation and diagnostics.
|
|
17
17
|
*/
|
|
18
|
+
export const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
|
|
18
19
|
export const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = 'insufficient_context';
|
|
19
|
-
/**
|
|
20
|
-
* PRESET evaluation criteria for this acceptance batch (v1-20261111).
|
|
21
|
-
*
|
|
22
|
-
* These numbers are a deliberate preset, NOT a value derived from the old
|
|
23
|
-
* GLM task-level samples: the old batch scored four task-level questions and
|
|
24
|
-
* is not the same question set. Those samples are used ONLY to replay the
|
|
25
|
-
* adjudicator against already-recorded numbers:
|
|
26
|
-
* replay-02 .9594 .9565 .0708 insufficient .1962 → uncertain (lead below margin)
|
|
27
|
-
* replay-03 .0496 .9958 .2068 insufficient .1375 → selected
|
|
28
|
-
* replay-04 .0624 .0340 .9888 insufficient .2668 → selected
|
|
29
|
-
*
|
|
30
|
-
* Do NOT tune these per failing turn, and do not tune them while a real
|
|
31
|
-
* batch is running: changing them is a product decision that requires a new
|
|
32
|
-
* version string and a new frozen batch.
|
|
33
|
-
*/
|
|
20
|
+
/** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
|
|
34
21
|
export const ADAPTIVE_DECISION_CRITERIA = {
|
|
35
|
-
version: '
|
|
22
|
+
version: 'v2-20261112',
|
|
36
23
|
/** A candidate must reach this independent score to be eligible. */
|
|
37
24
|
selectThreshold: 0.7,
|
|
38
|
-
/** The winner must lead the runner-up by this much, or the turn is ambiguous. */
|
|
39
|
-
leadMargin: 0.25,
|
|
40
25
|
/** Above this "information is insufficient" score, PD refuses to select. */
|
|
41
26
|
insufficientThreshold: 0.6,
|
|
42
27
|
};
|
|
@@ -53,9 +38,9 @@ export function buildDecisionQuestions(candidates) {
|
|
|
53
38
|
for (const candidate of candidates) {
|
|
54
39
|
questions[candidateQuestionId(candidate.ref)] = {
|
|
55
40
|
type: 'noul',
|
|
56
|
-
instructions:
|
|
57
|
-
+
|
|
58
|
-
+ '
|
|
41
|
+
instructions: `依据 currentInstruction 判断用户现在要做什么,并比较 state.candidates。候选 ${candidate.ref} 是否直接适用于这项任务,且最能改善下一步具体行动?`
|
|
42
|
+
+ '能避免当前任务的具体失误或补上关键步骤时给高分。仅主题相近、重复用户已明确的要求、或对下一步没有实质帮助时给低分。没有合适候选时全部给低分。'
|
|
43
|
+
+ (candidate.replaces === undefined ? '' : ' 此方案会移除该候选在 state 中的 replaces 原则。只有候选对当前任务明显更有帮助,且移除原原则不会丢掉当前仍需的约束时才给高分;拿不准则给低分。'),
|
|
59
44
|
};
|
|
60
45
|
}
|
|
61
46
|
questions[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION] = {
|
|
@@ -77,6 +62,7 @@ export function buildDecisionRequest(input) {
|
|
|
77
62
|
ref: candidate.ref,
|
|
78
63
|
text: candidate.text,
|
|
79
64
|
digest: candidate.digest,
|
|
65
|
+
...(candidate.replaces !== undefined ? { replaces: candidate.replaces } : {}),
|
|
80
66
|
})),
|
|
81
67
|
};
|
|
82
68
|
const body = {
|
|
@@ -166,7 +152,7 @@ export function validateDecisionResponse(value, expected) {
|
|
|
166
152
|
/**
|
|
167
153
|
* Local adjudication of the INDEPENDENT condition scores. Order matters:
|
|
168
154
|
* insufficient information first (it invalidates any candidate ranking), then
|
|
169
|
-
* the
|
|
155
|
+
* the applicability threshold. An exact tie leaves no unique winner.
|
|
170
156
|
*/
|
|
171
157
|
export function adjudicateDecision(scores, candidates, criteria = ADAPTIVE_DECISION_CRITERIA) {
|
|
172
158
|
const insufficient = scores[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION];
|
|
@@ -183,8 +169,8 @@ export function adjudicateDecision(scores, candidates, criteria = ADAPTIVE_DECIS
|
|
|
183
169
|
if (!top || top.score < criteria.selectThreshold) {
|
|
184
170
|
return { status: 'none_applicable', ref: null, reason: 'below_selection_threshold', scores };
|
|
185
171
|
}
|
|
186
|
-
if (runnerUp && top.score
|
|
187
|
-
return { status: 'uncertain', ref: null, reason: '
|
|
172
|
+
if (runnerUp && top.score === runnerUp.score) {
|
|
173
|
+
return { status: 'uncertain', ref: null, reason: 'candidate_tied', scores };
|
|
188
174
|
}
|
|
189
175
|
return { status: 'selected', ref: top.ref, reason: 'selected', scores };
|
|
190
176
|
}
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import type { HostEvent } from '@principles/core/host';
|
|
12
12
|
import type { ActivatedPrinciple, PdConfig } from '@principles/core/runtime';
|
|
13
|
+
import type { AdaptiveGapOptions } from './active-principle-prompt.js';
|
|
13
14
|
import { type AdaptiveSelectionModel } from './adaptive-selection.js';
|
|
14
15
|
/** Independent switch. `features.host.codex.enabled` remains the whole-hook gate. */
|
|
15
16
|
export declare const ADAPTIVE_ACTIVATION_FLAG = "host.codex.adaptive_activation";
|
|
@@ -26,7 +27,7 @@ export interface AdaptivePrioritySelection {
|
|
|
26
27
|
readonly deadlineAt?: number;
|
|
27
28
|
readonly signal?: AbortSignal;
|
|
28
29
|
}
|
|
29
|
-
export type AdaptivePriorityProvider = (event: HostEvent, candidates: readonly ActivatedPrinciple[]) => Promise<AdaptivePrioritySelection | undefined>;
|
|
30
|
+
export type AdaptivePriorityProvider = (event: HostEvent, candidates: readonly ActivatedPrinciple[], options: AdaptiveGapOptions) => Promise<AdaptivePrioritySelection | undefined>;
|
|
30
31
|
export interface AdaptiveActivationReadiness {
|
|
31
32
|
readonly readiness: 'ready' | 'disabled' | 'needs_setup';
|
|
32
33
|
readonly reason: string;
|
|
@@ -63,7 +63,7 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
63
63
|
const now = options.now ?? Date.now;
|
|
64
64
|
const requestTimeoutMs = options.requestTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
|
|
65
65
|
const outputReserveMs = options.outputReserveMs ?? ADAPTIVE_OUTPUT_RESERVE_MS;
|
|
66
|
-
return async (event, candidates) => {
|
|
66
|
+
return async (event, candidates, { excludedByBudget, replacementByActivationId }) => {
|
|
67
67
|
if (event.kind !== 'before_prompt_build')
|
|
68
68
|
return undefined;
|
|
69
69
|
const { sessionId, turnId, promptContent, workspaceDir } = event.context;
|
|
@@ -72,8 +72,8 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
72
72
|
const hostDeadlineAt = options.outerDeadlineAt === undefined
|
|
73
73
|
? undefined
|
|
74
74
|
: options.outerDeadlineAt - outputReserveMs;
|
|
75
|
-
// PRI-1181: deterministic gate
|
|
76
|
-
//
|
|
75
|
+
// PRI-1181: the deterministic gate runs before any model request.
|
|
76
|
+
// Native has already been assembled, even when Adaptive skips.
|
|
77
77
|
const skip = decideAdaptiveSkip({
|
|
78
78
|
kind: event.kind,
|
|
79
79
|
sessionId,
|
|
@@ -84,10 +84,10 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
84
84
|
? { minExecutableBudgetMs: options.minExecutableBudgetMs }
|
|
85
85
|
: {}),
|
|
86
86
|
});
|
|
87
|
-
if (skip.skip) {
|
|
87
|
+
if (skip.skip || (candidates.length === 0 && excludedByBudget)) {
|
|
88
88
|
options.onDiagnostic?.({
|
|
89
89
|
status: 'skipped',
|
|
90
|
-
reason: skip.reason,
|
|
90
|
+
reason: skip.skip ? skip.reason : 'no_appendable_gap',
|
|
91
91
|
stage: 'gate',
|
|
92
92
|
sends: 0,
|
|
93
93
|
requestSentAt: null,
|
|
@@ -112,6 +112,7 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
112
112
|
workspaceDir: workspaceDir || options.workspaceDir,
|
|
113
113
|
currentPrompt: prompt,
|
|
114
114
|
candidates,
|
|
115
|
+
replacementByActivationId,
|
|
115
116
|
model: options.model,
|
|
116
117
|
requestTimeoutMs,
|
|
117
118
|
...(hostDeadlineAt !== undefined ? { outerDeadlineAt: hostDeadlineAt, signal } : {}),
|
|
@@ -32,6 +32,7 @@ export interface AdaptiveCandidate {
|
|
|
32
32
|
readonly ref: string;
|
|
33
33
|
readonly text: string;
|
|
34
34
|
readonly digest: string;
|
|
35
|
+
readonly replaces?: string;
|
|
35
36
|
readonly principle: AdaptiveCandidateSource;
|
|
36
37
|
}
|
|
37
38
|
export interface BoundedSelectionInput {
|
|
@@ -46,6 +47,7 @@ export interface BoundedSelectionInput {
|
|
|
46
47
|
readonly ref: string;
|
|
47
48
|
readonly text: string;
|
|
48
49
|
readonly digest: string;
|
|
50
|
+
readonly replaces?: string;
|
|
49
51
|
}[];
|
|
50
52
|
};
|
|
51
53
|
readonly entries: readonly AdaptiveCandidate[];
|
|
@@ -112,6 +114,7 @@ export declare function buildBoundedSelectionInput(input: {
|
|
|
112
114
|
readonly source?: string;
|
|
113
115
|
}[];
|
|
114
116
|
readonly candidates: readonly AdaptiveCandidateSource[];
|
|
117
|
+
readonly replacementByActivationId?: ReadonlyMap<string, ActivatedPrinciple> | undefined;
|
|
115
118
|
}): BuildBoundedInputResult;
|
|
116
119
|
export interface DecisionSelectorOptions {
|
|
117
120
|
readonly fetchImpl?: typeof fetch;
|
|
@@ -145,6 +148,7 @@ export interface RunAdaptiveSelectionOptions {
|
|
|
145
148
|
readonly workspaceDir: string;
|
|
146
149
|
readonly currentPrompt: string;
|
|
147
150
|
readonly candidates: readonly ActivatedPrinciple[];
|
|
151
|
+
readonly replacementByActivationId?: ReadonlyMap<string, ActivatedPrinciple> | undefined;
|
|
148
152
|
readonly model: AdaptiveSelectionModel;
|
|
149
153
|
readonly requestTimeoutMs?: number;
|
|
150
154
|
readonly signal?: AbortSignal;
|
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import crypto from 'node:crypto';
|
|
24
24
|
import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
|
|
25
|
-
import { adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
|
|
25
|
+
import { ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS, adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
|
|
26
26
|
export const ADAPTIVE_SELECTION_LIMITS = {
|
|
27
27
|
maxCandidates: 12,
|
|
28
|
-
maxCandidateChars:
|
|
28
|
+
maxCandidateChars: ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS,
|
|
29
29
|
maxPriorMessages: 4,
|
|
30
30
|
maxPriorMessageChars: 1200,
|
|
31
31
|
maxInputChars: 6000,
|
|
@@ -67,7 +67,9 @@ export function buildBoundedSelectionInput(input) {
|
|
|
67
67
|
if (!principle.text.trim())
|
|
68
68
|
continue;
|
|
69
69
|
const candidateText = boundText(principle.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars);
|
|
70
|
+
const outgoing = input.replacementByActivationId?.get(principle.activationId);
|
|
70
71
|
entries.push({
|
|
72
|
+
...(outgoing ? { replaces: boundText(outgoing.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars) } : {}),
|
|
71
73
|
ref: `c${entries.length + 1}`,
|
|
72
74
|
text: candidateText,
|
|
73
75
|
// The digest stays part of the frozen candidate snapshot even though the
|
|
@@ -87,7 +89,7 @@ export function buildBoundedSelectionInput(input) {
|
|
|
87
89
|
payload: {
|
|
88
90
|
currentInstruction,
|
|
89
91
|
priorMessages: boundedPrior,
|
|
90
|
-
candidates: entries.map((
|
|
92
|
+
candidates: entries.map(({ ref, text, digest, replaces }) => ({ ref, text, digest, ...(replaces !== undefined ? { replaces } : {}) })),
|
|
91
93
|
},
|
|
92
94
|
entries,
|
|
93
95
|
priorDropped: Math.max(0, priorMessages.length - selectedPrior.length),
|
|
@@ -335,6 +337,7 @@ export async function runAdaptiveSelection(options) {
|
|
|
335
337
|
const built = buildBoundedSelectionInput({
|
|
336
338
|
currentInput: options.currentPrompt,
|
|
337
339
|
candidates: options.candidates,
|
|
340
|
+
replacementByActivationId: options.replacementByActivationId,
|
|
338
341
|
});
|
|
339
342
|
if (!built.ok)
|
|
340
343
|
return unavailable(built.reason, 'idle');
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D)
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* package:
|
|
2
|
+
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
|
|
3
|
+
* amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
|
|
4
|
+
* (2026-11-12) in:
|
|
6
5
|
* docs/superpowers/specs/2026-08-28-codex-governance-closure-g0-g2a-decision.md
|
|
7
6
|
* § "Frozen consent disclosure text (setup will show this verbatim)"
|
|
8
7
|
*
|
|
@@ -12,12 +11,18 @@
|
|
|
12
11
|
* the document and asserts byte equality with this constant, so any drift
|
|
13
12
|
* here fails CI.
|
|
14
13
|
*
|
|
14
|
+
* v2 (g2b) corrects the "what PD reads" paragraph: the model's own plaintext
|
|
15
|
+
* thinking summary IS stored (it is visible in the Codex UI); the encrypted
|
|
16
|
+
* reasoning body is neither read nor saved. The version advanced so that a
|
|
17
|
+
* consent granted against the old disclosure falls back to the bounded tier
|
|
18
|
+
* instead of silently widening what is stored.
|
|
19
|
+
*
|
|
15
20
|
* The English rendering states the same facts; per the G2A binding note it is
|
|
16
21
|
* produced at setup implementation time from the frozen Chinese text. Setup
|
|
17
22
|
* surfaces always present the Chinese SSoT first.
|
|
18
23
|
*/
|
|
19
|
-
export declare const CODEX_INGESTION_DISCLOSURE_VERSION = "
|
|
24
|
+
export declare const CODEX_INGESTION_DISCLOSURE_VERSION = "g2b-2026-11-12";
|
|
20
25
|
export type CodexIngestionDisclosureLanguage = 'zh' | 'en';
|
|
21
|
-
export declare const CODEX_INGESTION_DISCLOSURE_ZH = "### Principles Disciple \u2014 \u5BF9\u8BDD\u89C2\u5BDF\u4E0E\u6CBB\u7406\u95ED\u73AF\uFF08Codex\uFF09\n\n**\u5F00\u542F\u540E PD \u4F1A\u8BFB\u53D6\u4EC0\u4E48\uFF1F**\n\u8BFB\u53D6\u672C\u5DE5\u4F5C\u533A\u5185 Codex \u660E\u786E\u63D0\u4F9B\u7ED9 PD \u7684\u4F1A\u8BDD\u8BB0\u5F55\uFF08transcript\uFF09\u3002\u8FDB\u5165\u6CBB\u7406\u89C2\u5BDF\u7684\u53EA\u6709\u53EF\u89C1\u5185\u5BB9\uFF1A\u4F60\u53D1\u51FA\u7684\u6D88\u606F\u3001\u52A9\u624B\u7684\u53EF\u89C1\u56DE\u590D\u3001\
|
|
22
|
-
export declare const CODEX_INGESTION_DISCLOSURE_EN = "### Principles Disciple \u2014 Conversation Observation & Governance Closure (Codex)\n\n**What does PD read once enabled?**\nPD reads the Codex session transcripts that Codex explicitly provides to PD inside this workspace. Only visible content enters governance observation: the messages you send, the assistant's visible replies,
|
|
26
|
+
export declare const CODEX_INGESTION_DISCLOSURE_ZH = "### Principles Disciple \u2014 \u5BF9\u8BDD\u89C2\u5BDF\u4E0E\u6CBB\u7406\u95ED\u73AF\uFF08Codex\uFF09\n\n**\u5F00\u542F\u540E PD \u4F1A\u8BFB\u53D6\u4EC0\u4E48\uFF1F**\n\u8BFB\u53D6\u672C\u5DE5\u4F5C\u533A\u5185 Codex \u660E\u786E\u63D0\u4F9B\u7ED9 PD \u7684\u4F1A\u8BDD\u8BB0\u5F55\uFF08transcript\uFF09\u3002\u8FDB\u5165\u6CBB\u7406\u89C2\u5BDF\u7684\u53EA\u6709\u53EF\u89C1\u5185\u5BB9\uFF1A\u4F60\u53D1\u51FA\u7684\u6D88\u606F\u3001\u52A9\u624B\u7684\u53EF\u89C1\u56DE\u590D\u3001\u5DE5\u5177\u8C03\u7528\u7684\u540D\u79F0/\u8F93\u5165/\u7ED3\u679C\uFF08\u7528\u4E8E\u8BC6\u522B\u53CD\u590D\u51FA\u73B0\u7684\u95EE\u9898\uFF09\uFF0C\u4EE5\u53CA\u6A21\u578B\u81EA\u5DF1\u5199\u51FA\u7684\u601D\u8003\u6458\u8981\uFF08\u4E00\u6BB5\u7B80\u77ED\u6587\u5B57\uFF0CCodex \u754C\u9762\u4E0A\u4E5F\u4F1A\u663E\u793A\u7ED9\u4F60\uFF09\u3002Codex \u53E6\u5916\u4EE5\u52A0\u5BC6\u5F62\u5F0F\u4FDD\u5B58\u7684\u5B8C\u6574\u601D\u8003\u6B63\u6587\uFF0CPD \u65E2\u4E0D\u8BFB\u53D6\u4E5F\u4E0D\u4FDD\u5B58\u3002\u8BB0\u5F55\u4E2D\u540C\u65F6\u5B58\u5728\u7684\u7CFB\u7EDF/\u5F00\u53D1\u8005\u63D0\u793A\u8BCD\u3001\u5BBF\u4E3B\u6CE8\u5165\u7684\u73AF\u5883\u4E0A\u4E0B\u6587\uFF0C\u4F1A\u5728\u89E3\u6790\u65F6\u88AB\u8BC6\u522B\u5E76\u4E22\u5F03\u2014\u2014\u4E0D\u4F1A\u88AB\u4FDD\u5B58\u3001\u4E0D\u4F1A\u8FDB\u5165\u65E5\u5FD7\u3001\u4E0D\u4F1A\u53D1\u9001\u7ED9\u8BCA\u65AD\u6A21\u578B\u3002\n\n**\u4E3A\u4EC0\u4E48\u8BFB\u53D6\uFF1F**\n\u4E3A\u4E86\u8BA9 PD \u5728 Codex \u4E0A\u5B8C\u6210\u5B83\u627F\u8BFA\u7684\u95ED\u73AF\uFF1A\u628A\u4F60\u53CD\u590D\u7EA0\u6B63\u7684\u5730\u65B9\u53D8\u6210\u4E00\u6761\u53EF\u5BA1\u67E5\u7684\u539F\u5219\u5019\u9009\u2014\u2014\u4F60\u9700\u8981\u5148\u770B\u5230\u8BC1\u636E\uFF0C\u518D\u51B3\u5B9A\u662F\u5426\u91C7\u7EB3\u3002\u4E0D\u89E3\u6790\u5BF9\u8BDD\uFF0CPD \u5C31\u53EA\u80FD\u7BA1\u5DE5\u5177\uFF0C\u5B66\u4E0D\u5230\u7EA0\u6B63\u3002\n\n**\u4FDD\u5B58\u591A\u5C11\u3001\u591A\u4E45\uFF1F**\n\u6BCF\u4E2A\u4F1A\u8BDD\u53EA\u4FDD\u7559\u6700\u8FD1 32 \u6761\u53EF\u89C1\u6D88\u606F\u3001\u6700\u591A 7 \u5929\uFF08\u5148\u5230\u671F\u5148\u5220\u9664\uFF09\u3002\u5F53\u67D0\u4E2A\u95EE\u9898\u88AB\u6B63\u5F0F\u7ACB\u4E3A pain \u65F6\uFF0C\u624D\u4F1A\u628A\u5B83\u7684\u524D 12 \u6761\u6D88\u606F + \u89E6\u53D1\u70B9 + \u52A9\u624B\u7684\u4E0B\u4E00\u6761\u5B8C\u6574\u56DE\u590D\u5347\u7EA7\u4E3A\u957F\u671F\u6CBB\u7406\u8BC1\u636E\uFF0C\u6309\u73B0\u6709\u6CBB\u7406\u6570\u636E\u7684\u751F\u547D\u5468\u671F\u7BA1\u7406\u3002\u4FDD\u5B58\u7684\u5DE5\u5177\u8BC1\u636E\u5728\u843D\u76D8\u524D\u4F1A\u7ECF\u8FC7\u65E2\u6709\u7684\u654F\u611F\u5B57\u6BB5\u4E0E\u5E38\u89C1\u5BC6\u94A5\u683C\u5F0F\u8131\u654F\uFF1B\u4F46\u8BF7\u6CE8\u610F\uFF1A\u5982\u679C\u4E00\u6BB5\u5BC6\u94A5\u770B\u8D77\u6765\u5C31\u50CF\u666E\u901A\u6587\u5B57\uFF0C\u4EFB\u4F55\u8FC7\u6EE4\u5668\u90FD\u65E0\u6CD5\u8BC6\u522B\u5B83\u2014\u2014\u8BF7\u4E0D\u8981\u8BA9 PD \u89C2\u5BDF\u5305\u542B\u6B64\u7C7B\u5185\u5BB9\u7684\u4F1A\u8BDD\u3002\n\n**\u6570\u636E\u4F1A\u79BB\u5F00\u672C\u673A\u5417\uFF1F**\n\u89C2\u5BDF\u6570\u636E\u672C\u8EAB\u53EA\u5B58\u5728\u672C\u673A\u5DE5\u4F5C\u533A\u3002\u88AB\u5347\u7EA7\u4E3A\u6CBB\u7406\u8BC1\u636E\u7684\u5BF9\u8BDD\u7247\u6BB5\uFF0C\u4F1A\u50CF\u73B0\u6709\u8BCA\u65AD\u6D41\u7A0B\u4E00\u6837\u53D1\u9001\u7ED9\u4F60\u914D\u7F6E\u7684 LLM API \u505A\u8BCA\u65AD\u2014\u2014\u8FD9\u662F\u552F\u4E00\u7684\u5916\u53D1\u8DEF\u5F84\uFF0C\u4E0E OpenClaw \u4E0A\u7684\u73B0\u6709\u884C\u4E3A\u4E00\u81F4\u3002\u4EA7\u54C1\u9065\u6D4B\u4E0D\u5305\u542B\u4EFB\u4F55\u6D88\u606F\u5185\u5BB9\u6216\u4F1A\u8BDD\u6807\u8BC6\u3002\n\n**\u5982\u4F55\u5173\u95ED\uFF1F\u968F\u65F6\u3002**\n\u5173\u95ED\u540E PD \u7ACB\u5373\u505C\u6B62\u8BFB\u53D6 transcript\uFF08\u4E0D\u662F\"\u8BFB\u4E86\u518D\u4E22\u5F03\"\uFF0C\u800C\u662F\u6839\u672C\u4E0D\u6253\u5F00\uFF09\u3002\u5DF2\u6709\u7684\u539F\u5219\u6CE8\u5165\u3001\u5DE5\u5177\u62E6\u622A\u3001\u65E2\u6709\u5DE5\u5177\u8BC1\u636E\u5B8C\u5168\u4E0D\u53D7\u5F71\u54CD\u3002\u5DF2\u4FDD\u5B58\u7684\u5185\u5BB9\u6309\u4E0A\u8FF0\u671F\u9650\u81EA\u7136\u8FC7\u671F\uFF1B\u5347\u7EA7\u8FC7\u7684\u8BC1\u636E\u53EA\u80FD\u7531\u4F60\u901A\u8FC7\u65E2\u6709\u6CBB\u7406\u6E05\u7406\u547D\u4EE4\u663E\u5F0F\u5220\u9664\u3002\u5378\u8F7D\u4E0D\u4F1A\u9759\u9ED8\u5220\u9664\u4EFB\u4F55\u8BC1\u636E\u3002\n\n**\u9ED8\u8BA4\u72B6\u6001\uFF1F**\n\u9ED8\u8BA4\u5173\u95ED\u3002\u53EA\u6709\u4F60\u5728\u770B\u5230\u672C\u8BF4\u660E\u540E\u660E\u786E\u9009\u62E9\u5F00\u542F\u624D\u4F1A\u751F\u6548\uFF1B\u5347\u7EA7 PD \u6C38\u8FDC\u4E0D\u4F1A\u66FF\u4F60\u5F00\u542F\u3002";
|
|
27
|
+
export declare const CODEX_INGESTION_DISCLOSURE_EN = "### Principles Disciple \u2014 Conversation Observation & Governance Closure (Codex)\n\n**What does PD read once enabled?**\nPD reads the Codex session transcripts that Codex explicitly provides to PD inside this workspace. Only visible content enters governance observation: the messages you send, the assistant's visible replies, the names/inputs/results of tool calls (used to recognize recurring problems), and the short thinking summaries the model writes (the same text Codex shows you in its UI). The full reasoning body that Codex keeps in encrypted form is neither read nor saved by PD. System/developer prompts and host-injected environment context present in the same records are recognized and discarded during parsing \u2014 never saved, never written to logs, never sent to the diagnosis model.\n\n**Why read at all?**\nSo that PD can deliver on its promised closed loop on Codex: turning the places you repeatedly correct into a reviewable principle candidate \u2014 you see the evidence first, then decide whether to adopt it. Without parsing conversations, PD can only govern tools and cannot learn your corrections.\n\n**How much is kept, and for how long?**\nPer session, only the most recent 32 visible messages are kept, for at most 7 days (expired first, deleted first). Only when a problem is formally established as a pain are its preceding 12 messages + the trigger point + the assistant's next complete reply promoted into long-term governance evidence, managed under the existing governance data lifecycle. Saved tool evidence passes through the existing sensitive-field and common-secret-format redaction before being written; but note: if a secret looks like ordinary text, no filter can recognize it \u2014 please do not let PD observe sessions containing such content.\n\n**Does data leave this machine?**\nObservation data itself lives only in the local workspace. Conversation fragments promoted into governance evidence are sent to your configured LLM API for diagnosis, exactly like the existing diagnosis flow \u2014 this is the only egress path, consistent with current behavior on OpenClaw. Product telemetry contains no message content and no session identifiers.\n\n**How do I turn it off? Anytime.**\nOnce off, PD immediately stops reading transcripts (not \"read then discard\" \u2014 the transcript is never opened at all). Existing principle injection, tool interception, and existing tool evidence are completely unaffected. Saved content expires naturally per the limits above; promoted evidence can only be deleted explicitly by you through the existing governance cleanup commands. Uninstall never silently deletes any evidence.\n\n**Default state?**\nOff by default. It takes effect only after you explicitly choose to enable it after seeing this disclosure; upgrading PD never enables it for you.";
|
|
23
28
|
export declare function getCodexIngestionDisclosureText(language: CodexIngestionDisclosureLanguage): string;
|
package/dist/codex-disclosure.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D)
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* package:
|
|
2
|
+
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
|
|
3
|
+
* amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
|
|
4
|
+
* (2026-11-12) in:
|
|
6
5
|
* docs/superpowers/specs/2026-08-28-codex-governance-closure-g0-g2a-decision.md
|
|
7
6
|
* § "Frozen consent disclosure text (setup will show this verbatim)"
|
|
8
7
|
*
|
|
@@ -12,15 +11,21 @@
|
|
|
12
11
|
* the document and asserts byte equality with this constant, so any drift
|
|
13
12
|
* here fails CI.
|
|
14
13
|
*
|
|
14
|
+
* v2 (g2b) corrects the "what PD reads" paragraph: the model's own plaintext
|
|
15
|
+
* thinking summary IS stored (it is visible in the Codex UI); the encrypted
|
|
16
|
+
* reasoning body is neither read nor saved. The version advanced so that a
|
|
17
|
+
* consent granted against the old disclosure falls back to the bounded tier
|
|
18
|
+
* instead of silently widening what is stored.
|
|
19
|
+
*
|
|
15
20
|
* The English rendering states the same facts; per the G2A binding note it is
|
|
16
21
|
* produced at setup implementation time from the frozen Chinese text. Setup
|
|
17
22
|
* surfaces always present the Chinese SSoT first.
|
|
18
23
|
*/
|
|
19
|
-
export const CODEX_INGESTION_DISCLOSURE_VERSION = '
|
|
24
|
+
export const CODEX_INGESTION_DISCLOSURE_VERSION = 'g2b-2026-11-12';
|
|
20
25
|
export const CODEX_INGESTION_DISCLOSURE_ZH = `### Principles Disciple — 对话观察与治理闭环(Codex)
|
|
21
26
|
|
|
22
27
|
**开启后 PD 会读取什么?**
|
|
23
|
-
读取本工作区内 Codex 明确提供给 PD 的会话记录(transcript
|
|
28
|
+
读取本工作区内 Codex 明确提供给 PD 的会话记录(transcript)。进入治理观察的只有可见内容:你发出的消息、助手的可见回复、工具调用的名称/输入/结果(用于识别反复出现的问题),以及模型自己写出的思考摘要(一段简短文字,Codex 界面上也会显示给你)。Codex 另外以加密形式保存的完整思考正文,PD 既不读取也不保存。记录中同时存在的系统/开发者提示词、宿主注入的环境上下文,会在解析时被识别并丢弃——不会被保存、不会进入日志、不会发送给诊断模型。
|
|
24
29
|
|
|
25
30
|
**为什么读取?**
|
|
26
31
|
为了让 PD 在 Codex 上完成它承诺的闭环:把你反复纠正的地方变成一条可审查的原则候选——你需要先看到证据,再决定是否采纳。不解析对话,PD 就只能管工具,学不到纠正。
|
|
@@ -39,7 +44,7 @@ export const CODEX_INGESTION_DISCLOSURE_ZH = `### Principles Disciple — 对话
|
|
|
39
44
|
export const CODEX_INGESTION_DISCLOSURE_EN = `### Principles Disciple — Conversation Observation & Governance Closure (Codex)
|
|
40
45
|
|
|
41
46
|
**What does PD read once enabled?**
|
|
42
|
-
PD reads the Codex session transcripts that Codex explicitly provides to PD inside this workspace. Only visible content enters governance observation: the messages you send, the assistant's visible replies,
|
|
47
|
+
PD reads the Codex session transcripts that Codex explicitly provides to PD inside this workspace. Only visible content enters governance observation: the messages you send, the assistant's visible replies, the names/inputs/results of tool calls (used to recognize recurring problems), and the short thinking summaries the model writes (the same text Codex shows you in its UI). The full reasoning body that Codex keeps in encrypted form is neither read nor saved by PD. System/developer prompts and host-injected environment context present in the same records are recognized and discarded during parsing — never saved, never written to logs, never sent to the diagnosis model.
|
|
43
48
|
|
|
44
49
|
**Why read at all?**
|
|
45
50
|
So that PD can deliver on its promised closed loop on Codex: turning the places you repeatedly correct into a reviewable principle candidate — you see the evidence first, then decide whether to adopt it. Without parsing conversations, PD can only govern tools and cannot learn your corrections.
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
import { type GovernanceObservationInput } from '../governance-observation-store.js';
|
|
31
31
|
import { type HookHints, type SessionRef, type TranscriptDelta, type TranscriptPort, type TranscriptSourceAdapter } from './source.js';
|
|
32
32
|
import type { ConversationIngestionConsentDecision } from './consent.js';
|
|
33
|
+
import { type TextPolicy } from './text-policy.js';
|
|
33
34
|
/** Verdict of a pre-ingest host side-write: failure holds the checkpoint (retry-safe). */
|
|
34
35
|
export type PreIngestVerdict = {
|
|
35
36
|
ok: true;
|
|
@@ -65,6 +66,13 @@ export interface RunIngestionArgs {
|
|
|
65
66
|
readonly consent: {
|
|
66
67
|
decision: ConversationIngestionConsentDecision | 'not_present';
|
|
67
68
|
};
|
|
69
|
+
/**
|
|
70
|
+
* PRI-1179: how much `visible_text` may be stored. The host resolves this
|
|
71
|
+
* from its OWN consent record via `resolveTextPolicy(record, disclosureVersion)`
|
|
72
|
+
* — a stale or non-granted record resolves to the bounded tier, never wider.
|
|
73
|
+
* Absent = bounded (the pre-existing 200-char content bound).
|
|
74
|
+
*/
|
|
75
|
+
readonly textPolicy?: TextPolicy;
|
|
68
76
|
readonly now?: Date;
|
|
69
77
|
/** Injected filesystem boundary (tests spy here; production uses the node port). */
|
|
70
78
|
readonly port?: TranscriptPort;
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
import { ingestGovernanceObservations, readGovernanceCheckpoint, } from '../governance-observation-store.js';
|
|
31
31
|
import { CONVERSATION_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError, createNodeTranscriptPort, } from './source.js';
|
|
32
|
+
import { TEXT_POLICY_BOUNDED_MAX_CHARS } from './text-policy.js';
|
|
32
33
|
export function runConversationIngestion(args) {
|
|
33
34
|
const texts = {
|
|
34
35
|
readFailedNextAction: 'verify the transcript file still exists and is a regular file inside the host sessions root.',
|
|
@@ -107,9 +108,13 @@ export function runConversationIngestion(args) {
|
|
|
107
108
|
return degraded(verdict.reason, verdict.nextAction, delta.warnings);
|
|
108
109
|
}
|
|
109
110
|
}
|
|
110
|
-
// 10. Sanitize-at-store ingest with the durable checkpoint.
|
|
111
|
+
// 10. Sanitize-at-store ingest with the durable checkpoint. The text bound
|
|
112
|
+
// comes from the caller's consent-tiered policy (PRI-1179); the store's
|
|
113
|
+
// generic evidence bound stays the default when no policy is supplied.
|
|
114
|
+
const textPolicy = args.textPolicy ?? { tier: 'bounded', maxChars: TEXT_POLICY_BOUNDED_MAX_CHARS };
|
|
111
115
|
const result = ingestGovernanceObservations({
|
|
112
116
|
workspaceDir: args.workspaceDir,
|
|
117
|
+
maxVisibleTextChars: textPolicy.maxChars,
|
|
113
118
|
rollout: {
|
|
114
119
|
hostKind: args.source.hostKind,
|
|
115
120
|
rolloutIdentity: locator.sessionIdentity,
|
|
@@ -14,10 +14,9 @@
|
|
|
14
14
|
* 20,000 chars against malformed giant records; the observed
|
|
15
15
|
* truncation rate is reported at acceptance time.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* bounded storage path.
|
|
17
|
+
* PRI-1179 wires the policy into production: the host resolves the tier from its
|
|
18
|
+
* own consent record and passes it through `runConversationIngestion`, which
|
|
19
|
+
* forwards `maxChars` to the store and the core `sanitizeString` bound.
|
|
21
20
|
*/
|
|
22
21
|
export type TextPolicy = {
|
|
23
22
|
tier: 'bounded';
|
|
@@ -14,10 +14,9 @@
|
|
|
14
14
|
* 20,000 chars against malformed giant records; the observed
|
|
15
15
|
* truncation rate is reported at acceptance time.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* bounded storage path.
|
|
17
|
+
* PRI-1179 wires the policy into production: the host resolves the tier from its
|
|
18
|
+
* own consent record and passes it through `runConversationIngestion`, which
|
|
19
|
+
* forwards `maxChars` to the store and the core `sanitizeString` bound.
|
|
21
20
|
*/
|
|
22
21
|
export const TEXT_POLICY_BOUNDED_MAX_CHARS = 200;
|
|
23
22
|
export const TEXT_POLICY_FULL_MAX_CHARS = 20_000;
|
|
@@ -6,11 +6,10 @@ export declare const GOVERNANCE_PENDING_TAIL_STALE_MS: number;
|
|
|
6
6
|
/** Host taxonomy for governance observations (schema v4; PRI-1171 unification). */
|
|
7
7
|
export type GovernanceObservationHostKind = 'codex' | 'workbuddy' | 'openclaw';
|
|
8
8
|
/**
|
|
9
|
-
* PRI-1171 P2: `reasoning` joins the kind union
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* existing Codex path starts emitting it.
|
|
9
|
+
* PRI-1171 P2: `reasoning` joins the kind union (`workbuddy` decoder was the
|
|
10
|
+
* first producer). PRI-1179 added the Codex producer: only the rollout's
|
|
11
|
+
* plaintext `summary` is stored — never the encrypted reasoning body. The
|
|
12
|
+
* stored bound stays governed by the caller's text policy.
|
|
14
13
|
*/
|
|
15
14
|
export type GovernanceObservationKind = 'user_turn' | 'assistant_turn' | 'tool_call' | 'reasoning';
|
|
16
15
|
export type GovernanceObservationSource = 'live_hook' | 'transcript';
|
|
@@ -162,6 +161,12 @@ export interface IngestGovernanceObservationsInput {
|
|
|
162
161
|
readonly compactionTimestamp?: string;
|
|
163
162
|
/** Sequential rollback markers (num_turns each) decoded from the transcript delta. */
|
|
164
163
|
readonly rollbackTurns?: readonly number[];
|
|
164
|
+
/**
|
|
165
|
+
* PRI-1179: content bound for every stored `visible_text`, forwarded from the
|
|
166
|
+
* conversation-ingestion text policy (bounded 200 / full 20,000). Absent =
|
|
167
|
+
* the generic evidence bound, i.e. the pre-existing behavior.
|
|
168
|
+
*/
|
|
169
|
+
readonly maxVisibleTextChars?: number;
|
|
165
170
|
readonly now?: Date;
|
|
166
171
|
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
167
172
|
}
|
|
@@ -210,6 +215,24 @@ export interface ListGovernanceCheckpointsArgs {
|
|
|
210
215
|
readonly hostKind: GovernanceObservationHostKind;
|
|
211
216
|
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
212
217
|
}
|
|
218
|
+
export interface GovernanceUncheckpointedSession {
|
|
219
|
+
readonly rolloutIdentity: string;
|
|
220
|
+
/** MAX(observed_at) across this session's observations (TD §9 live_only stamp). */
|
|
221
|
+
readonly lastObservedAt: string;
|
|
222
|
+
readonly observationCount: number;
|
|
223
|
+
}
|
|
224
|
+
export interface ListGovernanceUncheckpointedSessionsArgs {
|
|
225
|
+
readonly workspaceDir: string;
|
|
226
|
+
readonly hostKind: GovernanceObservationHostKind;
|
|
227
|
+
/** Bounded result size (default 50, hard cap 200); `truncated` reports overflow. */
|
|
228
|
+
readonly limit?: number;
|
|
229
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
230
|
+
}
|
|
231
|
+
export type ListGovernanceUncheckpointedSessionsResult = {
|
|
232
|
+
ok: true;
|
|
233
|
+
sessions: readonly GovernanceUncheckpointedSession[];
|
|
234
|
+
truncated: boolean;
|
|
235
|
+
} | Degradation;
|
|
213
236
|
export type ListGovernanceCheckpointsResult = {
|
|
214
237
|
ok: true;
|
|
215
238
|
checkpoints: readonly GovernanceCheckpointRecord[];
|
|
@@ -222,6 +245,16 @@ export type ListGovernanceCheckpointsResult = {
|
|
|
222
245
|
* discovery (SPEC §13 / ADR-0020 §11.2).
|
|
223
246
|
*/
|
|
224
247
|
export declare function listGovernanceCheckpoints(args: ListGovernanceCheckpointsArgs): ListGovernanceCheckpointsResult;
|
|
248
|
+
/**
|
|
249
|
+
* Sessions that have observations but NO checkpoint row for this host kind
|
|
250
|
+
* (PRI-1171 ticket ⑦, TD §9). The live hook path never writes a checkpoint,
|
|
251
|
+
* so "no checkpoint" must never render as a lag anomaly: the health surface
|
|
252
|
+
* reports these as an explicit `live_only` state stamped with
|
|
253
|
+
* MAX(observed_at) instead of inventing a byte offset. Ordered by
|
|
254
|
+
* lastObservedAt descending; result bounded by `limit` with a `truncated`
|
|
255
|
+
* flag so large live-only sets stay visible without unbounded output.
|
|
256
|
+
*/
|
|
257
|
+
export declare function listGovernanceUncheckpointedSessions(args: ListGovernanceUncheckpointedSessionsArgs): ListGovernanceUncheckpointedSessionsResult;
|
|
225
258
|
export interface ListGovernanceObservationsInput {
|
|
226
259
|
readonly workspaceDir: string;
|
|
227
260
|
readonly rolloutIdentity?: string;
|
|
@@ -308,7 +308,11 @@ function upsertRollout(db, input, now) {
|
|
|
308
308
|
* committed content, mark partial, and report where the checkpoint must stop.
|
|
309
309
|
* Never overwrites committed content silently (source precedence, SPEC §10).
|
|
310
310
|
*/
|
|
311
|
-
function applyObservation({ db, rolloutRowId, input, workspaceDir }) {
|
|
311
|
+
function applyObservation({ db, rolloutRowId, input, workspaceDir, maxVisibleTextChars }) {
|
|
312
|
+
// One bound for every visible_text use in this function: the insert, the
|
|
313
|
+
// user-turn conflict comparison and the fill path must agree, otherwise a
|
|
314
|
+
// full-tier row would look like a content mismatch on the next replay.
|
|
315
|
+
const boundVisibleText = (value) => sanitizeString(value, workspaceDir, maxVisibleTextChars);
|
|
312
316
|
const byKey = db.prepare('SELECT * FROM governance_observations WHERE logical_key = ?').get(input.logicalObservationKey);
|
|
313
317
|
let existing = byKey;
|
|
314
318
|
// Cross-window tool completion by STABLE identity (P2 review): the call row
|
|
@@ -335,7 +339,7 @@ function applyObservation({ db, rolloutRowId, input, workspaceDir }) {
|
|
|
335
339
|
if (isRecord(physical))
|
|
336
340
|
return { disposition: 'duplicate' };
|
|
337
341
|
}
|
|
338
|
-
const sanitizedText = input.visibleText !== undefined ?
|
|
342
|
+
const sanitizedText = input.visibleText !== undefined ? boundVisibleText(input.visibleText) : null;
|
|
339
343
|
const facts = input.toolFacts !== undefined ? safeJson({ facts: sanitizeValue(input.toolFacts, 0, workspaceDir) }) : null;
|
|
340
344
|
db.prepare(`INSERT INTO governance_observations
|
|
341
345
|
(rollout_row_id, host_kind, rollout_identity, root_session_id, host_turn_id, kind, logical_key, transcript_record_key, source_order, source_ordinal, assistant_item_id, phase, tool_use_id, transcript_tool_call_id, visible_text, sanitized_tool_facts_json, source, completeness, retention_class, observed_at)
|
|
@@ -355,7 +359,7 @@ function applyObservation({ db, rolloutRowId, input, workspaceDir }) {
|
|
|
355
359
|
&& input.source === 'transcript'
|
|
356
360
|
&& input.visibleText !== undefined
|
|
357
361
|
&& typeof existingText === 'string'
|
|
358
|
-
&&
|
|
362
|
+
&& boundVisibleText(input.visibleText) !== existingText) {
|
|
359
363
|
db.prepare("UPDATE governance_observations SET completeness = 'partial' WHERE id = ?").run(existingId);
|
|
360
364
|
return { disposition: 'conflict', stopByteStart: input.recordByteStart };
|
|
361
365
|
}
|
|
@@ -395,7 +399,7 @@ function applyObservation({ db, rolloutRowId, input, workspaceDir }) {
|
|
|
395
399
|
fill('phase', boundedString(input.phase, MAX_TEXT_BOUND));
|
|
396
400
|
fill('tool_use_id', boundedString(input.toolUseId, MAX_TEXT_BOUND));
|
|
397
401
|
fill('transcript_tool_call_id', boundedString(input.transcriptToolCallId, MAX_TEXT_BOUND));
|
|
398
|
-
fill('visible_text', input.visibleText !== undefined ?
|
|
402
|
+
fill('visible_text', input.visibleText !== undefined ? boundVisibleText(input.visibleText) : null);
|
|
399
403
|
const incomingFacts = input.toolFacts !== undefined ? safeJson({ facts: sanitizeValue(input.toolFacts, 0, workspaceDir) }) : null;
|
|
400
404
|
// Cross-window tool completion (P1): the call row is partial and the result
|
|
401
405
|
// arrives under the same logical key from a later decode window. Merge the
|
|
@@ -550,7 +554,13 @@ export function ingestGovernanceObservations(input) {
|
|
|
550
554
|
}
|
|
551
555
|
for (const observation of input.observations) {
|
|
552
556
|
rolloutRowId = upsertRollout(db, observation, now);
|
|
553
|
-
const outcome = applyObservation({
|
|
557
|
+
const outcome = applyObservation({
|
|
558
|
+
db,
|
|
559
|
+
rolloutRowId,
|
|
560
|
+
input: observation,
|
|
561
|
+
workspaceDir: input.workspaceDir,
|
|
562
|
+
...(input.maxVisibleTextChars !== undefined ? { maxVisibleTextChars: input.maxVisibleTextChars } : {}),
|
|
563
|
+
});
|
|
554
564
|
if (outcome.disposition === 'inserted')
|
|
555
565
|
inserted += 1;
|
|
556
566
|
else if (outcome.disposition === 'enriched')
|
|
@@ -743,6 +753,54 @@ export function listGovernanceCheckpoints(args) {
|
|
|
743
753
|
close();
|
|
744
754
|
}
|
|
745
755
|
}
|
|
756
|
+
/**
|
|
757
|
+
* Sessions that have observations but NO checkpoint row for this host kind
|
|
758
|
+
* (PRI-1171 ticket ⑦, TD §9). The live hook path never writes a checkpoint,
|
|
759
|
+
* so "no checkpoint" must never render as a lag anomaly: the health surface
|
|
760
|
+
* reports these as an explicit `live_only` state stamped with
|
|
761
|
+
* MAX(observed_at) instead of inventing a byte offset. Ordered by
|
|
762
|
+
* lastObservedAt descending; result bounded by `limit` with a `truncated`
|
|
763
|
+
* flag so large live-only sets stay visible without unbounded output.
|
|
764
|
+
*/
|
|
765
|
+
export function listGovernanceUncheckpointedSessions(args) {
|
|
766
|
+
const { workspaceDir, hostKind, databaseFactory } = args;
|
|
767
|
+
const opened = openStore(workspaceDir, databaseFactory);
|
|
768
|
+
if (!('db' in opened))
|
|
769
|
+
return opened;
|
|
770
|
+
const { db, close } = opened;
|
|
771
|
+
try {
|
|
772
|
+
const limit = Math.min(Math.max(args.limit ?? 50, 1), 200);
|
|
773
|
+
const rows = db.prepare(`SELECT o.rollout_identity AS rollout_identity,
|
|
774
|
+
MAX(o.observed_at) AS last_observed_at,
|
|
775
|
+
COUNT(*) AS observation_count
|
|
776
|
+
FROM governance_observations o
|
|
777
|
+
WHERE o.host_kind = ?
|
|
778
|
+
AND o.rollout_identity NOT IN (
|
|
779
|
+
SELECT c.rollout_identity FROM governance_transcript_checkpoints c WHERE c.host_kind = ?
|
|
780
|
+
)
|
|
781
|
+
GROUP BY o.rollout_identity
|
|
782
|
+
ORDER BY last_observed_at DESC
|
|
783
|
+
LIMIT ?`).all(hostKind, hostKind, limit + 1);
|
|
784
|
+
const sessions = [];
|
|
785
|
+
for (const raw of rows.slice(0, limit)) {
|
|
786
|
+
if (!isRecord(raw))
|
|
787
|
+
continue;
|
|
788
|
+
sessions.push({
|
|
789
|
+
rolloutIdentity: String(rowField(raw, 'rollout_identity')),
|
|
790
|
+
lastObservedAt: String(rowField(raw, 'last_observed_at')),
|
|
791
|
+
observationCount: Number(rowField(raw, 'observation_count')),
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
return { ok: true, sessions, truncated: rows.length > limit };
|
|
795
|
+
}
|
|
796
|
+
catch (error) {
|
|
797
|
+
const detail = error instanceof Error ? error.message.slice(0, 160) : String(error);
|
|
798
|
+
return { ok: false, reason: `governance_live_sessions_failed:${detail}`, nextAction: 'Inspect the workspace trajectory.db; the health surface degraded without mutating anything.' };
|
|
799
|
+
}
|
|
800
|
+
finally {
|
|
801
|
+
close();
|
|
802
|
+
}
|
|
803
|
+
}
|
|
746
804
|
export function listGovernanceObservations(input) {
|
|
747
805
|
const opened = openStore(input.workspaceDir, input.databaseFactory);
|
|
748
806
|
if (!('db' in opened))
|
package/dist/index.js
CHANGED
|
@@ -284,9 +284,9 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
284
284
|
workspaceDir: event.context.workspaceDir,
|
|
285
285
|
...(roundKey !== undefined ? { roundKey } : {}),
|
|
286
286
|
...(options.adaptiveGapProvider ? {
|
|
287
|
-
async selectNativeGap(candidates) {
|
|
287
|
+
async selectNativeGap(candidates, gapOptions) {
|
|
288
288
|
try {
|
|
289
|
-
return await options.adaptiveGapProvider?.(event, candidates);
|
|
289
|
+
return await options.adaptiveGapProvider?.(event, candidates, gapOptions);
|
|
290
290
|
}
|
|
291
291
|
catch {
|
|
292
292
|
return undefined;
|
|
@@ -337,6 +337,9 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
337
337
|
// failure must not block the prompt result — it degrades to an
|
|
338
338
|
// observable warning (rc-9).
|
|
339
339
|
const emissionWarnings = [];
|
|
340
|
+
if (prompt.adaptivePacking?.source === 'native_gap' && prompt.adaptivePacking.status === 'unavailable') {
|
|
341
|
+
emissionWarnings.push(`adaptive_assembly_unavailable:${prompt.adaptivePacking.reason}`);
|
|
342
|
+
}
|
|
340
343
|
try {
|
|
341
344
|
options.events?.recordRuntimeActivationsInjected({
|
|
342
345
|
sessionId: event.context.sessionId,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ToolSemanticRegistry, type GovernanceHostKind } from '@principles/core/runtime';
|
|
1
|
+
import { type RuleHostResult, type ToolSemanticRegistry, type GovernanceHostKind } from '@principles/core/runtime';
|
|
2
2
|
import type { HostEvent, HostEventResult } from '@principles/core/host';
|
|
3
3
|
import { type RuleImplementationRuntime } from './rule-implementation-runtime.js';
|
|
4
4
|
export interface ProductionRuleContextRequest {
|
|
@@ -29,5 +29,40 @@ export interface ProductionRuleHostGateOptions {
|
|
|
29
29
|
* (shell/cmd/insert/patch/delete_file/move_file were never hinted).
|
|
30
30
|
*/
|
|
31
31
|
toolSemantics?: ToolSemanticRegistry;
|
|
32
|
+
/**
|
|
33
|
+
* PRI-1187: observation-only signal for the accepted "over-block" tradeoff.
|
|
34
|
+
*
|
|
35
|
+
* When a rule declares `affectedTools` and the current action family is NOT
|
|
36
|
+
* in that declaration, the rule is still evaluated (never skipped). This
|
|
37
|
+
* sink records one structured event per such evaluation so we can measure
|
|
38
|
+
* how much over-blocking exists and which rules cause it.
|
|
39
|
+
*
|
|
40
|
+
* Defaults ON. Silence it with `{ enabled: false }` or the environment
|
|
41
|
+
* variable `PD_AFFECTED_TOOLS_OBSERVABILITY=0`. The sink is called inside a
|
|
42
|
+
* try/catch and can never alter the decision.
|
|
43
|
+
*/
|
|
44
|
+
affectedToolsObservability?: AffectedToolsObservabilityOptions;
|
|
45
|
+
}
|
|
46
|
+
/** One observation-only "declared scope does not cover the action" record. */
|
|
47
|
+
export interface AffectedToolsMismatchEvent {
|
|
48
|
+
ruleId: string;
|
|
49
|
+
activationId: string;
|
|
50
|
+
activationMode: 'live' | 'shadow';
|
|
51
|
+
toolName: string;
|
|
52
|
+
/** Action family resolved by the ToolSemanticRegistry (write/execute/agent…). */
|
|
53
|
+
actionFamily: string;
|
|
54
|
+
/** Raw declaration, verbatim from the artifact. */
|
|
55
|
+
declaredTools: string[];
|
|
56
|
+
/** Resolved families of `declaredTools` (never empty when emitted). */
|
|
57
|
+
declaredFamilies: string[];
|
|
58
|
+
/** The rule's own decision for this call (not the merged verdict). */
|
|
59
|
+
decision: RuleHostResult['decision'];
|
|
60
|
+
hostKind?: GovernanceHostKind;
|
|
61
|
+
}
|
|
62
|
+
export interface AffectedToolsObservabilityOptions {
|
|
63
|
+
/** Defaults to `PD_AFFECTED_TOOLS_OBSERVABILITY !== '0' | 'false' | 'off'`. */
|
|
64
|
+
enabled?: boolean;
|
|
65
|
+
/** Defaults to one structured JSON line on `console.warn`. */
|
|
66
|
+
sink?: (event: AffectedToolsMismatchEvent) => void;
|
|
32
67
|
}
|
|
33
68
|
export declare function createProductionRuleHostGate(options?: ProductionRuleHostGateOptions): (event: HostEvent) => Promise<HostEventResult>;
|
|
@@ -10,6 +10,27 @@ const WARNING_LIMIT = 500;
|
|
|
10
10
|
const MAX_WARNINGS = 16;
|
|
11
11
|
const GATE_DEADLINE_MS = 3_000;
|
|
12
12
|
const ARTIFACT_CONTENT_BYTES = 512 * 1024;
|
|
13
|
+
/**
|
|
14
|
+
* Production RuleHost gate — the shared decision path for every supported host.
|
|
15
|
+
*
|
|
16
|
+
* PRI-1187 (Owner decision 2026-11-12): rules are NEVER filtered by
|
|
17
|
+
* `affectedTools`. Over-blocking (a write-only rule also observing exec) is
|
|
18
|
+
* accepted noise; under-blocking is not. `affectedTools` is the DECLARED
|
|
19
|
+
* SCOPE used by activation (`validateRuleReliability`: golden-trace tool
|
|
20
|
+
* families must be a subset of the declared families) and by approval/audit
|
|
21
|
+
* surfaces — it is NOT an execution bound.
|
|
22
|
+
*
|
|
23
|
+
* DO NOT re-add a runtime filter here. Three review rounds each found a way to
|
|
24
|
+
* skip a call the rule was validated to block: the reserved `host-liveness:`
|
|
25
|
+
* prefix, a narrow declaration with a broad implementation, and a guard that
|
|
26
|
+
* only inspected the golden trace. The decision and the follow-up ticket live
|
|
27
|
+
* in docs/proposals/PRI-1187-write-only-rule-exec-false-positive.md.
|
|
28
|
+
*
|
|
29
|
+
* The only affectedTools runtime code allowed in this file is the
|
|
30
|
+
* observation-only mismatch signal below: it logs, it never changes the
|
|
31
|
+
* evaluation set or the verdict.
|
|
32
|
+
*/
|
|
33
|
+
const AFFECTED_TOOLS_OBSERVABILITY_ENV = 'PD_AFFECTED_TOOLS_OBSERVABILITY';
|
|
13
34
|
// Check the actual imported builder, not an installed-package version string:
|
|
14
35
|
// a mixed host-runtime/core deployment must not claim input-v2 support.
|
|
15
36
|
const RECOVERY_INPUT_V2_AVAILABLE = RECOVERY_CONTROL_SURFACES
|
|
@@ -82,9 +103,73 @@ if (!baselineToolSemanticsResult.ok) {
|
|
|
82
103
|
throw new Error(`baseline tool semantic registry failed to build: ${baselineToolSemanticsResult.errors.join('; ')}`);
|
|
83
104
|
}
|
|
84
105
|
const BASELINE_TOOL_SEMANTICS = baselineToolSemanticsResult.registry;
|
|
106
|
+
/**
|
|
107
|
+
* Resolve a rule's declared scope for OBSERVATION ONLY.
|
|
108
|
+
*
|
|
109
|
+
* Returns `null` when the declaration cannot prove a mismatch (absent, not an
|
|
110
|
+
* array, empty, malformed entry, or a name the registry cannot classify). A
|
|
111
|
+
* `null` declaration therefore emits nothing — the signal must never guess,
|
|
112
|
+
* because a false positive would misdirect the follow-up work that decides
|
|
113
|
+
* whether the no-filter tradeoff stays.
|
|
114
|
+
*/
|
|
115
|
+
function resolveDeclaredFamilies(affectedTools, toolSemantics) {
|
|
116
|
+
if (!Array.isArray(affectedTools) || affectedTools.length === 0)
|
|
117
|
+
return null;
|
|
118
|
+
const tools = [];
|
|
119
|
+
const families = new Set();
|
|
120
|
+
for (const declared of affectedTools) {
|
|
121
|
+
if (typeof declared !== 'string' || declared.trim().length === 0)
|
|
122
|
+
return null;
|
|
123
|
+
const kind = toolSemantics.lookup(declared);
|
|
124
|
+
if (kind === null)
|
|
125
|
+
return null;
|
|
126
|
+
tools.push(declared);
|
|
127
|
+
families.add(kind);
|
|
128
|
+
}
|
|
129
|
+
return families.size === 0 ? null : { tools, families: [...families] };
|
|
130
|
+
}
|
|
131
|
+
function affectedToolsObservabilityDisabledByEnv() {
|
|
132
|
+
const raw = process.env[AFFECTED_TOOLS_OBSERVABILITY_ENV]?.trim().toLowerCase();
|
|
133
|
+
return raw === '0' || raw === 'false' || raw === 'off';
|
|
134
|
+
}
|
|
135
|
+
function defaultAffectedToolsSink(event) {
|
|
136
|
+
console.warn(`[PD:RuleHost] affected_tools_mismatch ${JSON.stringify(event)}`);
|
|
137
|
+
}
|
|
85
138
|
export function createProductionRuleHostGate(options = {}) {
|
|
86
139
|
const implementationRuntime = options.implementationRuntime ?? createNodeRuleImplementationRuntime();
|
|
87
140
|
const toolSemantics = options.toolSemantics ?? BASELINE_TOOL_SEMANTICS;
|
|
141
|
+
const observabilityEnabled = options.affectedToolsObservability?.enabled
|
|
142
|
+
?? !affectedToolsObservabilityDisabledByEnv();
|
|
143
|
+
const observabilitySink = options.affectedToolsObservability?.sink ?? defaultAffectedToolsSink;
|
|
144
|
+
/**
|
|
145
|
+
* PRI-1187 observation-only: record that a declared scope did not cover the
|
|
146
|
+
* action while the rule was still evaluated. MUST NOT skip, reorder, or
|
|
147
|
+
* mutate anything. Sink failures are swallowed for the same reason.
|
|
148
|
+
*/
|
|
149
|
+
const emitAffectedToolsMismatch = (candidate, observation) => {
|
|
150
|
+
if (!observabilityEnabled)
|
|
151
|
+
return;
|
|
152
|
+
if (candidate.declaredTools === null || candidate.declaredFamilies === null)
|
|
153
|
+
return;
|
|
154
|
+
if (candidate.declaredFamilies.includes(observation.actionFamily))
|
|
155
|
+
return;
|
|
156
|
+
try {
|
|
157
|
+
observabilitySink({
|
|
158
|
+
ruleId: candidate.ruleId,
|
|
159
|
+
activationId: candidate.implId,
|
|
160
|
+
activationMode: candidate.activationMode,
|
|
161
|
+
toolName: observation.toolName,
|
|
162
|
+
actionFamily: observation.actionFamily,
|
|
163
|
+
declaredTools: candidate.declaredTools,
|
|
164
|
+
declaredFamilies: candidate.declaredFamilies,
|
|
165
|
+
decision: observation.decision,
|
|
166
|
+
...(options.hostKind !== undefined ? { hostKind: options.hostKind } : {}),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
// Observation must never affect enforcement.
|
|
171
|
+
}
|
|
172
|
+
};
|
|
88
173
|
return async (event) => {
|
|
89
174
|
const startedAt = Date.now();
|
|
90
175
|
const warnings = [];
|
|
@@ -521,7 +606,10 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
521
606
|
continue;
|
|
522
607
|
}
|
|
523
608
|
const fallbackMeta = { name: activationId, version: '1', ruleId, coversCondition: 'all' };
|
|
524
|
-
|
|
609
|
+
// PRI-1187: resolved for the observation-only mismatch signal; it
|
|
610
|
+
// is attached to the candidate but never filters the batch.
|
|
611
|
+
const declaredScope = resolveDeclaredFamilies(content.affectedTools, toolSemantics);
|
|
612
|
+
candidates.push({ implId: activationId, ruleId, principleId, meta: isRuleMeta(content.meta) ? content.meta : fallbackMeta, source: content.implementationCode, activationMode, declaredTools: declaredScope?.tools ?? null, declaredFamilies: declaredScope?.families ?? null });
|
|
525
613
|
}
|
|
526
614
|
catch (error) {
|
|
527
615
|
addWarning(warnings, `implementation_unhealthy: ${error instanceof Error ? error.message : String(error)}`, 'fix the RuleCode and reactivate the rule');
|
|
@@ -605,6 +693,7 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
605
693
|
const shadowResult = normalized.matched
|
|
606
694
|
? { ...normalized, ruleId: candidate.ruleId, principleId: candidate.principleId }
|
|
607
695
|
: normalized;
|
|
696
|
+
emitAffectedToolsMismatch(candidate, { decision: shadowResult.decision, actionFamily: canonicalKind, toolName: input.toolName });
|
|
608
697
|
shadowEvaluations.push({
|
|
609
698
|
toolName: input.toolName,
|
|
610
699
|
filePath: action.normalizedPath,
|
|
@@ -645,6 +734,7 @@ export function createProductionRuleHostGate(options = {}) {
|
|
|
645
734
|
: normalized;
|
|
646
735
|
implementations.push({ ...candidate, evaluate: () => validatedResult });
|
|
647
736
|
liveEvaluatedResults.push(validatedResult);
|
|
737
|
+
emitAffectedToolsMismatch(candidate, { decision: validatedResult.decision, actionFamily: canonicalKind, toolName: input.toolName });
|
|
648
738
|
}
|
|
649
739
|
const result = mergeDecisions(implementations, hostInput, {
|
|
650
740
|
warn(message) { addWarning(warnings, message, 'inspect the unhealthy activation and RuleCode output'); },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"lint": "eslint \"src/**/*.ts\""
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@principles/core": "^7.
|
|
34
|
+
"@principles/core": "^7.5.0",
|
|
35
35
|
"@principles/install-layout": "^0.8.0",
|
|
36
36
|
"better-sqlite3": "^13.0.3",
|
|
37
37
|
"js-yaml": "^5.4.3"
|
|
@@ -49,5 +49,5 @@
|
|
|
49
49
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
50
50
|
},
|
|
51
51
|
"license": "Apache-2.0",
|
|
52
|
-
"gitHead": "
|
|
52
|
+
"gitHead": "95d49f9eae5bf499fc8e4f36fecb0ad5a490f05b"
|
|
53
53
|
}
|