@principles/host-runtime 4.1.3 → 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adaptive-consumer-schedule.d.ts +103 -0
- package/dist/adaptive-consumer-schedule.js +145 -0
- package/dist/adaptive-priority-provider.d.ts +7 -1
- package/dist/adaptive-priority-provider.js +6 -3
- package/dist/adaptive-selection.d.ts +1 -1
- package/dist/adaptive-selection.js +2 -1
- package/dist/degraded-enforcement-marker.d.ts +35 -0
- package/dist/degraded-enforcement-marker.js +79 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +8 -0
- package/dist/internalization-consumer-cycle.d.ts +35 -0
- package/dist/internalization-consumer-cycle.js +51 -17
- package/dist/prompt-activation-deliverability.d.ts +10 -0
- package/dist/prompt-activation-deliverability.js +5 -2
- package/dist/prompt-injection-event-evidence.d.ts +34 -0
- package/dist/prompt-injection-event-evidence.js +96 -0
- package/dist/signal-classifier.js +4 -4
- package/package.json +4 -4
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptive consumer schedule (SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4).
|
|
3
|
+
*
|
|
4
|
+
* Problem: the internalization consumer used ONE fixed 120s interval for every
|
|
5
|
+
* situation — an empty queue burned a wake-up every two minutes, and a deep
|
|
6
|
+
* backlog advanced at the same two-minute cadence (one task per cycle), so
|
|
7
|
+
* throughput was capped by the timer rather than by the provider.
|
|
8
|
+
*
|
|
9
|
+
* This module is a PURE decision function. It does not own a timer, a queue, or
|
|
10
|
+
* any persisted state: the existing single `setTimeout` chain in the host keeps
|
|
11
|
+
* scheduling, and the host keeps the cycle counters. Keeping the policy pure is
|
|
12
|
+
* what makes every branch testable without waiting real time.
|
|
13
|
+
*
|
|
14
|
+
* Data sources are the facts the cycle already computes (queue snapshot,
|
|
15
|
+
* recovery sweep) plus the run outcome — never a second source of truth.
|
|
16
|
+
*
|
|
17
|
+
* Delays are bounded by a floor (busy-loop guard) and by the retry policy's
|
|
18
|
+
* own backoff (no duplicated exponential math). Provider-rate-limit handling
|
|
19
|
+
* reuses `RetryPolicy.calculateBackoff` with a higher ceiling: the adapter
|
|
20
|
+
* already hands transport retry/Retry-After to pi-ai, so the scheduler's job is
|
|
21
|
+
* only to stop re-entering the cycle while the provider is unhappy.
|
|
22
|
+
*/
|
|
23
|
+
import { type RetryPolicy } from '@principles/core/runtime';
|
|
24
|
+
export type AdaptiveConsumerState = 'idle' | 'low_load' | 'backlog' | 'recovery_priority' | 'rate_limited' | 'provider_cooling' | 'overloaded';
|
|
25
|
+
/** Facts the host observes around ONE consumer cycle. */
|
|
26
|
+
export interface AdaptiveConsumerSignals {
|
|
27
|
+
/** Ready (actionable) tasks in the internalization queue at cycle start. */
|
|
28
|
+
readonly readyQueueDepth: number;
|
|
29
|
+
/** Tasks waiting for their retry window. */
|
|
30
|
+
readonly retryQueueDepth: number;
|
|
31
|
+
/** Age of the oldest ready task, or null when the queue is empty/unknown. */
|
|
32
|
+
readonly oldestReadyAgeMs: number | null;
|
|
33
|
+
/** Whether the cycle actually leased and ran a task. */
|
|
34
|
+
readonly lastCycleWorked: boolean;
|
|
35
|
+
/** Wall-clock duration of the finished cycle, or null before the first one. */
|
|
36
|
+
readonly lastCycleDurationMs: number | null;
|
|
37
|
+
/** Consecutive cycles that found no work. */
|
|
38
|
+
readonly consecutiveEmptyCycles: number;
|
|
39
|
+
/** Consecutive cycles that failed (cycle error or task-level failure). */
|
|
40
|
+
readonly consecutiveFailures: number;
|
|
41
|
+
/** The last failure was a provider rate limit (`rate_limit` category). */
|
|
42
|
+
readonly providerLimited: boolean;
|
|
43
|
+
/** Expired leases recovered by the cycle's recovery sweep. */
|
|
44
|
+
readonly recoveredLastCycle: number;
|
|
45
|
+
}
|
|
46
|
+
export interface AdaptiveConsumerScheduleOptions {
|
|
47
|
+
/** Empty queue + empty retry queue. Baseline behaviour (was 120s). */
|
|
48
|
+
readonly idleDelayMs?: number;
|
|
49
|
+
/** One or two ready tasks: shorten the interval. */
|
|
50
|
+
readonly lowLoadDelayMs?: number;
|
|
51
|
+
/** Sustained backlog: process the next task promptly. */
|
|
52
|
+
readonly backlogDelayMs?: number;
|
|
53
|
+
/** Expired leases were recovered: re-check soon so the retried task resumes. */
|
|
54
|
+
readonly recoveryDelayMs?: number;
|
|
55
|
+
/** Overload (extreme depth or a stalled oldest task): limit new admissions. */
|
|
56
|
+
readonly overloadDelayMs?: number;
|
|
57
|
+
/** Queue depth at which admission is deliberately slowed. */
|
|
58
|
+
readonly overloadQueueDepth?: number;
|
|
59
|
+
/** Oldest-ready age at which the queue is considered stalled. */
|
|
60
|
+
readonly stallAgeMs?: number;
|
|
61
|
+
/** Provider cooldown ceiling (bounded exponential, never unbounded). */
|
|
62
|
+
readonly failureMaxDelayMs?: number;
|
|
63
|
+
/** Hard floor for every state — prevents an empty-queue busy loop. */
|
|
64
|
+
readonly minDelayMs?: number;
|
|
65
|
+
/** Reused backoff authority; defaults to DefaultRetryPolicy(30s base, 5m cap). */
|
|
66
|
+
readonly retryPolicy?: RetryPolicy;
|
|
67
|
+
}
|
|
68
|
+
export interface AdaptiveConsumerScheduleDecision {
|
|
69
|
+
readonly state: AdaptiveConsumerState;
|
|
70
|
+
readonly delayMs: number;
|
|
71
|
+
readonly reason: string;
|
|
72
|
+
readonly signals: AdaptiveConsumerSignals;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Baseline values. The previous fixed interval was 120_000ms; every branch that
|
|
76
|
+
* is not evidence of work keeps that baseline or a longer bounded backoff, so
|
|
77
|
+
* this change can only shorten the interval when there is something to do.
|
|
78
|
+
*/
|
|
79
|
+
export declare const ADAPTIVE_CONSUMER_DEFAULTS: {
|
|
80
|
+
readonly idleDelayMs: 120000;
|
|
81
|
+
readonly lowLoadDelayMs: 60000;
|
|
82
|
+
readonly backlogDelayMs: 15000;
|
|
83
|
+
readonly recoveryDelayMs: 15000;
|
|
84
|
+
readonly overloadDelayMs: 60000;
|
|
85
|
+
readonly overloadQueueDepth: 50;
|
|
86
|
+
readonly stallAgeMs: number;
|
|
87
|
+
readonly failureMaxDelayMs: 300000;
|
|
88
|
+
readonly minDelayMs: 5000;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Decide how long to wait before the next consumer cycle.
|
|
92
|
+
*
|
|
93
|
+
* Priority (first match wins):
|
|
94
|
+
* 1. provider rate-limited → bounded exponential backoff (Retry-After is
|
|
95
|
+
* honoured inside pi-ai; the scheduler must not hammer the provider)
|
|
96
|
+
* 2. recent failures → provider/cycle cooling backoff
|
|
97
|
+
* 3. recovery sweep worked → re-check promptly so retried tasks resume
|
|
98
|
+
* 4. empty queues → baseline long sleep (no busy loop)
|
|
99
|
+
* 5. overload → slow admission deliberately
|
|
100
|
+
* 6. queue depth > 2 → backlog cadence
|
|
101
|
+
* 7. otherwise → low-load cadence
|
|
102
|
+
*/
|
|
103
|
+
export declare function nextConsumerDelay(signals: AdaptiveConsumerSignals, options?: AdaptiveConsumerScheduleOptions): AdaptiveConsumerScheduleDecision;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptive consumer schedule (SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4).
|
|
3
|
+
*
|
|
4
|
+
* Problem: the internalization consumer used ONE fixed 120s interval for every
|
|
5
|
+
* situation — an empty queue burned a wake-up every two minutes, and a deep
|
|
6
|
+
* backlog advanced at the same two-minute cadence (one task per cycle), so
|
|
7
|
+
* throughput was capped by the timer rather than by the provider.
|
|
8
|
+
*
|
|
9
|
+
* This module is a PURE decision function. It does not own a timer, a queue, or
|
|
10
|
+
* any persisted state: the existing single `setTimeout` chain in the host keeps
|
|
11
|
+
* scheduling, and the host keeps the cycle counters. Keeping the policy pure is
|
|
12
|
+
* what makes every branch testable without waiting real time.
|
|
13
|
+
*
|
|
14
|
+
* Data sources are the facts the cycle already computes (queue snapshot,
|
|
15
|
+
* recovery sweep) plus the run outcome — never a second source of truth.
|
|
16
|
+
*
|
|
17
|
+
* Delays are bounded by a floor (busy-loop guard) and by the retry policy's
|
|
18
|
+
* own backoff (no duplicated exponential math). Provider-rate-limit handling
|
|
19
|
+
* reuses `RetryPolicy.calculateBackoff` with a higher ceiling: the adapter
|
|
20
|
+
* already hands transport retry/Retry-After to pi-ai, so the scheduler's job is
|
|
21
|
+
* only to stop re-entering the cycle while the provider is unhappy.
|
|
22
|
+
*/
|
|
23
|
+
import { DefaultRetryPolicy } from '@principles/core/runtime';
|
|
24
|
+
/**
|
|
25
|
+
* Baseline values. The previous fixed interval was 120_000ms; every branch that
|
|
26
|
+
* is not evidence of work keeps that baseline or a longer bounded backoff, so
|
|
27
|
+
* this change can only shorten the interval when there is something to do.
|
|
28
|
+
*/
|
|
29
|
+
export const ADAPTIVE_CONSUMER_DEFAULTS = {
|
|
30
|
+
idleDelayMs: 120_000,
|
|
31
|
+
lowLoadDelayMs: 60_000,
|
|
32
|
+
backlogDelayMs: 15_000,
|
|
33
|
+
recoveryDelayMs: 15_000,
|
|
34
|
+
overloadDelayMs: 60_000,
|
|
35
|
+
overloadQueueDepth: 50,
|
|
36
|
+
stallAgeMs: 10 * 60 * 1000,
|
|
37
|
+
failureMaxDelayMs: 300_000,
|
|
38
|
+
minDelayMs: 5_000,
|
|
39
|
+
};
|
|
40
|
+
function resolveOptions(options) {
|
|
41
|
+
return {
|
|
42
|
+
idleDelayMs: options.idleDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.idleDelayMs,
|
|
43
|
+
lowLoadDelayMs: options.lowLoadDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.lowLoadDelayMs,
|
|
44
|
+
backlogDelayMs: options.backlogDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.backlogDelayMs,
|
|
45
|
+
recoveryDelayMs: options.recoveryDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.recoveryDelayMs,
|
|
46
|
+
overloadDelayMs: options.overloadDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.overloadDelayMs,
|
|
47
|
+
overloadQueueDepth: options.overloadQueueDepth ?? ADAPTIVE_CONSUMER_DEFAULTS.overloadQueueDepth,
|
|
48
|
+
stallAgeMs: options.stallAgeMs ?? ADAPTIVE_CONSUMER_DEFAULTS.stallAgeMs,
|
|
49
|
+
failureMaxDelayMs: options.failureMaxDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.failureMaxDelayMs,
|
|
50
|
+
minDelayMs: options.minDelayMs ?? ADAPTIVE_CONSUMER_DEFAULTS.minDelayMs,
|
|
51
|
+
retryPolicy: options.retryPolicy ?? new DefaultRetryPolicy({ baseDelayMs: 30_000, maxDelayMs: 300_000 }),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function clampDelay(delayMs, minDelayMs, maxDelayMs) {
|
|
55
|
+
const floored = Math.max(minDelayMs, Math.floor(delayMs));
|
|
56
|
+
return Math.min(floored, maxDelayMs);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Backoff for consecutive failures / a rate-limited provider.
|
|
60
|
+
*
|
|
61
|
+
* `consecutiveFailures` is 1-based for the retry policy (attempt 1 → base
|
|
62
|
+
* delay). Jitter comes from the shared policy; the ceiling is explicit so a
|
|
63
|
+
* long outage never pushes the next wake-up past five minutes.
|
|
64
|
+
*/
|
|
65
|
+
function failureDelay(consecutiveFailures, options, ceilingMs) {
|
|
66
|
+
const attempt = Math.max(1, Math.floor(consecutiveFailures));
|
|
67
|
+
return clampDelay(options.retryPolicy.calculateBackoff(attempt), options.minDelayMs, ceilingMs);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Decide how long to wait before the next consumer cycle.
|
|
71
|
+
*
|
|
72
|
+
* Priority (first match wins):
|
|
73
|
+
* 1. provider rate-limited → bounded exponential backoff (Retry-After is
|
|
74
|
+
* honoured inside pi-ai; the scheduler must not hammer the provider)
|
|
75
|
+
* 2. recent failures → provider/cycle cooling backoff
|
|
76
|
+
* 3. recovery sweep worked → re-check promptly so retried tasks resume
|
|
77
|
+
* 4. empty queues → baseline long sleep (no busy loop)
|
|
78
|
+
* 5. overload → slow admission deliberately
|
|
79
|
+
* 6. queue depth > 2 → backlog cadence
|
|
80
|
+
* 7. otherwise → low-load cadence
|
|
81
|
+
*/
|
|
82
|
+
export function nextConsumerDelay(signals, options = {}) {
|
|
83
|
+
const opts = resolveOptions(options);
|
|
84
|
+
if (signals.providerLimited) {
|
|
85
|
+
// Rate limits get a longer ceiling than ordinary failures: the provider is
|
|
86
|
+
// explicitly asking us to slow down.
|
|
87
|
+
return {
|
|
88
|
+
state: 'rate_limited',
|
|
89
|
+
delayMs: failureDelay(Math.max(1, signals.consecutiveFailures), opts, 600_000),
|
|
90
|
+
reason: 'provider reported rate_limit; backing off before the next cycle',
|
|
91
|
+
signals,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
if (signals.consecutiveFailures > 0) {
|
|
95
|
+
return {
|
|
96
|
+
state: 'provider_cooling',
|
|
97
|
+
delayMs: failureDelay(signals.consecutiveFailures, opts, opts.failureMaxDelayMs),
|
|
98
|
+
reason: `consecutive_failures=${signals.consecutiveFailures}; cooling down`,
|
|
99
|
+
signals,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (signals.recoveredLastCycle > 0) {
|
|
103
|
+
return {
|
|
104
|
+
state: 'recovery_priority',
|
|
105
|
+
delayMs: clampDelay(opts.recoveryDelayMs, opts.minDelayMs, opts.failureMaxDelayMs),
|
|
106
|
+
reason: `recovered=${signals.recoveredLastCycle} expired lease(s); resuming soon`,
|
|
107
|
+
signals,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
if (signals.readyQueueDepth === 0 && signals.retryQueueDepth === 0) {
|
|
111
|
+
return {
|
|
112
|
+
state: 'idle',
|
|
113
|
+
delayMs: clampDelay(opts.idleDelayMs, opts.minDelayMs, opts.failureMaxDelayMs),
|
|
114
|
+
reason: 'queue empty; keeping the baseline long sleep',
|
|
115
|
+
signals,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const stalled = signals.oldestReadyAgeMs !== null && signals.oldestReadyAgeMs >= opts.stallAgeMs;
|
|
119
|
+
if (signals.readyQueueDepth >= opts.overloadQueueDepth || stalled) {
|
|
120
|
+
return {
|
|
121
|
+
state: 'overloaded',
|
|
122
|
+
delayMs: clampDelay(opts.overloadDelayMs, opts.minDelayMs, opts.failureMaxDelayMs),
|
|
123
|
+
reason: stalled
|
|
124
|
+
? `oldest ready task is ${signals.oldestReadyAgeMs}ms old; limiting new admissions`
|
|
125
|
+
: `ready queue depth ${signals.readyQueueDepth} >= ${opts.overloadQueueDepth}; limiting new admissions`,
|
|
126
|
+
signals,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (signals.readyQueueDepth > 2 || signals.lastCycleWorked) {
|
|
130
|
+
return {
|
|
131
|
+
state: 'backlog',
|
|
132
|
+
delayMs: clampDelay(opts.backlogDelayMs, opts.minDelayMs, opts.failureMaxDelayMs),
|
|
133
|
+
reason: signals.lastCycleWorked
|
|
134
|
+
? 'cycle completed work; continuing the backlog promptly'
|
|
135
|
+
: `ready queue depth ${signals.readyQueueDepth}; processing backlog promptly`,
|
|
136
|
+
signals,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
state: 'low_load',
|
|
141
|
+
delayMs: clampDelay(opts.lowLoadDelayMs, opts.minDelayMs, opts.failureMaxDelayMs),
|
|
142
|
+
reason: `ready queue depth ${signals.readyQueueDepth}; shortening the interval`,
|
|
143
|
+
signals,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -9,7 +9,7 @@
|
|
|
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
|
|
12
|
+
import { type ActivatedPrinciple, type PdConfig } from '@principles/core/runtime';
|
|
13
13
|
import type { AdaptiveGapOptions } from './active-principle-prompt.js';
|
|
14
14
|
import { type AdaptiveSelectionModel } from './adaptive-selection.js';
|
|
15
15
|
/** Independent switch. `features.host.codex.enabled` remains the whole-hook gate. */
|
|
@@ -59,6 +59,12 @@ export interface AdaptiveSelectionDiagnosticLine {
|
|
|
59
59
|
readonly modelObserved: string | null;
|
|
60
60
|
/** Observed response provider; null when absent or no body was parsed. */
|
|
61
61
|
readonly providerObserved: string | null;
|
|
62
|
+
/**
|
|
63
|
+
* The activation id this turn resolved to append, or null when nothing was
|
|
64
|
+
* appended. This is the SELECTION target: the assembly must still confirm it
|
|
65
|
+
* actually reached the injected list before it is reported as appended.
|
|
66
|
+
*/
|
|
67
|
+
readonly targetActivationId: string | null;
|
|
62
68
|
/** Bounded local adjudication evidence (ids only, never prompt text). */
|
|
63
69
|
readonly decision: {
|
|
64
70
|
readonly status: string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { pdProviderCredentials } from '@principles/core/runtime';
|
|
1
2
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
2
3
|
import { ADAPTIVE_SELECTION_LIMITS, runAdaptiveSelection, } from './adaptive-selection.js';
|
|
3
4
|
import { decideAdaptiveSkip } from './adaptive-skip-decision.js';
|
|
@@ -38,12 +39,12 @@ export function resolveAdaptiveSelectionModel(config, env, flag = ADAPTIVE_ACTIV
|
|
|
38
39
|
nextAction: 'Set endpoint (https URL), model and apiKeyEnv on adaptiveActivation',
|
|
39
40
|
};
|
|
40
41
|
}
|
|
41
|
-
if (
|
|
42
|
+
if (pdProviderCredentials.resolve(section.apiKeyEnv, { env }).value === null) {
|
|
42
43
|
return {
|
|
43
44
|
ok: false,
|
|
44
45
|
readiness: 'needs_setup',
|
|
45
|
-
reason: `
|
|
46
|
-
nextAction: `
|
|
46
|
+
reason: `No API key for '${section.apiKeyEnv}' in env or ~/.pd/credentials.yaml`,
|
|
47
|
+
nextAction: `Save an API key for '${section.apiKeyEnv}' in the console, or set the environment variable`,
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
50
|
return {
|
|
@@ -99,6 +100,7 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
99
100
|
finishReason: 'skipped',
|
|
100
101
|
modelObserved: null,
|
|
101
102
|
providerObserved: null,
|
|
103
|
+
targetActivationId: null,
|
|
102
104
|
decision: null,
|
|
103
105
|
failures: [],
|
|
104
106
|
});
|
|
@@ -133,6 +135,7 @@ export function createAdaptivePriorityProvider(options) {
|
|
|
133
135
|
finishReason: outcome.diagnostics.finishReason,
|
|
134
136
|
modelObserved: outcome.diagnostics.modelObserved,
|
|
135
137
|
providerObserved: outcome.diagnostics.providerObserved,
|
|
138
|
+
targetActivationId: outcome.status === 'selected' && outcome.target ? outcome.target.activationId : null,
|
|
136
139
|
decision: outcome.diagnostics.decision,
|
|
137
140
|
failures: [...outcome.diagnostics.failures],
|
|
138
141
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ActivatedPrinciple } from '@principles/core/runtime';
|
|
2
2
|
import { type DecisionOutcome, type DecisionProtocolError, type DecisionRequestEnvelope } from './adaptive-decision-protocol.js';
|
|
3
3
|
export declare const ADAPTIVE_SELECTION_LIMITS: {
|
|
4
4
|
readonly maxCandidates: 12;
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* - Diagnostics never carry the raw prompt, the raw response, or credentials.
|
|
22
22
|
*/
|
|
23
23
|
import crypto from 'node:crypto';
|
|
24
|
+
import { pdProviderCredentials } from '@principles/core/runtime';
|
|
24
25
|
import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
|
|
25
26
|
import { ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS, adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
|
|
26
27
|
export const ADAPTIVE_SELECTION_LIMITS = {
|
|
@@ -199,7 +200,7 @@ export function createDecisionSelector(options) {
|
|
|
199
200
|
diagnostics.cancelledAt = now();
|
|
200
201
|
fail('TURN_DEADLINE_EXCEEDED');
|
|
201
202
|
}
|
|
202
|
-
const apiKey =
|
|
203
|
+
const apiKey = pdProviderCredentials.resolve(options.model.apiKeyEnv).value;
|
|
203
204
|
if (!apiKey)
|
|
204
205
|
fail('DECISION_CREDENTIAL_MISSING');
|
|
205
206
|
const body = JSON.stringify(input.body);
|
|
@@ -5,6 +5,29 @@ export interface DegradedEnforcementRecord {
|
|
|
5
5
|
lastSeenAt: string;
|
|
6
6
|
occurrences: number;
|
|
7
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* Three-state read result (PRI-1210). `unknown` is a real state, not a
|
|
10
|
+
* degraded-to-healthy default: a marker file that exists but cannot be read,
|
|
11
|
+
* parsed or validated means we do NOT know whether enforcement was bypassed,
|
|
12
|
+
* and callers must not print it as healthy or as 0.
|
|
13
|
+
*/
|
|
14
|
+
export type DegradedEnforcementState = 'healthy' | 'degraded' | 'unknown';
|
|
15
|
+
export interface DegradedEnforcementReading {
|
|
16
|
+
state: DegradedEnforcementState;
|
|
17
|
+
markerPath: string;
|
|
18
|
+
/** Present when state === 'degraded'. */
|
|
19
|
+
reason?: string;
|
|
20
|
+
/** Present when state === 'degraded'. */
|
|
21
|
+
firstSeenAt?: string;
|
|
22
|
+
/** Present when state === 'degraded' (the most recent observed fail-open). */
|
|
23
|
+
lastSeenAt?: string;
|
|
24
|
+
/** Present when state === 'degraded'. */
|
|
25
|
+
occurrences?: number;
|
|
26
|
+
/** Present when state === 'unknown' — why the marker could not be read. */
|
|
27
|
+
unreadableReason?: string;
|
|
28
|
+
/** Present when state !== 'healthy'. */
|
|
29
|
+
nextAction?: string;
|
|
30
|
+
}
|
|
8
31
|
/** Stable per-workspace marker path (keyed by resolved workspace dir). */
|
|
9
32
|
export declare function markerPathFor(workspaceDir: string): string;
|
|
10
33
|
/**
|
|
@@ -13,3 +36,15 @@ export declare function markerPathFor(workspaceDir: string): string;
|
|
|
13
36
|
* `lastSeenAt` so a stale marker is distinguishable from an active one.
|
|
14
37
|
*/
|
|
15
38
|
export declare function recordDegradedEnforcement(workspaceDir: string, reason: string, now?: Date): void;
|
|
39
|
+
/**
|
|
40
|
+
* Read the durable degraded-enforcement marker for one workspace (PRI-1210).
|
|
41
|
+
*
|
|
42
|
+
* - no marker file → `healthy` (the gate never fail-opened here);
|
|
43
|
+
* - valid marker file → `degraded` with the recorded reason and timing;
|
|
44
|
+
* - unreadable / malformed → `unknown` (never folded into healthy or into 0).
|
|
45
|
+
*
|
|
46
|
+
* The marker is a historical record, not a live probe: `lastSeenAt` is the most
|
|
47
|
+
* recent observed fail-open, and this reader does not prove the current state
|
|
48
|
+
* of the governance store. Read-only by contract.
|
|
49
|
+
*/
|
|
50
|
+
export declare function readDegradedEnforcement(workspaceDir: string): DegradedEnforcementReading;
|
|
@@ -18,6 +18,34 @@ import { createHash } from 'node:crypto';
|
|
|
18
18
|
import * as fs from 'node:fs';
|
|
19
19
|
import * as os from 'node:os';
|
|
20
20
|
import * as path from 'node:path';
|
|
21
|
+
const UNREADABLE_MARKER_NEXT_ACTION = 'Inspect the marker file and the workspace governance store. Enforcement ran fail-open when this was recorded; the recorder never clears the marker automatically — after investigating, an Owner may delete the marker file to reset this signal.';
|
|
22
|
+
function isRecord(value) {
|
|
23
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Validate the persisted record as untrusted runtime data (rc-1..rc-4).
|
|
27
|
+
* A record missing/malforming any field is NOT silently repaired: repairing it
|
|
28
|
+
* would invent evidence about an enforcement bypass.
|
|
29
|
+
*/
|
|
30
|
+
function parseDegradedEnforcementRecord(value) {
|
|
31
|
+
if (!isRecord(value))
|
|
32
|
+
return null;
|
|
33
|
+
const { workspaceDir, reason, firstSeenAt, lastSeenAt, occurrences } = value;
|
|
34
|
+
if (typeof workspaceDir !== 'string' || workspaceDir === '')
|
|
35
|
+
return null;
|
|
36
|
+
if (typeof reason !== 'string' || reason === '')
|
|
37
|
+
return null;
|
|
38
|
+
if (typeof firstSeenAt !== 'string' || !Number.isFinite(Date.parse(firstSeenAt)))
|
|
39
|
+
return null;
|
|
40
|
+
if (typeof lastSeenAt !== 'string' || !Number.isFinite(Date.parse(lastSeenAt)))
|
|
41
|
+
return null;
|
|
42
|
+
if (typeof occurrences !== 'number' || !Number.isSafeInteger(occurrences) || occurrences < 1)
|
|
43
|
+
return null;
|
|
44
|
+
return { workspaceDir, reason, firstSeenAt, lastSeenAt, occurrences };
|
|
45
|
+
}
|
|
46
|
+
function unknownReading(markerPath, unreadableReason) {
|
|
47
|
+
return { state: 'unknown', markerPath, unreadableReason, nextAction: UNREADABLE_MARKER_NEXT_ACTION };
|
|
48
|
+
}
|
|
21
49
|
function markerDir() {
|
|
22
50
|
return path.join(path.resolve(os.homedir()), '.pd', 'enforcement-health');
|
|
23
51
|
}
|
|
@@ -64,3 +92,54 @@ export function recordDegradedEnforcement(workspaceDir, reason, now = new Date()
|
|
|
64
92
|
// Observability only — the gate's fail-open decision stands regardless.
|
|
65
93
|
}
|
|
66
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Read the durable degraded-enforcement marker for one workspace (PRI-1210).
|
|
97
|
+
*
|
|
98
|
+
* - no marker file → `healthy` (the gate never fail-opened here);
|
|
99
|
+
* - valid marker file → `degraded` with the recorded reason and timing;
|
|
100
|
+
* - unreadable / malformed → `unknown` (never folded into healthy or into 0).
|
|
101
|
+
*
|
|
102
|
+
* The marker is a historical record, not a live probe: `lastSeenAt` is the most
|
|
103
|
+
* recent observed fail-open, and this reader does not prove the current state
|
|
104
|
+
* of the governance store. Read-only by contract.
|
|
105
|
+
*/
|
|
106
|
+
export function readDegradedEnforcement(workspaceDir) {
|
|
107
|
+
const markerPath = markerPathFor(workspaceDir);
|
|
108
|
+
let raw;
|
|
109
|
+
try {
|
|
110
|
+
raw = fs.readFileSync(markerPath, 'utf8');
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
// rc-5: Object.hasOwn, not `in`, on a runtime-provided error object.
|
|
114
|
+
if (isRecord(error) && Object.hasOwn(error, 'code') && error.code === 'ENOENT') {
|
|
115
|
+
return { state: 'healthy', markerPath };
|
|
116
|
+
}
|
|
117
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
118
|
+
return unknownReading(markerPath, `marker_unreadable: ${message}`.slice(0, 300));
|
|
119
|
+
}
|
|
120
|
+
let parsed;
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(raw);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return unknownReading(markerPath, 'marker_malformed_json');
|
|
126
|
+
}
|
|
127
|
+
const record = parseDegradedEnforcementRecord(parsed);
|
|
128
|
+
if (record === null)
|
|
129
|
+
return unknownReading(markerPath, 'marker_shape_invalid');
|
|
130
|
+
// rc-6 lineage consistency: the marker path is keyed by the resolved
|
|
131
|
+
// workspace string, so a record naming another workspace means the file was
|
|
132
|
+
// tampered with or copied — report unknown instead of trusting the reason.
|
|
133
|
+
if (path.resolve(record.workspaceDir) !== path.resolve(workspaceDir)) {
|
|
134
|
+
return unknownReading(markerPath, 'marker_workspace_mismatch');
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
state: 'degraded',
|
|
138
|
+
markerPath,
|
|
139
|
+
reason: record.reason,
|
|
140
|
+
firstSeenAt: record.firstSeenAt,
|
|
141
|
+
lastSeenAt: record.lastSeenAt,
|
|
142
|
+
occurrences: record.occurrences,
|
|
143
|
+
nextAction: UNREADABLE_MARKER_NEXT_ACTION,
|
|
144
|
+
};
|
|
145
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -28,6 +28,7 @@ export * from './signal-stage2-cycle.js';
|
|
|
28
28
|
export * from './host-liveness-contract.js';
|
|
29
29
|
export * from './internalization-consumer-governance.js';
|
|
30
30
|
export * from './internalization-consumer-cycle.js';
|
|
31
|
+
export * from './adaptive-consumer-schedule.js';
|
|
31
32
|
export * from './diagnostician-auto-run.js';
|
|
32
33
|
export * from './host-tool-declaration.js';
|
|
33
34
|
export * from './host-tool-semantic-resolver.js';
|
|
@@ -45,6 +46,7 @@ export * from './workbuddy-worker-status.js';
|
|
|
45
46
|
export * from './codex-legacy-registration.js';
|
|
46
47
|
export * from './codex-transcript-locate.js';
|
|
47
48
|
export * from './intervention-evidence-ingress.js';
|
|
49
|
+
export * from './degraded-enforcement-marker.js';
|
|
48
50
|
export declare const HOST_RUNTIME_ROUTES: readonly ['before_prompt_build', 'before_tool_call', 'after_tool_call'];
|
|
49
51
|
export type HostRuntimeRoute = (typeof HOST_RUNTIME_ROUTES)[number];
|
|
50
52
|
export type HostRuntimePort = (event: HostEvent) => HostEventResult | Promise<HostEventResult>;
|
package/dist/index.js
CHANGED
|
@@ -49,6 +49,9 @@ export * from './host-liveness-contract.js';
|
|
|
49
49
|
// auto-consumer + Companion workspace worker call the same cycle).
|
|
50
50
|
export * from './internalization-consumer-governance.js';
|
|
51
51
|
export * from './internalization-consumer-cycle.js';
|
|
52
|
+
// SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4: pure adaptive schedule
|
|
53
|
+
// policy for the existing consumer timer chain (no new background service).
|
|
54
|
+
export * from './adaptive-consumer-schedule.js';
|
|
52
55
|
export * from './diagnostician-auto-run.js';
|
|
53
56
|
// PRI-634-F R2: durable host-authored tool declaration — hosts persist, host-
|
|
54
57
|
// neutral consumers (pd-cli/pd-console) resolve through the ONE resolver.
|
|
@@ -88,6 +91,11 @@ export * from './codex-transcript-locate.js';
|
|
|
88
91
|
// entry point every host source (OpenClaw hooks, Codex pd-hook) uses to
|
|
89
92
|
// append normalized evidence. Never throws; never delays a hook.
|
|
90
93
|
export * from './intervention-evidence-ingress.js';
|
|
94
|
+
// PRI-1210: the durable degraded-enforcement marker was write-only. The reader
|
|
95
|
+
// is exported so `pd health`, `pd health --host codex` and the Console report
|
|
96
|
+
// the SAME three-state fact (healthy / degraded / unknown) instead of each
|
|
97
|
+
// re-deriving the marker path and parse rules.
|
|
98
|
+
export * from './degraded-enforcement-marker.js';
|
|
91
99
|
export const HOST_RUNTIME_ROUTES = [
|
|
92
100
|
'before_prompt_build',
|
|
93
101
|
'before_tool_call',
|
|
@@ -90,6 +90,28 @@ export interface InternalizationConsumerCycleOutcome {
|
|
|
90
90
|
readonly taskId?: string;
|
|
91
91
|
readonly taskKind?: string;
|
|
92
92
|
readonly runStatus?: 'succeeded' | 'failed' | 'retried';
|
|
93
|
+
/**
|
|
94
|
+
* SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4: the failure category of
|
|
95
|
+
* the executed task (absent on success/skip). The host scheduler uses it to
|
|
96
|
+
* distinguish a provider rate limit from ordinary work.
|
|
97
|
+
*/
|
|
98
|
+
readonly errorCategory?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Facts the adaptive scheduler needs, observed by THIS cycle. A cycle that
|
|
101
|
+
* never reached the queue snapshot (disabled flag, malformed config) reports
|
|
102
|
+
* zeros — it genuinely observed nothing.
|
|
103
|
+
*
|
|
104
|
+
* `recovered` is filled by the finally-block recovery sweep, which runs after
|
|
105
|
+
* the return value is constructed; the object is intentionally mutated before
|
|
106
|
+
* the promise settles so the caller sees the sweep result.
|
|
107
|
+
*/
|
|
108
|
+
readonly signals: InternalizationConsumerCycleSignals;
|
|
109
|
+
}
|
|
110
|
+
export interface InternalizationConsumerCycleSignals {
|
|
111
|
+
readonly readyQueueDepth: number;
|
|
112
|
+
readonly retryQueueDepth: number;
|
|
113
|
+
readonly oldestReadyAgeMs: number | null;
|
|
114
|
+
readonly recovered: number;
|
|
93
115
|
}
|
|
94
116
|
/**
|
|
95
117
|
* PRI-954 (F10) oldest-ready-stage-first ordering. Returns the configured
|
|
@@ -103,10 +125,23 @@ export declare function orderKindsByOldestReadyStage<T extends string>(runnerKin
|
|
|
103
125
|
taskKind: T;
|
|
104
126
|
createdAt?: string;
|
|
105
127
|
}[]): T[];
|
|
128
|
+
/**
|
|
129
|
+
* SPEC §4: age of the oldest ready task, or null when no row carries a usable
|
|
130
|
+
* createdAt. Unknown age must never be reported as 0 (that would make a stalled
|
|
131
|
+
* queue look fresh and suppress the overload branch).
|
|
132
|
+
*/
|
|
133
|
+
export declare function oldestReadyAgeMs(readyTasks: readonly {
|
|
134
|
+
createdAt?: string;
|
|
135
|
+
}[], nowMs: number): number | null;
|
|
106
136
|
/**
|
|
107
137
|
* Run ONE bounded consumer cycle for a workspace. At most one downstream task
|
|
108
138
|
* is leased and executed per cycle (DEFAULT_CONSUMER_MAX_TASKS_PER_CYCLE=1);
|
|
109
139
|
* backlog converges over repeated cycles and never starves reconciliation
|
|
110
140
|
* (bounded budget in the finally block).
|
|
141
|
+
*
|
|
142
|
+
* SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4: the outcome now carries
|
|
143
|
+
* the queue facts the NEXT scheduling decision needs. They are collected in a
|
|
144
|
+
* single object that the inner cycle mutates, so the recovery sweep (finally
|
|
145
|
+
* block, after the return value is built) is still visible to the caller.
|
|
111
146
|
*/
|
|
112
147
|
export declare function runInternalizationConsumerCycle(workspaceDir: string, ports: InternalizationConsumerCyclePorts): Promise<InternalizationConsumerCycleOutcome>;
|
|
@@ -70,10 +70,12 @@ async function safeRunRecoverySweep(stateManager, ports) {
|
|
|
70
70
|
}));
|
|
71
71
|
logger.info(`[PD:${logLabel}] Recovery sweep: recovered=${sweep.recovered} failed=${sweep.errors.length}`);
|
|
72
72
|
}
|
|
73
|
+
return sweep.recovered;
|
|
73
74
|
}
|
|
74
75
|
catch (sweepErr) {
|
|
75
76
|
emitEvent('INTERNALIZATION_CONSUMER_RECOVER_FAILED', String(sweepErr));
|
|
76
77
|
logger.warn(`[PD:${logLabel}] Recovery sweep failed: ${String(sweepErr)}`);
|
|
78
|
+
return 0;
|
|
77
79
|
}
|
|
78
80
|
}
|
|
79
81
|
/**
|
|
@@ -116,6 +118,26 @@ export function orderKindsByOldestReadyStage(runnerKinds, readyTasks) {
|
|
|
116
118
|
return [...runnerKinds];
|
|
117
119
|
return [...runnerKinds.slice(startIndex), ...runnerKinds.slice(0, startIndex)];
|
|
118
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* SPEC §4: age of the oldest ready task, or null when no row carries a usable
|
|
123
|
+
* createdAt. Unknown age must never be reported as 0 (that would make a stalled
|
|
124
|
+
* queue look fresh and suppress the overload branch).
|
|
125
|
+
*/
|
|
126
|
+
export function oldestReadyAgeMs(readyTasks, nowMs) {
|
|
127
|
+
let oldestMs = null;
|
|
128
|
+
for (const task of readyTasks) {
|
|
129
|
+
if (typeof task.createdAt !== 'string' || task.createdAt.length === 0)
|
|
130
|
+
continue;
|
|
131
|
+
const parsed = Date.parse(task.createdAt);
|
|
132
|
+
if (!Number.isFinite(parsed))
|
|
133
|
+
continue;
|
|
134
|
+
if (oldestMs === null || parsed < oldestMs)
|
|
135
|
+
oldestMs = parsed;
|
|
136
|
+
}
|
|
137
|
+
if (oldestMs === null)
|
|
138
|
+
return null;
|
|
139
|
+
return Math.max(0, nowMs - oldestMs);
|
|
140
|
+
}
|
|
119
141
|
async function runReconciliationBudget(workspaceDir, orchestrator, ports) {
|
|
120
142
|
const { logger, emitEvent, logLabel } = ports;
|
|
121
143
|
try {
|
|
@@ -167,8 +189,24 @@ async function runReconciliationBudget(workspaceDir, orchestrator, ports) {
|
|
|
167
189
|
* is leased and executed per cycle (DEFAULT_CONSUMER_MAX_TASKS_PER_CYCLE=1);
|
|
168
190
|
* backlog converges over repeated cycles and never starves reconciliation
|
|
169
191
|
* (bounded budget in the finally block).
|
|
192
|
+
*
|
|
193
|
+
* SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §4: the outcome now carries
|
|
194
|
+
* the queue facts the NEXT scheduling decision needs. They are collected in a
|
|
195
|
+
* single object that the inner cycle mutates, so the recovery sweep (finally
|
|
196
|
+
* block, after the return value is built) is still visible to the caller.
|
|
170
197
|
*/
|
|
171
198
|
export async function runInternalizationConsumerCycle(workspaceDir, ports) {
|
|
199
|
+
const signals = {
|
|
200
|
+
readyQueueDepth: 0,
|
|
201
|
+
retryQueueDepth: 0,
|
|
202
|
+
oldestReadyAgeMs: null,
|
|
203
|
+
recovered: 0,
|
|
204
|
+
};
|
|
205
|
+
// eslint-disable-next-line @typescript-eslint/no-use-before-define -- the wrapper is the public entry point; the inner cycle is declared below so the exported surface reads first
|
|
206
|
+
const outcome = await executeConsumerCycle(workspaceDir, ports, signals);
|
|
207
|
+
return { ...outcome, signals };
|
|
208
|
+
}
|
|
209
|
+
async function executeConsumerCycle(workspaceDir, ports, signals) {
|
|
172
210
|
const { logger, emitEvent, logLabel, owner } = ports;
|
|
173
211
|
const { hostToolCatalog, toolSemantics } = ports;
|
|
174
212
|
// PRI-741: artificer host semantic projection — built once from the SAME
|
|
@@ -246,6 +284,11 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
|
|
|
246
284
|
actionableTaskKinds: new Set(MVP_CORE_TASK_KINDS),
|
|
247
285
|
});
|
|
248
286
|
const snapshot = await readModel.getSnapshot();
|
|
287
|
+
// SPEC §4: scheduling facts come from the SAME snapshot the decision used.
|
|
288
|
+
// A malformed createdAt is skipped (unknown age never becomes "0ms old").
|
|
289
|
+
signals.readyQueueDepth = snapshot.readyTasks.length;
|
|
290
|
+
signals.retryQueueDepth = snapshot.retryWaitCount;
|
|
291
|
+
signals.oldestReadyAgeMs = oldestReadyAgeMs(snapshot.readyTasks, Date.now());
|
|
249
292
|
if (snapshot.readyTasks.length > 5) {
|
|
250
293
|
logger.warn(`[PD:${logLabel}] Backlog detected: ${snapshot.readyTasks.length} tasks ready. Processing only one task.`);
|
|
251
294
|
}
|
|
@@ -834,21 +877,12 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
|
|
|
834
877
|
}
|
|
835
878
|
catch (runErr) {
|
|
836
879
|
logger.error(`[PD:${logLabel}] Runner crashed for task ${taskId}: ${String(runErr)}`);
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
}
|
|
844
|
-
else {
|
|
845
|
-
await stateManager.markTaskFailed(taskId, 'execution_failed', failureReason);
|
|
846
|
-
logger.info(`[PD:${logLabel}] Marked task ${taskId} as failed.`);
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
catch (dbErr) {
|
|
850
|
-
logger.error(`[PD:${logLabel}] Failed to update state for crashed task ${taskId}: ${String(dbErr)}`);
|
|
851
|
-
}
|
|
880
|
+
// SPEC §5.3 / task-book §1.1: this layer holds no execution identity
|
|
881
|
+
// (no lease fence, no runId), so it MUST NOT write task state. A crash
|
|
882
|
+
// that happens after acquisition is resolved by the task's own lease,
|
|
883
|
+
// and an unowned/stale lease is reclaimed by the recovery sweep above —
|
|
884
|
+
// both report what happened. Writing `failed`/`retry_wait` from here
|
|
885
|
+
// was the exact "unowned terminal write" this remediation removes.
|
|
852
886
|
throw runErr;
|
|
853
887
|
}
|
|
854
888
|
if (runResult.status === 'succeeded') {
|
|
@@ -881,7 +915,7 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
|
|
|
881
915
|
nextAction,
|
|
882
916
|
}));
|
|
883
917
|
logger.warn(`[PD:${logLabel}] Task ${taskId} status: ${runResult.status}. Category: ${errorCategory}. Reason: ${failureReason}. Next Action: ${nextAction}`);
|
|
884
|
-
return { ran: true, taskId, taskKind, runStatus: runResult.status === 'retried' ? 'retried' : 'failed' };
|
|
918
|
+
return { ran: true, taskId, taskKind, runStatus: runResult.status === 'retried' ? 'retried' : 'failed', ...(errorCategory !== undefined ? { errorCategory } : {}) };
|
|
885
919
|
}
|
|
886
920
|
catch (err) {
|
|
887
921
|
emitEvent('INTERNALIZATION_CONSUMER_ERROR', String(err));
|
|
@@ -896,7 +930,7 @@ export async function runInternalizationConsumerCycle(workspaceDir, ports) {
|
|
|
896
930
|
// executes if the orchestrator constructor threw — enumerate every early
|
|
897
931
|
// return between resource-open and the finally steps (ERR-024).
|
|
898
932
|
if (handle) {
|
|
899
|
-
await safeRunRecoverySweep(handle.stateManager, ports);
|
|
933
|
+
signals.recovered = await safeRunRecoverySweep(handle.stateManager, ports);
|
|
900
934
|
}
|
|
901
935
|
// A (最终复核): 每周期固定小预算 — continuous backlog 下 reconciliation
|
|
902
936
|
// 不会被 ready 任务永久饿死 (公平性);游标 restart-durable。
|
|
@@ -21,6 +21,14 @@ export interface PromptDeliverabilityCandidateArtifact {
|
|
|
21
21
|
validationStatus: string;
|
|
22
22
|
/** Formal ledger identity column; identity never comes from content titles. */
|
|
23
23
|
sourcePrincipleId?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Ledger identity resolved through the artifact's candidate lineage (the same
|
|
26
|
+
* authority the activation dispatcher uses). Legacy artifacts were written
|
|
27
|
+
* before the identity column was stamped; the precheck must measure them
|
|
28
|
+
* under the identity they will actually activate as, not refuse them as if
|
|
29
|
+
* they had none.
|
|
30
|
+
*/
|
|
31
|
+
resolvedPrincipleId?: string;
|
|
24
32
|
}
|
|
25
33
|
export type PromptArtifactDeliverability = {
|
|
26
34
|
status: 'deliverable';
|
|
@@ -148,4 +156,6 @@ export declare function checkPromptArtifactDeliverabilityById(input: {
|
|
|
148
156
|
targetHost?: PromptInjectionTargetHost;
|
|
149
157
|
/** See `checkPromptArtifactDeliverability.authority` (approve-time = 'owner'). */
|
|
150
158
|
authority?: 'owner' | 'system_policy';
|
|
159
|
+
/** Ledger identity already resolved from the artifact's candidate lineage. */
|
|
160
|
+
resolvedPrincipleId?: string;
|
|
151
161
|
}): Promise<PromptArtifactDeliverability>;
|
|
@@ -24,7 +24,7 @@ export function resolvePromptCandidatePrinciple(artifact) {
|
|
|
24
24
|
artifact_kind: artifact.artifactKind,
|
|
25
25
|
content_json: artifact.contentJson,
|
|
26
26
|
validation_status: artifact.validationStatus,
|
|
27
|
-
source_principle_id: artifact.sourcePrincipleId,
|
|
27
|
+
source_principle_id: artifact.resolvedPrincipleId ?? artifact.sourcePrincipleId,
|
|
28
28
|
}, syntheticPendingActivation(artifact.artifactId));
|
|
29
29
|
}
|
|
30
30
|
function selfReportEnabledFor(workspaceDir) {
|
|
@@ -222,6 +222,9 @@ export async function checkPromptArtifactDeliverabilityById(input) {
|
|
|
222
222
|
}
|
|
223
223
|
return checkPromptArtifactDeliverability({
|
|
224
224
|
...input,
|
|
225
|
-
artifact:
|
|
225
|
+
artifact: {
|
|
226
|
+
...loaded.artifact,
|
|
227
|
+
...(input.resolvedPrincipleId !== undefined ? { resolvedPrincipleId: input.resolvedPrincipleId } : {}),
|
|
228
|
+
},
|
|
226
229
|
});
|
|
227
230
|
}
|
|
@@ -49,3 +49,37 @@ export interface InjectionEventEvidenceReport {
|
|
|
49
49
|
export declare function readInjectionEventEvidence(input: {
|
|
50
50
|
stateDir: string;
|
|
51
51
|
}): InjectionEventEvidenceReport;
|
|
52
|
+
/**
|
|
53
|
+
* One Adaptive Activation turn, as recorded on the SAME injection event that
|
|
54
|
+
* carries the final assembly. `appendedActivationId` is the assembly fact
|
|
55
|
+
* (present only when the id reached `activationIds`), never a model-selection
|
|
56
|
+
* claim; `scored` states whether a scoring request actually left the process.
|
|
57
|
+
*/
|
|
58
|
+
export interface AdaptiveInjectionRecord {
|
|
59
|
+
ts: string | null;
|
|
60
|
+
runId: string | null;
|
|
61
|
+
sessionId: string;
|
|
62
|
+
resultCode: string;
|
|
63
|
+
scored: boolean;
|
|
64
|
+
appendedActivationId: string | null;
|
|
65
|
+
activationIds: string[];
|
|
66
|
+
}
|
|
67
|
+
export interface AdaptiveInjectionRecordsReport {
|
|
68
|
+
filesRead: string[];
|
|
69
|
+
lines: number;
|
|
70
|
+
parseFailures: number;
|
|
71
|
+
/** Newest first. Absence means "no Adaptive fact was recorded", not "no append". */
|
|
72
|
+
records: AdaptiveInjectionRecord[];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Read-model for the Console's "what happened last time" card. Reads only the
|
|
76
|
+
* bounded `adaptive` fact already present on injection events (ids + codes),
|
|
77
|
+
* and never re-derives it from model output. Old events without the field are
|
|
78
|
+
* simply absent — there is no back-fill and no guess (rc-9).
|
|
79
|
+
*/
|
|
80
|
+
export declare function readAdaptiveInjectionRecords(input: {
|
|
81
|
+
stateDir: string;
|
|
82
|
+
workspaceDir?: string;
|
|
83
|
+
hostKind?: 'openclaw' | 'codex' | 'workbuddy';
|
|
84
|
+
limit?: number;
|
|
85
|
+
}): AdaptiveInjectionRecordsReport;
|
|
@@ -143,3 +143,99 @@ export function readInjectionEventEvidence(input) {
|
|
|
143
143
|
note: 'absence from rows means UNKNOWN (no logs), never zero; self-report is a separate signal and is not compliance evidence; rows never merge workspaces',
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Read-model for the Console's "what happened last time" card. Reads only the
|
|
148
|
+
* bounded `adaptive` fact already present on injection events (ids + codes),
|
|
149
|
+
* and never re-derives it from model output. Old events without the field are
|
|
150
|
+
* simply absent — there is no back-fill and no guess (rc-9).
|
|
151
|
+
*/
|
|
152
|
+
export function readAdaptiveInjectionRecords(input) {
|
|
153
|
+
const logsRoot = path.resolve(input.stateDir, 'logs');
|
|
154
|
+
const filesRead = [];
|
|
155
|
+
const limit = Math.max(1, Math.min(input.limit ?? 20, 100));
|
|
156
|
+
if (!fs.existsSync(logsRoot)) {
|
|
157
|
+
return { filesRead, lines: 0, parseFailures: 0, records: [] };
|
|
158
|
+
}
|
|
159
|
+
const files = fs.readdirSync(logsRoot)
|
|
160
|
+
.filter((name) => name.startsWith('events_') && name.endsWith('.jsonl'))
|
|
161
|
+
.sort();
|
|
162
|
+
let lines = 0;
|
|
163
|
+
let parseFailures = 0;
|
|
164
|
+
const records = [];
|
|
165
|
+
for (const name of files) {
|
|
166
|
+
const filePath = path.resolve(logsRoot, name);
|
|
167
|
+
if (!filePath.startsWith(logsRoot + path.sep) || path.basename(name) !== name)
|
|
168
|
+
continue;
|
|
169
|
+
filesRead.push(filePath);
|
|
170
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
171
|
+
for (const line of raw.split('\n')) {
|
|
172
|
+
if (line.trim().length === 0)
|
|
173
|
+
continue;
|
|
174
|
+
lines += 1;
|
|
175
|
+
let parsed;
|
|
176
|
+
try {
|
|
177
|
+
parsed = JSON.parse(line);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
parseFailures += 1;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (!isRecord(parsed)) {
|
|
184
|
+
parseFailures += 1;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (nonEmptyString(parsed.type) !== 'runtime_v2_prompt_activations_injected')
|
|
188
|
+
continue;
|
|
189
|
+
const { data } = parsed;
|
|
190
|
+
if (!isRecord(data)) {
|
|
191
|
+
parseFailures += 1;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const { adaptive } = data;
|
|
195
|
+
// No Adaptive fact on this event = this turn did not run Adaptive (or
|
|
196
|
+
// predates it). Not a parse failure: nothing was recorded.
|
|
197
|
+
if (adaptive === undefined)
|
|
198
|
+
continue;
|
|
199
|
+
if (!isRecord(adaptive)) {
|
|
200
|
+
parseFailures += 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const resultCode = nonEmptyString(adaptive.resultCode);
|
|
204
|
+
const sessionId = nonEmptyString(data.sessionId) ?? nonEmptyString(parsed.sessionId);
|
|
205
|
+
const workspaceDir = nonEmptyString(data.workspaceDir);
|
|
206
|
+
const { activationIds } = data;
|
|
207
|
+
if (resultCode === undefined || sessionId === undefined || workspaceDir === undefined
|
|
208
|
+
|| typeof adaptive.scored !== 'boolean' || !Array.isArray(activationIds)
|
|
209
|
+
|| !activationIds.every((id) => typeof id === 'string')) {
|
|
210
|
+
// rc-3/rc-4: a malformed Adaptive fact is skipped loudly, never guessed.
|
|
211
|
+
parseFailures += 1;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (input.workspaceDir !== undefined && workspaceDir !== input.workspaceDir)
|
|
215
|
+
continue;
|
|
216
|
+
const rawHostKind = data.hostKind;
|
|
217
|
+
const hostKind = isPromptInjectionTargetHost(rawHostKind) ? rawHostKind : 'unknown';
|
|
218
|
+
if (input.hostKind !== undefined && hostKind !== input.hostKind)
|
|
219
|
+
continue;
|
|
220
|
+
records.push({
|
|
221
|
+
ts: nonEmptyString(parsed.ts) ?? null,
|
|
222
|
+
runId: nonEmptyString(data.runId) ?? null,
|
|
223
|
+
sessionId,
|
|
224
|
+
resultCode,
|
|
225
|
+
scored: adaptive.scored,
|
|
226
|
+
appendedActivationId: nonEmptyString(adaptive.appendedActivationId) ?? null,
|
|
227
|
+
activationIds,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
records.sort((a, b) => {
|
|
232
|
+
if (a.ts === b.ts)
|
|
233
|
+
return 0;
|
|
234
|
+
if (a.ts === null)
|
|
235
|
+
return 1;
|
|
236
|
+
if (b.ts === null)
|
|
237
|
+
return -1;
|
|
238
|
+
return a.ts < b.ts ? 1 : -1;
|
|
239
|
+
});
|
|
240
|
+
return { filesRead, lines, parseFailures, records: records.slice(0, limit) };
|
|
241
|
+
}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* No second model runtime is introduced (ADR-0029: pi-ai is the only backend).
|
|
14
14
|
*/
|
|
15
15
|
import path from 'node:path';
|
|
16
|
-
import { PiAiRuntimeAdapter, RUNTIME_CONTRACT_SCHEMA_VERSION, SIGNAL_CLASSIFIER_SYSTEM_PROMPT, buildLlmPrompt, resolveLlmClassificationPayload, safeStringifyPreview, } from '@principles/core/runtime';
|
|
16
|
+
import { PiAiRuntimeAdapter, RUNTIME_CONTRACT_SCHEMA_VERSION, SIGNAL_CLASSIFIER_SYSTEM_PROMPT, buildLlmPrompt, resolveLlmClassificationPayload, pdProviderCredentials, safeStringifyPreview, } from '@principles/core/runtime';
|
|
17
17
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
18
18
|
/**
|
|
19
19
|
* The Stage-2 structured-output contract this classifier requests. It MUST stay
|
|
@@ -153,12 +153,12 @@ export function createSignalClassifierForWorkspace(workspaceDir, options = {}) {
|
|
|
153
153
|
nextAction: `Set provider and model on runtime profile '${runtimeProfileId}'`,
|
|
154
154
|
};
|
|
155
155
|
}
|
|
156
|
-
if (
|
|
156
|
+
if (pdProviderCredentials.resolve(profile.apiKeyEnv).value === null) {
|
|
157
157
|
return {
|
|
158
158
|
ok: false,
|
|
159
159
|
readiness: 'needs_setup',
|
|
160
|
-
reason: `
|
|
161
|
-
nextAction: `
|
|
160
|
+
reason: `No API key for '${profile.apiKeyEnv}' in env or ~/.pd/credentials.yaml`,
|
|
161
|
+
nextAction: `Save an API key for '${profile.apiKeyEnv}' in the console, or set the environment variable`,
|
|
162
162
|
};
|
|
163
163
|
}
|
|
164
164
|
const resolved = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "4.1
|
|
3
|
+
"version": "4.2.1",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -35,8 +35,8 @@
|
|
|
35
35
|
"lint": "eslint \"src/**/*.ts\""
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@principles/core": "^7.
|
|
39
|
-
"@principles/install-layout": "^0.8.
|
|
38
|
+
"@principles/core": "^7.8.0",
|
|
39
|
+
"@principles/install-layout": "^0.8.2",
|
|
40
40
|
"better-sqlite3": "^13.0.3",
|
|
41
41
|
"js-yaml": "^5.4.3"
|
|
42
42
|
},
|
|
@@ -53,5 +53,5 @@
|
|
|
53
53
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
54
54
|
},
|
|
55
55
|
"license": "Apache-2.0",
|
|
56
|
-
"gitHead": "
|
|
56
|
+
"gitHead": "8ad7b7924a5edb2231486ef0ed99c2462ad78318"
|
|
57
57
|
}
|