@principles/host-runtime 3.4.1 → 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 +13 -0
- package/dist/active-principle-prompt.js +87 -10
- package/dist/adaptive-decision-protocol.d.ts +129 -0
- package/dist/adaptive-decision-protocol.js +176 -0
- package/dist/adaptive-priority-provider.d.ts +38 -13
- package/dist/adaptive-priority-provider.js +70 -66
- package/dist/adaptive-selection.d.ts +71 -64
- package/dist/adaptive-selection.js +220 -329
- package/dist/adaptive-skip-decision.d.ts +26 -14
- package/dist/adaptive-skip-decision.js +33 -29
- package/dist/codex-disclosure.d.ts +12 -7
- package/dist/codex-disclosure.js +12 -7
- package/dist/codex-rule-context-provider.js +4 -1
- 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 +73 -1
- package/dist/governance-observation-store.js +251 -14
- package/dist/governance-signal-admission.d.ts +19 -3
- package/dist/governance-signal-admission.js +12 -4
- package/dist/host-tool-declaration.d.ts +18 -2
- package/dist/host-tool-declaration.js +67 -11
- package/dist/host-tool-semantic-resolver.d.ts +7 -0
- package/dist/host-tool-semantic-resolver.js +22 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +17 -0
- package/dist/production-rulehost-gate.d.ts +36 -1
- package/dist/production-rulehost-gate.js +106 -4
- package/dist/trajectory-retention.d.ts +147 -0
- package/dist/trajectory-retention.js +907 -0
- package/package.json +4 -4
|
@@ -68,6 +68,7 @@ export interface ActivePrinciplePromptResult {
|
|
|
68
68
|
injectedExpectationsOverflow?: number;
|
|
69
69
|
}
|
|
70
70
|
export interface AdaptivePackingReport {
|
|
71
|
+
source?: 'native_gap';
|
|
71
72
|
status: 'target_present' | 'prioritized' | 'unavailable';
|
|
72
73
|
reason?: string;
|
|
73
74
|
targetActivationId: string;
|
|
@@ -76,6 +77,7 @@ export interface AdaptivePackingReport {
|
|
|
76
77
|
displacedActivationIds: string[];
|
|
77
78
|
/** Internal return-boundary checks; these snapshots are not delivery evidence. */
|
|
78
79
|
targetSnapshot?: ActivatedPrinciple;
|
|
80
|
+
displacedSnapshot?: ActivatedPrinciple;
|
|
79
81
|
targetBody?: string;
|
|
80
82
|
nativeBaseline?: ActivePrinciplePromptResult;
|
|
81
83
|
deadlineAt?: number;
|
|
@@ -202,6 +204,10 @@ export declare function packSharedDirectives(input: {
|
|
|
202
204
|
/** Fair rotation continues past a non-fit; legacy FIFO stops at the first one. */
|
|
203
205
|
continueOnNonFit: boolean;
|
|
204
206
|
}): SharedDirectivePacking;
|
|
207
|
+
export interface AdaptiveGapOptions {
|
|
208
|
+
readonly excludedByBudget: boolean;
|
|
209
|
+
readonly replacementByActivationId: ReadonlyMap<string, ActivatedPrinciple>;
|
|
210
|
+
}
|
|
205
211
|
export declare function buildActivePrinciplePromptContext(input: {
|
|
206
212
|
workspaceDir: string;
|
|
207
213
|
/**
|
|
@@ -223,6 +229,13 @@ export declare function buildActivePrinciplePromptContext(input: {
|
|
|
223
229
|
artifactId: string;
|
|
224
230
|
activationId: string;
|
|
225
231
|
};
|
|
232
|
+
/** Select only from omitted principles with a feasible plan in the current budget. */
|
|
233
|
+
selectNativeGap?: (candidates: readonly ActivatedPrinciple[], options: AdaptiveGapOptions) => Promise<{
|
|
234
|
+
artifactId: string;
|
|
235
|
+
activationId: string;
|
|
236
|
+
signal?: AbortSignal;
|
|
237
|
+
deadlineAt?: number;
|
|
238
|
+
} | undefined>;
|
|
226
239
|
/**
|
|
227
240
|
* PRI-1140 (Owner supplementary condition): additive-only adaptive packing.
|
|
228
241
|
* Only meaningful together with `adaptivePriority`. When true, the
|
|
@@ -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,22 +346,68 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
345
346
|
};
|
|
346
347
|
const nativePacking = pack(nativeScanOrder);
|
|
347
348
|
const nativeResult = makeResult(nativePacking, principles);
|
|
348
|
-
|
|
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
|
+
}
|
|
387
|
+
const priority = input.adaptivePriority ?? gapPriority;
|
|
349
388
|
if (priority === undefined)
|
|
350
389
|
return nativeResult;
|
|
390
|
+
const signal = gapPriority?.signal ?? input.signal ?? new AbortController().signal;
|
|
391
|
+
const deadlineAt = gapPriority?.deadlineAt ?? input.deadlineAt;
|
|
392
|
+
const outgoing = gapPriority ? replacements.get(priority.activationId) : undefined;
|
|
393
|
+
const additiveOnly = (gapPriority !== undefined && outgoing === undefined) || input.additiveOnly === true;
|
|
351
394
|
const report = (status, reason, displacedActivationIds = []) => ({
|
|
352
395
|
status,
|
|
396
|
+
...(gapPriority ? { source: 'native_gap' } : {}),
|
|
353
397
|
...(reason ? { reason } : {}),
|
|
354
398
|
targetActivationId: typeof priority.activationId === 'string' ? priority.activationId : '',
|
|
355
399
|
targetArtifactId: typeof priority.artifactId === 'string' ? priority.artifactId : '',
|
|
356
400
|
...(input.hookInvocationId ? { hookInvocationId: input.hookInvocationId } : {}),
|
|
357
401
|
displacedActivationIds,
|
|
358
402
|
});
|
|
403
|
+
if (gapPriority && (signal.aborted || (deadlineAt !== undefined && Date.now() >= deadlineAt))) {
|
|
404
|
+
return { ...nativeResult, adaptivePacking: report('unavailable', 'deadline') };
|
|
405
|
+
}
|
|
359
406
|
const nativeTargetMatches = principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
360
407
|
const [nativeTarget] = nativeTargetMatches;
|
|
361
408
|
const baselineHasTarget = nativePacking.included.some((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
362
409
|
const withoutTarget = (reason) => {
|
|
363
|
-
if (nativeTargetMatches.length !== 1 || !nativeTarget)
|
|
410
|
+
if (gapPriority || nativeTargetMatches.length !== 1 || !nativeTarget)
|
|
364
411
|
return { ...nativeResult, adaptivePacking: report('unavailable', reason) };
|
|
365
412
|
const targetPrincipleId = nativeTarget.principleId;
|
|
366
413
|
const safePrinciples = principles.filter((principle) => principle.principleId !== targetPrincipleId);
|
|
@@ -381,6 +428,9 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
381
428
|
if (principles.filter((principle) => principle.principleId === nativeTarget.principleId).length !== 1) {
|
|
382
429
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_ambiguous') };
|
|
383
430
|
}
|
|
431
|
+
if (gapPriority && !feasible.includes(nativeTarget)) {
|
|
432
|
+
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_not_in_feasible_gap') };
|
|
433
|
+
}
|
|
384
434
|
const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true, noBusyWait: true });
|
|
385
435
|
const authorizedMatches = authorityRead.principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
|
|
386
436
|
const [authorizedTarget] = authorizedMatches;
|
|
@@ -402,12 +452,12 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
402
452
|
|| authorizedTarget.artifactContentSha256 !== nativeTarget.artifactContentSha256) {
|
|
403
453
|
return withoutTarget('target_changed');
|
|
404
454
|
}
|
|
405
|
-
const signal = input.signal ?? new AbortController().signal;
|
|
406
455
|
const targetRendered = renderPrinciplesToDirectives([nativeTarget], new Set([nativeTarget.principleId]), { escapeFn: escapeXml });
|
|
407
456
|
const targetBody = targetRendered.slice(targetRendered.indexOf('<directive '), targetRendered.indexOf('</directive>') + '</directive>'.length);
|
|
408
457
|
const prepared = (status, displaced = []) => ({
|
|
409
458
|
...report(status, undefined, displaced), targetSnapshot: authorizedTarget, targetBody,
|
|
410
|
-
|
|
459
|
+
...(outgoing ? { displacedSnapshot: outgoing } : {}),
|
|
460
|
+
nativeBaseline: nativeResult, ...(deadlineAt !== undefined ? { deadlineAt } : {}),
|
|
411
461
|
});
|
|
412
462
|
if (baselineHasTarget) {
|
|
413
463
|
const stillValid = await revalidateAdaptivePrinciple(input.workspaceDir, authorizedTarget, signal);
|
|
@@ -415,13 +465,21 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
415
465
|
return withoutTarget('target_changed');
|
|
416
466
|
return { ...nativeResult, adaptivePacking: prepared('target_present') };
|
|
417
467
|
}
|
|
418
|
-
|
|
419
|
-
const
|
|
420
|
-
|
|
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)]);
|
|
421
480
|
if (!prioritizedPacking.included.some((principle) => principle.principleId === nativeTarget.principleId)) {
|
|
422
481
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_does_not_fit') };
|
|
423
482
|
}
|
|
424
|
-
const mandatoryIds = input.mandatoryPrincipleIds ?? [];
|
|
425
483
|
if (!Array.isArray(mandatoryIds) || mandatoryIds.some((id) => typeof id !== 'string')
|
|
426
484
|
|| mandatoryIds.some((id) => !prioritizedPacking.included.some((principle) => principle.principleId === id))) {
|
|
427
485
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'mandatory_constraint_displaced') };
|
|
@@ -430,19 +488,38 @@ export async function buildActivePrinciplePromptContext(input) {
|
|
|
430
488
|
const displacedActivationIds = nativePacking.included
|
|
431
489
|
.filter((principle) => !prioritizedActivationIds.has(principle.activationId))
|
|
432
490
|
.map((principle) => principle.activationId);
|
|
491
|
+
if (outgoing && (displacedActivationIds.length !== 1 || displacedActivationIds[0] !== outgoing.activationId)) {
|
|
492
|
+
return withoutTarget('unexpected_replacement');
|
|
493
|
+
}
|
|
433
494
|
// PRI-1140: an additive-only target may never squeeze out content the
|
|
434
495
|
// native baseline already assembled. Decided BEFORE the revalidation read so
|
|
435
496
|
// a refused placement costs no further I/O; the would-be displacement is the
|
|
436
497
|
// recorded reason (bounded like the other diagnostic id lists).
|
|
437
|
-
if (
|
|
498
|
+
if (additiveOnly && displacedActivationIds.length > 0) {
|
|
438
499
|
return {
|
|
439
500
|
...nativeResult,
|
|
440
501
|
adaptivePacking: report('unavailable', 'would_displace_native_assembly', displacedActivationIds.slice(0, MAX_SHARED_DIAGNOSTIC_IDS)),
|
|
441
502
|
};
|
|
442
503
|
}
|
|
443
|
-
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
|
+
}
|
|
444
511
|
if (!stillValid)
|
|
445
512
|
return { ...nativeResult, adaptivePacking: report('unavailable', 'target_changed') };
|
|
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
|
+
}
|
|
446
523
|
const result = makeResult(prioritizedPacking, principles, prepared('prioritized', displacedActivationIds));
|
|
447
524
|
// Adaptive assembly is deliberately limited to the existing renderer's Native budget cap.
|
|
448
525
|
return result;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1182 — Adaptive Activation: the real Decisions scoring protocol.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from the already-verified lab implementation
|
|
5
|
+
* (`scripts/dev/adaptive-selector-lab/diagnostic.mjs`): one POST with
|
|
6
|
+
* `{model, state, questions, provider}`, one `{model, answers}` response.
|
|
7
|
+
*
|
|
8
|
+
* The difference from the lab experiment is the QUESTION SET: the lab asked
|
|
9
|
+
* four task-level questions, while production asks one independent
|
|
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.
|
|
14
|
+
*
|
|
15
|
+
* Everything here is pure: no I/O, no clock, no transport. The caller owns
|
|
16
|
+
* scheduling, cancellation and diagnostics.
|
|
17
|
+
*/
|
|
18
|
+
export declare const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
|
|
19
|
+
export declare const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = "insufficient_context";
|
|
20
|
+
/** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
|
|
21
|
+
export declare const ADAPTIVE_DECISION_CRITERIA: {
|
|
22
|
+
readonly version: 'v2-20261112';
|
|
23
|
+
/** A candidate must reach this independent score to be eligible. */
|
|
24
|
+
readonly selectThreshold: 0.7;
|
|
25
|
+
/** Above this "information is insufficient" score, PD refuses to select. */
|
|
26
|
+
readonly insufficientThreshold: 0.6;
|
|
27
|
+
};
|
|
28
|
+
export interface DecisionQuestion {
|
|
29
|
+
readonly type: 'noul';
|
|
30
|
+
readonly instructions: string;
|
|
31
|
+
}
|
|
32
|
+
export type DecisionQuestions = Record<string, DecisionQuestion>;
|
|
33
|
+
export interface DecisionRequestEnvelope {
|
|
34
|
+
readonly model: string;
|
|
35
|
+
readonly state: string;
|
|
36
|
+
readonly questions: DecisionQuestions;
|
|
37
|
+
readonly provider?: {
|
|
38
|
+
readonly only: readonly string[];
|
|
39
|
+
readonly allow_fallbacks: false;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export type DecisionProtocolError = 'DECISION_MODEL_MISMATCH' | 'DECISION_PROVIDER_MISMATCH' | 'DECISION_OUTPUT_INVALID' | 'DECISION_QUESTION_MISMATCH' | 'DECISION_SCORE_INVALID' | 'INPUT_REFUSED';
|
|
43
|
+
export interface BuildDecisionRequestInput {
|
|
44
|
+
readonly model: string;
|
|
45
|
+
readonly provider?: string;
|
|
46
|
+
readonly currentInstruction: string;
|
|
47
|
+
readonly priorMessages: readonly {
|
|
48
|
+
readonly text: string;
|
|
49
|
+
readonly source: string;
|
|
50
|
+
readonly index: number;
|
|
51
|
+
}[];
|
|
52
|
+
readonly candidates: readonly {
|
|
53
|
+
readonly ref: string;
|
|
54
|
+
readonly text: string;
|
|
55
|
+
readonly digest: string;
|
|
56
|
+
readonly replaces?: string;
|
|
57
|
+
}[];
|
|
58
|
+
/** Bounded by the caller; a request larger than this is refused locally. */
|
|
59
|
+
readonly maxPayloadChars: number;
|
|
60
|
+
}
|
|
61
|
+
export type BuildDecisionRequestResult = {
|
|
62
|
+
readonly ok: true;
|
|
63
|
+
readonly body: DecisionRequestEnvelope;
|
|
64
|
+
readonly questionIds: readonly string[];
|
|
65
|
+
} | {
|
|
66
|
+
readonly ok: false;
|
|
67
|
+
readonly reason: DecisionProtocolError;
|
|
68
|
+
};
|
|
69
|
+
export declare function candidateQuestionId(ref: string): string;
|
|
70
|
+
/**
|
|
71
|
+
* One question per candidate (its applicability condition) plus one
|
|
72
|
+
* "insufficient context" question. Instructions refer to the snapshot by ref;
|
|
73
|
+
* the candidate text itself travels once, in `state`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function buildDecisionQuestions(candidates: readonly {
|
|
76
|
+
readonly ref: string;
|
|
77
|
+
readonly text: string;
|
|
78
|
+
readonly replaces?: string;
|
|
79
|
+
}[]): DecisionQuestions;
|
|
80
|
+
export declare function buildDecisionRequest(input: BuildDecisionRequestInput): BuildDecisionRequestResult;
|
|
81
|
+
/**
|
|
82
|
+
* Model identity is exact against an explicit allowlist when one is frozen
|
|
83
|
+
* (the acceptance batch does this). Otherwise one bounded alias class is
|
|
84
|
+
* accepted: a `:free` tag may be absent, and a dated canonical slug
|
|
85
|
+
* (`<base>-YYYYMMDD`) is accepted — the two aliases the lab verified.
|
|
86
|
+
*
|
|
87
|
+
* An unregistered DATE is never accepted through the allowlist path: the
|
|
88
|
+
* observed id must be one of the frozen strings, so a same-prefix slug with a
|
|
89
|
+
* different date is a mismatch.
|
|
90
|
+
*/
|
|
91
|
+
export declare function isDecisionModelIdentity(configured: string, observed: string, allowedResponseModels?: readonly string[]): boolean;
|
|
92
|
+
export type DecisionValidationResult = {
|
|
93
|
+
readonly ok: true;
|
|
94
|
+
readonly scores: Readonly<Record<string, number>>;
|
|
95
|
+
} | {
|
|
96
|
+
readonly ok: false;
|
|
97
|
+
readonly reason: DecisionProtocolError;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Validates model identity, provider identity (when configured), completeness
|
|
101
|
+
* of the exact question set, and every score range. Any missing, extra or
|
|
102
|
+
* malformed answer is a rejected turn — never a partial score table.
|
|
103
|
+
*/
|
|
104
|
+
export declare function validateDecisionResponse(value: unknown, expected: {
|
|
105
|
+
readonly model: string;
|
|
106
|
+
readonly questionIds: readonly string[];
|
|
107
|
+
readonly provider?: string;
|
|
108
|
+
/** Frozen exact response-model allowlist. Present = exact membership only. */
|
|
109
|
+
readonly allowedResponseModels?: readonly string[];
|
|
110
|
+
}): DecisionValidationResult;
|
|
111
|
+
export type DecisionOutcome = {
|
|
112
|
+
readonly status: 'selected';
|
|
113
|
+
readonly ref: string;
|
|
114
|
+
readonly reason: 'selected';
|
|
115
|
+
readonly scores: Readonly<Record<string, number>>;
|
|
116
|
+
} | {
|
|
117
|
+
readonly status: 'none_applicable' | 'uncertain';
|
|
118
|
+
readonly ref: null;
|
|
119
|
+
readonly reason: 'below_selection_threshold' | 'candidate_tied' | 'information_insufficient';
|
|
120
|
+
readonly scores: Readonly<Record<string, number>>;
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Local adjudication of the INDEPENDENT condition scores. Order matters:
|
|
124
|
+
* insufficient information first (it invalidates any candidate ranking), then
|
|
125
|
+
* the applicability threshold. An exact tie leaves no unique winner.
|
|
126
|
+
*/
|
|
127
|
+
export declare function adjudicateDecision(scores: Readonly<Record<string, number>>, candidates: readonly {
|
|
128
|
+
readonly ref: string;
|
|
129
|
+
}[], criteria?: typeof ADAPTIVE_DECISION_CRITERIA): DecisionOutcome;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1182 — Adaptive Activation: the real Decisions scoring protocol.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from the already-verified lab implementation
|
|
5
|
+
* (`scripts/dev/adaptive-selector-lab/diagnostic.mjs`): one POST with
|
|
6
|
+
* `{model, state, questions, provider}`, one `{model, answers}` response.
|
|
7
|
+
*
|
|
8
|
+
* The difference from the lab experiment is the QUESTION SET: the lab asked
|
|
9
|
+
* four task-level questions, while production asks one independent
|
|
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.
|
|
14
|
+
*
|
|
15
|
+
* Everything here is pure: no I/O, no clock, no transport. The caller owns
|
|
16
|
+
* scheduling, cancellation and diagnostics.
|
|
17
|
+
*/
|
|
18
|
+
export const ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS = 600;
|
|
19
|
+
export const ADAPTIVE_DECISION_INSUFFICIENT_QUESTION = 'insufficient_context';
|
|
20
|
+
/** Preset applicability and context guards. Scores are model judgments, not calibrated probabilities. */
|
|
21
|
+
export const ADAPTIVE_DECISION_CRITERIA = {
|
|
22
|
+
version: 'v2-20261112',
|
|
23
|
+
/** A candidate must reach this independent score to be eligible. */
|
|
24
|
+
selectThreshold: 0.7,
|
|
25
|
+
/** Above this "information is insufficient" score, PD refuses to select. */
|
|
26
|
+
insufficientThreshold: 0.6,
|
|
27
|
+
};
|
|
28
|
+
export function candidateQuestionId(ref) {
|
|
29
|
+
return `candidate_${ref}`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* One question per candidate (its applicability condition) plus one
|
|
33
|
+
* "insufficient context" question. Instructions refer to the snapshot by ref;
|
|
34
|
+
* the candidate text itself travels once, in `state`.
|
|
35
|
+
*/
|
|
36
|
+
export function buildDecisionQuestions(candidates) {
|
|
37
|
+
const questions = {};
|
|
38
|
+
for (const candidate of candidates) {
|
|
39
|
+
questions[candidateQuestionId(candidate.ref)] = {
|
|
40
|
+
type: 'noul',
|
|
41
|
+
instructions: `依据 currentInstruction 判断用户现在要做什么,并比较 state.candidates。候选 ${candidate.ref} 是否直接适用于这项任务,且最能改善下一步具体行动?`
|
|
42
|
+
+ '能避免当前任务的具体失误或补上关键步骤时给高分。仅主题相近、重复用户已明确的要求、或对下一步没有实质帮助时给低分。没有合适候选时全部给低分。'
|
|
43
|
+
+ (candidate.replaces === undefined ? '' : ' 此方案会移除该候选在 state 中的 replaces 原则。只有候选对当前任务明显更有帮助,且移除原原则不会丢掉当前仍需的约束时才给高分;拿不准则给低分。'),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
questions[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION] = {
|
|
47
|
+
type: 'noul',
|
|
48
|
+
instructions: '信息不足:当前输入是否缺少判断候选是否适用所需的信息(例如只有确认词、指代不明、'
|
|
49
|
+
+ '不知道在问哪一个任务)?信息不足时概率接近 1;能够明确判断时为 0。',
|
|
50
|
+
};
|
|
51
|
+
return questions;
|
|
52
|
+
}
|
|
53
|
+
export function buildDecisionRequest(input) {
|
|
54
|
+
if (input.candidates.length === 0) {
|
|
55
|
+
return { ok: false, reason: 'INPUT_REFUSED' };
|
|
56
|
+
}
|
|
57
|
+
const questions = buildDecisionQuestions(input.candidates);
|
|
58
|
+
const state = {
|
|
59
|
+
currentInstruction: input.currentInstruction,
|
|
60
|
+
priorMessages: input.priorMessages,
|
|
61
|
+
candidates: input.candidates.map((candidate) => ({
|
|
62
|
+
ref: candidate.ref,
|
|
63
|
+
text: candidate.text,
|
|
64
|
+
digest: candidate.digest,
|
|
65
|
+
...(candidate.replaces !== undefined ? { replaces: candidate.replaces } : {}),
|
|
66
|
+
})),
|
|
67
|
+
};
|
|
68
|
+
const body = {
|
|
69
|
+
model: input.model,
|
|
70
|
+
state: JSON.stringify(state),
|
|
71
|
+
questions,
|
|
72
|
+
...(input.provider
|
|
73
|
+
? { provider: { only: [input.provider], allow_fallbacks: false } }
|
|
74
|
+
: {}),
|
|
75
|
+
};
|
|
76
|
+
if (JSON.stringify({ state: body.state, questions }).length > input.maxPayloadChars) {
|
|
77
|
+
return { ok: false, reason: 'INPUT_REFUSED' };
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
ok: true,
|
|
81
|
+
body,
|
|
82
|
+
questionIds: [...Object.keys(questions)],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** rc-1/rc-2: parsed JSON is unknown until these guards pass. */
|
|
86
|
+
function isRecord(value) {
|
|
87
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Model identity is exact against an explicit allowlist when one is frozen
|
|
91
|
+
* (the acceptance batch does this). Otherwise one bounded alias class is
|
|
92
|
+
* accepted: a `:free` tag may be absent, and a dated canonical slug
|
|
93
|
+
* (`<base>-YYYYMMDD`) is accepted — the two aliases the lab verified.
|
|
94
|
+
*
|
|
95
|
+
* An unregistered DATE is never accepted through the allowlist path: the
|
|
96
|
+
* observed id must be one of the frozen strings, so a same-prefix slug with a
|
|
97
|
+
* different date is a mismatch.
|
|
98
|
+
*/
|
|
99
|
+
export function isDecisionModelIdentity(configured, observed, allowedResponseModels) {
|
|
100
|
+
if (allowedResponseModels !== undefined && allowedResponseModels.length > 0) {
|
|
101
|
+
return allowedResponseModels.includes(observed);
|
|
102
|
+
}
|
|
103
|
+
if (configured === observed)
|
|
104
|
+
return true;
|
|
105
|
+
const base = configured.endsWith(':free') ? configured.slice(0, -':free'.length) : configured;
|
|
106
|
+
if (base === observed)
|
|
107
|
+
return true;
|
|
108
|
+
return new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}-\\d{8}$`, 'u').test(observed);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Validates model identity, provider identity (when configured), completeness
|
|
112
|
+
* of the exact question set, and every score range. Any missing, extra or
|
|
113
|
+
* malformed answer is a rejected turn — never a partial score table.
|
|
114
|
+
*/
|
|
115
|
+
export function validateDecisionResponse(value, expected) {
|
|
116
|
+
if (!isRecord(value))
|
|
117
|
+
return { ok: false, reason: 'DECISION_OUTPUT_INVALID' };
|
|
118
|
+
const { model } = value;
|
|
119
|
+
if (typeof model !== 'string'
|
|
120
|
+
|| !isDecisionModelIdentity(expected.model, model, expected.allowedResponseModels)) {
|
|
121
|
+
return { ok: false, reason: 'DECISION_MODEL_MISMATCH' };
|
|
122
|
+
}
|
|
123
|
+
if (expected.provider !== undefined) {
|
|
124
|
+
const { provider } = value;
|
|
125
|
+
if (provider !== undefined
|
|
126
|
+
&& (typeof provider !== 'string' || provider.toLowerCase() !== expected.provider.toLowerCase())) {
|
|
127
|
+
return { ok: false, reason: 'DECISION_PROVIDER_MISMATCH' };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const { answers } = value;
|
|
131
|
+
if (!isRecord(answers))
|
|
132
|
+
return { ok: false, reason: 'DECISION_OUTPUT_INVALID' };
|
|
133
|
+
const answerKeys = Object.keys(answers);
|
|
134
|
+
if (answerKeys.length !== expected.questionIds.length
|
|
135
|
+
|| expected.questionIds.some((id) => !Object.hasOwn(answers, id))) {
|
|
136
|
+
return { ok: false, reason: 'DECISION_QUESTION_MISMATCH' };
|
|
137
|
+
}
|
|
138
|
+
const scores = {};
|
|
139
|
+
for (const id of expected.questionIds) {
|
|
140
|
+
const answer = answers[id];
|
|
141
|
+
if (!isRecord(answer) || answer.type !== 'noul') {
|
|
142
|
+
return { ok: false, reason: 'DECISION_OUTPUT_INVALID' };
|
|
143
|
+
}
|
|
144
|
+
const { noul } = answer;
|
|
145
|
+
if (typeof noul !== 'number' || !Number.isFinite(noul) || noul < 0 || noul > 1) {
|
|
146
|
+
return { ok: false, reason: 'DECISION_SCORE_INVALID' };
|
|
147
|
+
}
|
|
148
|
+
scores[id] = noul;
|
|
149
|
+
}
|
|
150
|
+
return { ok: true, scores };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Local adjudication of the INDEPENDENT condition scores. Order matters:
|
|
154
|
+
* insufficient information first (it invalidates any candidate ranking), then
|
|
155
|
+
* the applicability threshold. An exact tie leaves no unique winner.
|
|
156
|
+
*/
|
|
157
|
+
export function adjudicateDecision(scores, candidates, criteria = ADAPTIVE_DECISION_CRITERIA) {
|
|
158
|
+
const insufficient = scores[ADAPTIVE_DECISION_INSUFFICIENT_QUESTION];
|
|
159
|
+
if (insufficient !== undefined && insufficient >= criteria.insufficientThreshold) {
|
|
160
|
+
return { status: 'uncertain', ref: null, reason: 'information_insufficient', scores };
|
|
161
|
+
}
|
|
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);
|
|
168
|
+
const [top, runnerUp] = ranked;
|
|
169
|
+
if (!top || top.score < criteria.selectThreshold) {
|
|
170
|
+
return { status: 'none_applicable', ref: null, reason: 'below_selection_threshold', scores };
|
|
171
|
+
}
|
|
172
|
+
if (runnerUp && top.score === runnerUp.score) {
|
|
173
|
+
return { status: 'uncertain', ref: null, reason: 'candidate_tied', scores };
|
|
174
|
+
}
|
|
175
|
+
return { status: 'selected', ref: top.ref, reason: 'selected', scores };
|
|
176
|
+
}
|
|
@@ -9,10 +9,17 @@
|
|
|
9
9
|
* mapping. Any missing identity/config/model keeps the Native path unchanged.
|
|
10
10
|
*/
|
|
11
11
|
import type { HostEvent } from '@principles/core/host';
|
|
12
|
-
import type { PdConfig } from '@principles/core/runtime';
|
|
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";
|
|
17
|
+
export type AdaptiveActivationFlag = typeof ADAPTIVE_ACTIVATION_FLAG | 'host.workbuddy.adaptive_activation' | 'host.openclaw.adaptive_activation';
|
|
18
|
+
/**
|
|
19
|
+
* PRI-1182 §2: time kept back from the host window for the principle assembly
|
|
20
|
+
* and the hook's own output. Selection never spends the reserve.
|
|
21
|
+
*/
|
|
22
|
+
export declare const ADAPTIVE_OUTPUT_RESERVE_MS = 200;
|
|
16
23
|
export interface AdaptivePrioritySelection {
|
|
17
24
|
readonly artifactId: string;
|
|
18
25
|
readonly activationId: string;
|
|
@@ -20,7 +27,7 @@ export interface AdaptivePrioritySelection {
|
|
|
20
27
|
readonly deadlineAt?: number;
|
|
21
28
|
readonly signal?: AbortSignal;
|
|
22
29
|
}
|
|
23
|
-
export type AdaptivePriorityProvider = (event: HostEvent) => Promise<AdaptivePrioritySelection | undefined>;
|
|
30
|
+
export type AdaptivePriorityProvider = (event: HostEvent, candidates: readonly ActivatedPrinciple[], options: AdaptiveGapOptions) => Promise<AdaptivePrioritySelection | undefined>;
|
|
24
31
|
export interface AdaptiveActivationReadiness {
|
|
25
32
|
readonly readiness: 'ready' | 'disabled' | 'needs_setup';
|
|
26
33
|
readonly reason: string;
|
|
@@ -29,30 +36,42 @@ export interface AdaptiveActivationReadiness {
|
|
|
29
36
|
export type AdaptiveModelResolution = {
|
|
30
37
|
readonly ok: true;
|
|
31
38
|
readonly model: AdaptiveSelectionModel;
|
|
32
|
-
readonly profileId: string;
|
|
33
39
|
} | {
|
|
34
40
|
readonly ok: false;
|
|
41
|
+
readonly readiness: 'disabled' | 'needs_setup';
|
|
35
42
|
readonly reason: string;
|
|
36
43
|
readonly nextAction: string;
|
|
37
44
|
};
|
|
38
|
-
export declare function resolveAdaptiveSelectionModel(config: PdConfig, env: Record<string, string | undefined
|
|
45
|
+
export declare function resolveAdaptiveSelectionModel(config: PdConfig, env: Record<string, string | undefined>, flag?: AdaptiveActivationFlag): AdaptiveModelResolution;
|
|
39
46
|
export interface AdaptiveSelectionDiagnosticLine {
|
|
40
47
|
readonly status: string;
|
|
41
48
|
readonly reason: string;
|
|
42
49
|
readonly stage: string;
|
|
43
50
|
readonly sends: number;
|
|
51
|
+
readonly requestSentAt: number | null;
|
|
44
52
|
readonly firstByteAt: number | null;
|
|
45
53
|
readonly generationEndedAt: number | null;
|
|
54
|
+
readonly validatedAt: number | null;
|
|
46
55
|
readonly cancelledAt: number | null;
|
|
47
56
|
readonly httpStatus: number | null;
|
|
48
57
|
readonly finishReason: string;
|
|
58
|
+
/** Observed response model; null when no body was parsed. */
|
|
59
|
+
readonly modelObserved: string | null;
|
|
60
|
+
/** Observed response provider; null when absent or no body was parsed. */
|
|
61
|
+
readonly providerObserved: string | null;
|
|
62
|
+
/** Bounded local adjudication evidence (ids only, never prompt text). */
|
|
63
|
+
readonly decision: {
|
|
64
|
+
readonly status: string;
|
|
65
|
+
readonly ref: string | null;
|
|
66
|
+
readonly reason: string;
|
|
67
|
+
readonly scores: Readonly<Record<string, number>>;
|
|
68
|
+
} | null;
|
|
49
69
|
readonly failures: readonly string[];
|
|
50
70
|
}
|
|
51
71
|
export interface CreateAdaptivePriorityProviderOptions {
|
|
52
72
|
readonly workspaceDir: string;
|
|
53
73
|
readonly model: AdaptiveSelectionModel;
|
|
54
|
-
readonly
|
|
55
|
-
readonly generationTimeoutMs?: number;
|
|
74
|
+
readonly requestTimeoutMs?: number;
|
|
56
75
|
/**
|
|
57
76
|
* Absolute host deadline (Codex: the plugin hook window minus the Native
|
|
58
77
|
* reserve). Selection, revalidation and packing all share it: a selection
|
|
@@ -60,13 +79,19 @@ export interface CreateAdaptivePriorityProviderOptions {
|
|
|
60
79
|
*/
|
|
61
80
|
readonly outerDeadlineAt?: number;
|
|
62
81
|
/**
|
|
63
|
-
* PRI-
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
|
|
82
|
+
* PRI-1182 §2: reserved for assembly and output after the decision. The
|
|
83
|
+
* effective deadline is the earlier of the host's remaining window (minus
|
|
84
|
+
* this reserve) and the request's own short limit.
|
|
85
|
+
*/
|
|
86
|
+
readonly outputReserveMs?: number;
|
|
87
|
+
/**
|
|
88
|
+
* PRI-1181/PRI-1182: below this remaining budget the turn is skipped before
|
|
89
|
+
* the candidate read — no model request is sent at all. Defaults to the
|
|
90
|
+
* request's minimum executable envelope
|
|
91
|
+
* (`ADAPTIVE_SKIP_LIMITS.minExecutableBudgetMs`); 0 disables the gate for
|
|
92
|
+
* scenarios that isolate transport cancellation.
|
|
67
93
|
*/
|
|
68
|
-
readonly
|
|
69
|
-
readonly maxTokens?: number;
|
|
94
|
+
readonly minExecutableBudgetMs?: number;
|
|
70
95
|
readonly now?: () => number;
|
|
71
96
|
/** Test seam: production uses the global transport. */
|
|
72
97
|
readonly fetchImpl?: typeof fetch;
|
|
@@ -81,12 +106,12 @@ export type AdaptivePriorityProviderResolution = (AdaptiveActivationReadiness &
|
|
|
81
106
|
readonly ok: true;
|
|
82
107
|
readonly readiness: 'ready';
|
|
83
108
|
readonly provider: AdaptivePriorityProvider;
|
|
84
|
-
readonly profileId: string;
|
|
85
109
|
}) | (AdaptiveActivationReadiness & {
|
|
86
110
|
readonly ok: false;
|
|
87
111
|
});
|
|
88
112
|
export interface CreateAdaptiveProviderFromConfigOptions extends Omit<CreateAdaptivePriorityProviderOptions, 'workspaceDir' | 'model'> {
|
|
89
113
|
readonly env?: Record<string, string | undefined>;
|
|
114
|
+
readonly flag?: AdaptiveActivationFlag;
|
|
90
115
|
}
|
|
91
116
|
/**
|
|
92
117
|
* Config-first factory for hosts (Codex pd-hook) that already loaded the
|