create-principles-disciple 1.152.5 → 1.153.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/_release/product-identity.json +1 -1
- package/agent-skill/pd-setup/SKILL.md +70 -0
- package/codex-adapter/dist/background-selection.d.ts +9 -0
- package/codex-adapter/dist/background-selection.js +142 -0
- package/codex-adapter/dist/ingestion/adaptive-append-state.d.ts +209 -0
- package/codex-adapter/dist/ingestion/adaptive-append-state.js +544 -0
- package/codex-adapter/dist/pd-hook.js +329 -5
- package/codex-adapter/package.json +1 -1
- package/console/dist/server/config/pd-config-store.d.ts +11 -15
- package/console/dist/server/config/pd-config-store.js +92 -17
- package/console/dist/server/models/AdaptiveActivationConsoleModel.d.ts +43 -4
- package/console/dist/server/models/AdaptiveActivationConsoleModel.js +36 -7
- package/console/dist/server/routes/config.js +34 -8
- package/console/dist/web/assets/app.css +6 -0
- package/console/dist/web/assets/app.js +22 -22
- package/core/dist/runtime/activation/sqlite-approval-store.d.ts.map +1 -1
- package/core/dist/runtime/activation/sqlite-approval-store.js +7 -1
- package/core/dist/runtime/activation/sqlite-approval-store.js.map +1 -1
- package/core/dist/runtime/config/pd-config-feature-flags.d.ts +10 -0
- package/core/dist/runtime/config/pd-config-feature-flags.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-feature-flags.js +14 -0
- package/core/dist/runtime/config/pd-config-feature-flags.js.map +1 -1
- package/core/dist/runtime/config/pd-config-types.d.ts +9 -0
- package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-types.js.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.js +10 -2
- package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +13 -2
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
- package/core/dist/runtime/intent/intent-doc.d.ts +22 -0
- package/core/dist/runtime/intent/intent-doc.d.ts.map +1 -1
- package/core/dist/runtime/intent/intent-doc.js +79 -0
- package/core/dist/runtime/intent/intent-doc.js.map +1 -1
- package/core/dist/runtime/intent/intent-friction-block.d.ts +7 -0
- package/core/dist/runtime/intent/intent-friction-block.d.ts.map +1 -1
- package/core/dist/runtime/intent/intent-friction-block.js +34 -1
- package/core/dist/runtime/intent/intent-friction-block.js.map +1 -1
- package/core/dist/runtime/intent/intent-snapshot.d.ts +44 -5
- package/core/dist/runtime/intent/intent-snapshot.d.ts.map +1 -1
- package/core/dist/runtime/intent/intent-snapshot.js +83 -15
- package/core/dist/runtime/intent/intent-snapshot.js.map +1 -1
- package/core/dist/runtime/intent/strategic-conflict-gate.d.ts +19 -0
- package/core/dist/runtime/intent/strategic-conflict-gate.d.ts.map +1 -1
- package/core/dist/runtime/intent/strategic-conflict-gate.js +94 -26
- package/core/dist/runtime/intent/strategic-conflict-gate.js.map +1 -1
- package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts +22 -11
- package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/diag-rootcause-runner.js +101 -28
- package/core/dist/runtime/internalization/diag-rootcause-runner.js.map +1 -1
- package/core/dist/runtime/internalization/dreamer-prompt-builder.d.ts.map +1 -1
- package/core/dist/runtime/internalization/dreamer-prompt-builder.js +1 -0
- package/core/dist/runtime/internalization/dreamer-prompt-builder.js.map +1 -1
- package/core/dist/runtime/internalization/dreamer-runner.d.ts +9 -2
- package/core/dist/runtime/internalization/dreamer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/dreamer-runner.js +11 -1
- package/core/dist/runtime/internalization/dreamer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/evaluator-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/evaluator-runner.js +7 -0
- package/core/dist/runtime/internalization/evaluator-runner.js.map +1 -1
- package/core/dist/runtime/internalization/formation-context.d.ts +16 -0
- package/core/dist/runtime/internalization/formation-context.d.ts.map +1 -1
- package/core/dist/runtime/internalization/formation-context.js +109 -8
- package/core/dist/runtime/internalization/formation-context.js.map +1 -1
- package/core/dist/runtime/internalization/index.d.ts +2 -2
- package/core/dist/runtime/internalization/index.d.ts.map +1 -1
- package/core/dist/runtime/internalization/index.js +1 -1
- package/core/dist/runtime/internalization/index.js.map +1 -1
- package/core/dist/runtime/internalization/intent-contract.d.ts +55 -4
- package/core/dist/runtime/internalization/intent-contract.d.ts.map +1 -1
- package/core/dist/runtime/internalization/intent-contract.js +111 -30
- package/core/dist/runtime/internalization/intent-contract.js.map +1 -1
- package/core/dist/runtime/internalization/philosopher-runner.d.ts +9 -2
- package/core/dist/runtime/internalization/philosopher-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/philosopher-runner.js +11 -1
- package/core/dist/runtime/internalization/philosopher-runner.js.map +1 -1
- package/core/dist/runtime/internalization/scribe-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/scribe-runner.js +17 -7
- package/core/dist/runtime/internalization/scribe-runner.js.map +1 -1
- package/core/dist/runtime/store/intent/sqlite-intent-decision-store.d.ts +10 -0
- package/core/dist/runtime/store/intent/sqlite-intent-decision-store.d.ts.map +1 -1
- package/core/dist/runtime/store/intent/sqlite-intent-decision-store.js +15 -4
- package/core/dist/runtime/store/intent/sqlite-intent-decision-store.js.map +1 -1
- package/core/dist/telemetry-event.d.ts +2 -2
- package/core/dist/telemetry-event.d.ts.map +1 -1
- package/core/dist/telemetry-event.js +6 -0
- package/core/dist/telemetry-event.js.map +1 -1
- package/core/package.json +1 -1
- package/dist/agent-skill.d.ts +59 -0
- package/dist/agent-skill.d.ts.map +1 -0
- package/dist/agent-skill.js +198 -0
- package/dist/agent-skill.js.map +1 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +12 -0
- package/dist/i18n.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +171 -3
- package/dist/index.js.map +1 -1
- package/dist/install-summary.d.ts +52 -0
- package/dist/install-summary.d.ts.map +1 -1
- package/dist/install-summary.js +104 -0
- package/dist/install-summary.js.map +1 -1
- package/host-runtime/dist/adaptive-background-append.d.ts +70 -0
- package/host-runtime/dist/adaptive-background-append.js +165 -0
- package/host-runtime/dist/index.d.ts +1 -0
- package/host-runtime/dist/index.js +5 -0
- package/host-runtime/package.json +1 -1
- package/package.json +3 -2
- package/pd-cli/dist/commands/health-console.d.ts +21 -0
- package/pd-cli/dist/commands/health-console.d.ts.map +1 -0
- package/pd-cli/dist/commands/health-console.js +106 -0
- package/pd-cli/dist/commands/health-console.js.map +1 -0
- package/pd-cli/dist/commands/health.d.ts +159 -0
- package/pd-cli/dist/commands/health.d.ts.map +1 -1
- package/pd-cli/dist/commands/health.js +162 -2
- package/pd-cli/dist/commands/health.js.map +1 -1
- package/pd-cli/dist/commands/mcp-probe.d.ts +48 -0
- package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -0
- package/pd-cli/dist/commands/mcp-probe.js +479 -0
- package/pd-cli/dist/commands/mcp-probe.js.map +1 -0
- package/pd-cli/dist/commands/runtime-internalization-run-once.js +2 -2
- package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
- package/pd-cli/dist/program.d.ts.map +1 -1
- package/pd-cli/dist/program.js +57 -0
- package/pd-cli/dist/program.js.map +1 -1
- package/pd-cli/dist/services/console-launcher.d.ts +3 -0
- package/pd-cli/dist/services/console-launcher.d.ts.map +1 -1
- package/pd-cli/dist/services/console-launcher.js +3 -2
- package/pd-cli/dist/services/console-launcher.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +533 -449
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/i18n.js +12 -0
- package/release-manager/package.json +2 -1
- package/workbuddy-adapter/dist/pd-hook.js +37 -3
- package/workbuddy-adapter/package.json +1 -1
|
@@ -5,7 +5,8 @@ import path from 'node:path';
|
|
|
5
5
|
import process from 'node:process';
|
|
6
6
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
7
7
|
import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime';
|
|
8
|
-
import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
8
|
+
import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, renderAcceptedAdaptiveAppend, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
9
|
+
import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
|
|
9
10
|
import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
|
|
10
11
|
import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
|
|
11
12
|
import { CodexHooksHostAdapter } from './host-adapter.js';
|
|
@@ -15,6 +16,7 @@ import { runGovernanceAdmission } from './ingestion/admission.js';
|
|
|
15
16
|
import { parseOwnerStatementPrefix, recordExplicitOwnerStatement } from './ingestion/explicit-owner-statement.js';
|
|
16
17
|
import { writeCurrentTurnContext, clearCurrentTurnContext } from './ingestion/turn-context.js';
|
|
17
18
|
import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
|
|
19
|
+
import { ADAPTIVE_APPEND_SCHEMA_VERSION, appendAdaptiveAppendFact, appendToolObservation, claimAdaptiveAppendResult, claimAdaptiveReportMarker, clearAdaptiveAppendTurn, clearStaleAdaptiveAppendState, currentHookIdentity, discardAdaptiveAppendJob, evaluateAppendOrdering, hasAdaptiveAppendTurn, markAdaptiveTurnEnded, markAdaptiveTurnStarted, readToolObservations, releaseAdaptiveAppendClaim, spawnAdaptiveBackgroundSelection, writeAdaptiveAppendJob, } from './ingestion/adaptive-append-state.js';
|
|
18
20
|
const MAX_DIAGNOSTIC = 500;
|
|
19
21
|
function diagnostic(reason, nextAction) {
|
|
20
22
|
const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
|
|
@@ -126,6 +128,108 @@ function codexEventEmitter(stateDir, evidence, readAdaptiveFact) {
|
|
|
126
128
|
},
|
|
127
129
|
};
|
|
128
130
|
}
|
|
131
|
+
/** One bounded Adaptive fact line; evidence is best-effort and never blocks the hook. */
|
|
132
|
+
function emitBackgroundFact(key, fact) {
|
|
133
|
+
try {
|
|
134
|
+
appendAdaptiveAppendFact({
|
|
135
|
+
stateDir: key.stateDir,
|
|
136
|
+
sessionId: key.sessionId,
|
|
137
|
+
turnId: key.turnId,
|
|
138
|
+
workspaceDir: key.workspaceDir,
|
|
139
|
+
resultCode: fact.resultCode,
|
|
140
|
+
scored: fact.scored,
|
|
141
|
+
budget: fact.budget,
|
|
142
|
+
injectedCharCount: fact.injectedCharCount,
|
|
143
|
+
...(fact.appended ? { appended: fact.appended } : {}),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// A failed evidence write must not change the host decision.
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Emit at most ONE terminal drop fact for this turn. */
|
|
151
|
+
function reportBackgroundDrop(key, drop) {
|
|
152
|
+
if (!claimAdaptiveReportMarker({ ...key, reason: drop.reason }))
|
|
153
|
+
return;
|
|
154
|
+
emitBackgroundFact(key, {
|
|
155
|
+
resultCode: `skipped:background_${drop.reason}`,
|
|
156
|
+
scored: drop.scored,
|
|
157
|
+
budget: drop.budget,
|
|
158
|
+
injectedCharCount: 0,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Turn end: claim any ready result, record one honest terminal fact, mark the
|
|
163
|
+
* turn ended (a late selector must discard its decision) and clear the state.
|
|
164
|
+
*
|
|
165
|
+
* Unconditional mark/clear: Stop can land while the selector is still scoring,
|
|
166
|
+
* when neither a job nor a result exists. Returning early there used to skip
|
|
167
|
+
* the marker, so the late result landed in an ended turn with no terminal fact
|
|
168
|
+
* and the console stayed on "waiting for the next request" (P1-2).
|
|
169
|
+
*/
|
|
170
|
+
function finalizeBackgroundTurn(key) {
|
|
171
|
+
const claimed = claimAdaptiveAppendResult({ ...key, now: Date.now() });
|
|
172
|
+
if (claimed.status === 'ready') {
|
|
173
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
174
|
+
reportBackgroundDrop(key, { reason: 'turn_ended', scored: true, budget: claimed.result.budgetChars });
|
|
175
|
+
}
|
|
176
|
+
else if (claimed.status === 'expired') {
|
|
177
|
+
reportBackgroundDrop(key, { reason: 'expired', scored: true, budget: 0 });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
reportBackgroundDrop(key, { reason: 'turn_ended', scored: false, budget: 0 });
|
|
181
|
+
}
|
|
182
|
+
markAdaptiveTurnEnded(key);
|
|
183
|
+
clearAdaptiveAppendTurn(key);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* "Qualified read-only" is the existing semantic declaration plus the existing
|
|
187
|
+
* shell-risk classifier: a `write` kind, an unresolved kind, or an execute
|
|
188
|
+
* command that cannot be proven `safe` never qualifies.
|
|
189
|
+
*/
|
|
190
|
+
function resolveAppendToolFacts(kind, toolInput) {
|
|
191
|
+
if (kind === 'execute')
|
|
192
|
+
return { readOnly: classifyBashRisk(true, toolInput) === 'safe' };
|
|
193
|
+
return { readOnly: kind === 'read' || kind === 'search' };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Consume-time proof. The decision may be seconds old, so the target's
|
|
197
|
+
* authorization/body is re-read through the shared revalidator, the installed
|
|
198
|
+
* hook identity must be unchanged, and the directive must still fit the
|
|
199
|
+
* Native budget reported for THIS turn.
|
|
200
|
+
*/
|
|
201
|
+
async function consumeBackgroundAppend(input) {
|
|
202
|
+
const currentIdentity = currentHookIdentity();
|
|
203
|
+
const storedIdentity = input.result.hookIdentity;
|
|
204
|
+
if (!currentIdentity || !storedIdentity)
|
|
205
|
+
return { ok: false, reason: 'version_unverified' };
|
|
206
|
+
if (currentIdentity.entryPath !== storedIdentity.entryPath || currentIdentity.mtimeMs !== storedIdentity.mtimeMs) {
|
|
207
|
+
return { ok: false, reason: 'version_changed' };
|
|
208
|
+
}
|
|
209
|
+
if (input.result.nativeActivationIds.includes(input.result.target.activationId)) {
|
|
210
|
+
return { ok: false, reason: 'already_native' };
|
|
211
|
+
}
|
|
212
|
+
const rendered = await renderAcceptedAdaptiveAppend({
|
|
213
|
+
workspaceDir: input.workspaceDir,
|
|
214
|
+
target: input.result.target,
|
|
215
|
+
signal: AbortSignal.timeout(1500),
|
|
216
|
+
});
|
|
217
|
+
if (!rendered.ok)
|
|
218
|
+
return { ok: false, reason: rendered.reason };
|
|
219
|
+
if (input.result.nativeChars + rendered.directive.length > input.result.budgetChars) {
|
|
220
|
+
return { ok: false, reason: 'budget_exhausted' };
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
ok: true,
|
|
224
|
+
directive: rendered.directive,
|
|
225
|
+
target: {
|
|
226
|
+
principleId: rendered.principle.principleId,
|
|
227
|
+
activationId: rendered.principle.activationId,
|
|
228
|
+
artifactId: rendered.principle.artifactId,
|
|
229
|
+
revisionFingerprint: input.result.target.revisionFingerprint,
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
129
233
|
/**
|
|
130
234
|
* PRI-813: admissible evaluation entry = the CANONICAL core schema guard
|
|
131
235
|
* (rc-1/rc-2, P4: no hand-rolled field copy that could drift from the
|
|
@@ -310,6 +414,11 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
310
414
|
return { stdout: {}, exitCode: 0, stderr: [diagnostic('host.codex_disabled', 'Enable PD in the selected Workspace .pd/config.yaml — in the existing "features:" block set host.codex: {enabled: true} (one flat key, not nested).')] };
|
|
311
415
|
}
|
|
312
416
|
const ingestionEnabled = flags.codex_conversation_ingestion?.enabled === true;
|
|
417
|
+
// PRI-1196: selection timing. Absent = 'sync' — every existing workspace
|
|
418
|
+
// keeps the historical behavior. Background mode never builds the sync
|
|
419
|
+
// provider, so this turn cannot be scored twice.
|
|
420
|
+
const adaptiveTiming = config.effective.config.adaptiveActivation?.timing === 'background' ? 'background' : 'sync';
|
|
421
|
+
const backgroundSelectionEnabled = flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'background';
|
|
313
422
|
if (event.kind === 'turn_complete') {
|
|
314
423
|
// Withdraw the live turn context: once the turn completes, the
|
|
315
424
|
// agent-assisted explicit entry must fail closed (turn_context_missing)
|
|
@@ -333,6 +442,19 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
333
442
|
const stderr = ingestionEnabled
|
|
334
443
|
? [...clearDiagnostics, ...await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })]
|
|
335
444
|
: [...clearDiagnostics, diagnostic('feature_disabled', 'Enable bounded conversation ingestion in the selected Workspace .pd/config.yaml — in the existing "features:" block set codex_conversation_ingestion: {enabled: true} (one flat key, not nested).')];
|
|
445
|
+
// Clean up the background turn whenever THIS turn was tracked, even if the
|
|
446
|
+
// timing was switched back to `sync` mid-turn: the started marker outlives
|
|
447
|
+
// the setting, and leaving it behind would strand a late result (P1-2).
|
|
448
|
+
if (event.context.turnId !== undefined) {
|
|
449
|
+
const backgroundKey = {
|
|
450
|
+
workspaceDir: resolution.workspaceDir,
|
|
451
|
+
stateDir: path.join(resolution.workspaceDir, '.state'),
|
|
452
|
+
sessionId: event.context.sessionId,
|
|
453
|
+
turnId: event.context.turnId,
|
|
454
|
+
};
|
|
455
|
+
if (hasAdaptiveAppendTurn(backgroundKey))
|
|
456
|
+
finalizeBackgroundTurn(backgroundKey);
|
|
457
|
+
}
|
|
336
458
|
return { stdout: {}, exitCode: 0, stderr };
|
|
337
459
|
}
|
|
338
460
|
try {
|
|
@@ -343,6 +465,9 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
343
465
|
const clearDiagnostics = cleared.ok
|
|
344
466
|
? []
|
|
345
467
|
: [diagnostic(`turn_context_${cleared.reason}`, 'The turn context could not be withdrawn; the agent-assisted explicit entry stays fail-closed only via its staleness bound. Inspect the workspace .state directory.')];
|
|
468
|
+
// A SessionStart payload carries no turn_id, so per-turn cleanup is not
|
|
469
|
+
// addressable; sweep only residue above the age bound (P2-3).
|
|
470
|
+
clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
|
|
346
471
|
const health = await createProductionHostRuntime({ hostKind: 'codex' }).health(resolution.workspaceDir);
|
|
347
472
|
if (!health.ok)
|
|
348
473
|
return { stdout: {}, exitCode: 0, stderr: [...clearDiagnostics, diagnostic(health.reason ?? 'runtime_unhealthy', health.nextAction ?? 'Inspect the Workspace runtime.')] };
|
|
@@ -450,7 +575,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
450
575
|
const adaptiveDiagnostics = [];
|
|
451
576
|
let adaptivePriorityProvider;
|
|
452
577
|
let adaptiveTurnFact = null;
|
|
453
|
-
if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
|
|
578
|
+
if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'sync') {
|
|
454
579
|
const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
|
|
455
580
|
env: _env,
|
|
456
581
|
...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
|
|
@@ -501,6 +626,63 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
501
626
|
// defaults) and must be visible on stderr (rc-9).
|
|
502
627
|
? toolSemanticsResolution.warnings.map((warning) => diagnostic(warning, 're-run this host so it refreshes its persisted tool declaration'))
|
|
503
628
|
: [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
|
|
629
|
+
// PRI-1196: the background decision is bound to THIS host turn. The
|
|
630
|
+
// `started` marker (written below) keeps ordering observation alive for the
|
|
631
|
+
// whole turn, including the scoring window in which neither a job nor a
|
|
632
|
+
// result exists (P1-1).
|
|
633
|
+
const backgroundTurnKey = backgroundSelectionEnabled && event.context.turnId !== undefined
|
|
634
|
+
? {
|
|
635
|
+
workspaceDir: resolution.workspaceDir,
|
|
636
|
+
stateDir: path.join(resolution.workspaceDir, '.state'),
|
|
637
|
+
sessionId: event.context.sessionId,
|
|
638
|
+
turnId: event.context.turnId,
|
|
639
|
+
}
|
|
640
|
+
: null;
|
|
641
|
+
// Residue sweep runs on EVERY prompt build, including after the timing was
|
|
642
|
+
// switched back to `sync` or the switch was turned off — the job carries the
|
|
643
|
+
// Owner prompt and must not wait for the feature to be re-enabled (P2-1).
|
|
644
|
+
let turnStartedNow = 'failed';
|
|
645
|
+
if (event.kind === 'before_prompt_build') {
|
|
646
|
+
clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
|
|
647
|
+
if (backgroundTurnKey)
|
|
648
|
+
turnStartedNow = markAdaptiveTurnStarted(backgroundTurnKey);
|
|
649
|
+
}
|
|
650
|
+
const toolKind = toolSemantics.resolve(event.context.toolName ?? '');
|
|
651
|
+
const appendToolFacts = resolveAppendToolFacts(toolKind, event.context.toolInput);
|
|
652
|
+
if (backgroundTurnKey
|
|
653
|
+
&& event.context.toolCallId !== undefined
|
|
654
|
+
&& (event.kind === 'before_tool_call' || event.kind === 'after_tool_call')
|
|
655
|
+
&& hasAdaptiveAppendTurn(backgroundTurnKey)) {
|
|
656
|
+
appendToolObservation({
|
|
657
|
+
...backgroundTurnKey,
|
|
658
|
+
observation: {
|
|
659
|
+
phase: event.kind === 'before_tool_call' ? 'pre' : 'post',
|
|
660
|
+
toolCallId: event.context.toolCallId,
|
|
661
|
+
toolName: event.context.toolName ?? '',
|
|
662
|
+
canonicalKind: toolKind,
|
|
663
|
+
readOnly: appendToolFacts.readOnly,
|
|
664
|
+
at: Date.now(),
|
|
665
|
+
},
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
// Capture the Native assembly facts the background job must match. The
|
|
669
|
+
// emitter receives them from the runtime; no second prompt build is needed.
|
|
670
|
+
const nativeCapture = { value: null };
|
|
671
|
+
const baseEmitter = codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext, () => adaptiveTurnFact);
|
|
672
|
+
const events = {
|
|
673
|
+
...baseEmitter,
|
|
674
|
+
recordRuntimeActivationsInjected(data) {
|
|
675
|
+
nativeCapture.value = {
|
|
676
|
+
activationIds: [...data.activationIds],
|
|
677
|
+
injectedCharCount: data.injectedCharCount,
|
|
678
|
+
budget: data.budget,
|
|
679
|
+
capacitySource: data.budgetCapacitySource,
|
|
680
|
+
capacityStatus: data.budgetCapacityStatus,
|
|
681
|
+
contextWindowTokens: data.budgetContextWindowTokens,
|
|
682
|
+
};
|
|
683
|
+
baseEmitter.recordRuntimeActivationsInjected(data);
|
|
684
|
+
},
|
|
685
|
+
};
|
|
504
686
|
const result = await createProductionHostRuntime({
|
|
505
687
|
projectDir: requestedCwd,
|
|
506
688
|
hostKind: 'codex',
|
|
@@ -514,7 +696,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
514
696
|
currentToolUseId: event.context.toolCallId ?? '',
|
|
515
697
|
toolSemantics,
|
|
516
698
|
}),
|
|
517
|
-
events
|
|
699
|
+
events,
|
|
518
700
|
}).dispatch(event);
|
|
519
701
|
// PRI-813: the shared gate's evaluation facts leave through metadata —
|
|
520
702
|
// persist them here (telemetry persistence is host-side business; the
|
|
@@ -526,7 +708,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
526
708
|
// claims only what reached stdout (codex_permission_decision_encoded).
|
|
527
709
|
// V2 rules remain suspended by the shared gate when this provider reports
|
|
528
710
|
// unavailable history; that degraded state is preserved in stderr.
|
|
529
|
-
|
|
711
|
+
let encoded = adapter.encodeOutput(result, event.kind);
|
|
530
712
|
// CR-07 (A16): the explicit-statement receipt rides as additional context
|
|
531
713
|
// so the model can answer truthfully about what happened (received +
|
|
532
714
|
// queued), instead of guessing or claiming it is still waiting for input.
|
|
@@ -538,6 +720,148 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
538
720
|
: explicitReceiptContext;
|
|
539
721
|
}
|
|
540
722
|
}
|
|
723
|
+
const backgroundDiagnostics = [];
|
|
724
|
+
// PRI-1196 — background start. The Native body is ALREADY encoded above;
|
|
725
|
+
// this only writes a single-use job and hands it to a detached process.
|
|
726
|
+
// It never awaits the decision, and the child has no inherited stdio.
|
|
727
|
+
if (backgroundTurnKey && event.kind === 'before_prompt_build') {
|
|
728
|
+
const injection = nativeCapture.value;
|
|
729
|
+
if (injection === null) {
|
|
730
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: 0, injectedCharCount: 0 });
|
|
731
|
+
backgroundDiagnostics.push(diagnostic('adaptive_background_spawn_failed:native_assembly_missing', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
const output = encoded;
|
|
735
|
+
const nativeText = output.hookSpecificOutput?.additionalContext;
|
|
736
|
+
const nativeChars = typeof nativeText === 'string' ? nativeText.length : injection.injectedCharCount;
|
|
737
|
+
try {
|
|
738
|
+
if (turnStartedNow === 'exists') {
|
|
739
|
+
// A retried/replayed UserPromptSubmit for the same turn must not
|
|
740
|
+
// start a second scoring request (P2-5). The `started` marker is the
|
|
741
|
+
// gate that survives the selector withdrawing its job.
|
|
742
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
743
|
+
}
|
|
744
|
+
else {
|
|
745
|
+
const written = writeAdaptiveAppendJob({
|
|
746
|
+
schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
|
|
747
|
+
createdAt: Date.now(),
|
|
748
|
+
sessionId: event.context.sessionId,
|
|
749
|
+
turnId: backgroundTurnKey.turnId,
|
|
750
|
+
workspaceDir: resolution.workspaceDir,
|
|
751
|
+
promptContent: event.context.promptContent ?? '',
|
|
752
|
+
nativeActivationIds: injection.activationIds,
|
|
753
|
+
nativeChars,
|
|
754
|
+
budgetChars: injection.budget,
|
|
755
|
+
hookIdentity: currentHookIdentity(),
|
|
756
|
+
});
|
|
757
|
+
if (!written.ok) {
|
|
758
|
+
if (written.reason === 'already_started') {
|
|
759
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
760
|
+
}
|
|
761
|
+
else {
|
|
762
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
763
|
+
backgroundDiagnostics.push(diagnostic('adaptive_background_job_failed', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
const spawned = spawnAdaptiveBackgroundSelection(written.jobPath);
|
|
768
|
+
if (!spawned.ok) {
|
|
769
|
+
discardAdaptiveAppendJob(written.jobPath);
|
|
770
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
771
|
+
backgroundDiagnostics.push(diagnostic(`adaptive_background_spawn_failed:${spawned.reason}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
772
|
+
}
|
|
773
|
+
else {
|
|
774
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawned', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
catch (error) {
|
|
780
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
781
|
+
backgroundDiagnostics.push(diagnostic(`adaptive_background_job_failed:${errorMessage(error)}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
// PRI-1196 — consume at a qualified read-only tool boundary of the SAME
|
|
786
|
+
// turn. The claim rename makes replay/concurrency emit at most once.
|
|
787
|
+
if (backgroundTurnKey && event.kind === 'after_tool_call' && event.context.toolCallId !== undefined) {
|
|
788
|
+
const claimed = claimAdaptiveAppendResult({ ...backgroundTurnKey, now: Date.now() });
|
|
789
|
+
if (claimed.status === 'invalid') {
|
|
790
|
+
// The claim already withdrew the unreadable result; without a fact the
|
|
791
|
+
// console would keep showing "waiting for the next request" (rc-9, P2-2).
|
|
792
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: claimed.reason ?? 'result_invalid', scored: true, budget: 0 });
|
|
793
|
+
}
|
|
794
|
+
else if (!appendToolFacts.readOnly) {
|
|
795
|
+
if (claimed.status === 'ready') {
|
|
796
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
797
|
+
reportBackgroundDrop(backgroundTurnKey, {
|
|
798
|
+
reason: toolKind === 'write' ? 'mutating_tool' : 'unknown_tool',
|
|
799
|
+
scored: true,
|
|
800
|
+
budget: claimed.result.budgetChars,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
else {
|
|
805
|
+
const ordering = evaluateAppendOrdering(readToolObservations(backgroundTurnKey), event.context.toolCallId);
|
|
806
|
+
if (!ordering.ok) {
|
|
807
|
+
if (claimed.status === 'ready') {
|
|
808
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
809
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: ordering.reason, scored: true, budget: claimed.result.budgetChars });
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
else if (claimed.status === 'expired') {
|
|
813
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: 'expired', scored: true, budget: 0 });
|
|
814
|
+
}
|
|
815
|
+
else if (claimed.status === 'ready') {
|
|
816
|
+
const consumed = await consumeBackgroundAppend({
|
|
817
|
+
workspaceDir: resolution.workspaceDir,
|
|
818
|
+
result: claimed.result,
|
|
819
|
+
});
|
|
820
|
+
if (consumed.ok) {
|
|
821
|
+
// The appended directive is additional context for the NEXT model
|
|
822
|
+
// request; Native items and their order are untouched.
|
|
823
|
+
//
|
|
824
|
+
// This calls the Codex encoder DIRECTLY instead of routing the
|
|
825
|
+
// result through the shared dispatch: `hasValidResultSemantics`
|
|
826
|
+
// (host-runtime) deliberately forbids `after_tool_call` results
|
|
827
|
+
// carrying `additionalContext`, while the Codex host contract
|
|
828
|
+
// accepts exactly that shape (codex-adapter spec §5.3.2). The
|
|
829
|
+
// shared rule encodes the host-neutral default; the Codex adapter
|
|
830
|
+
// is the host authority for its own output shape. If upstream later
|
|
831
|
+
// generalises that rule, this direct call stays correct only as
|
|
832
|
+
// long as `encodeOutput` remains the Codex output authority.
|
|
833
|
+
encoded = adapter.encodeOutput({ decision: 'observe', source: event.source, additionalContext: consumed.directive }, 'after_tool_call');
|
|
834
|
+
emitBackgroundFact(backgroundTurnKey, {
|
|
835
|
+
resultCode: 'selected:background_appended',
|
|
836
|
+
scored: true,
|
|
837
|
+
budget: claimed.result.budgetChars,
|
|
838
|
+
injectedCharCount: consumed.directive.length,
|
|
839
|
+
appended: consumed.target,
|
|
840
|
+
});
|
|
841
|
+
// Terminal fact for this turn: a later Stop must not overwrite it
|
|
842
|
+
// with "turn ended" in "上一次结果".
|
|
843
|
+
claimAdaptiveReportMarker({ ...backgroundTurnKey, reason: 'appended' });
|
|
844
|
+
try {
|
|
845
|
+
recordCodexPromptDeliveryEvidence({
|
|
846
|
+
workspaceDir: resolution.workspaceDir,
|
|
847
|
+
sessionId: event.context.sessionId,
|
|
848
|
+
turnId: backgroundTurnKey.turnId,
|
|
849
|
+
injected: [consumed.target],
|
|
850
|
+
evidenceEnabled: evidenceContext.evidenceEnabled,
|
|
851
|
+
warn: evidenceContext.warn,
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
catch (error) {
|
|
855
|
+
evidenceDiagnostics.push(diagnostic(`codex_evidence_append_failed:${errorMessage(error)}`, 'The append was already encoded; evidence replay from the durable source is safe.'));
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: consumed.reason, scored: true, budget: claimed.result.budgetChars });
|
|
860
|
+
}
|
|
861
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
541
865
|
if (result.decision === 'deny') {
|
|
542
866
|
try {
|
|
543
867
|
let liveActivationId;
|
|
@@ -580,7 +904,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
580
904
|
evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
|
|
581
905
|
}
|
|
582
906
|
}
|
|
583
|
-
const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics];
|
|
907
|
+
const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics, ...backgroundDiagnostics];
|
|
584
908
|
return { stdout: encoded, exitCode: 0, stderr };
|
|
585
909
|
}
|
|
586
910
|
catch (error) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/codex-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -183,6 +183,15 @@ export declare function getFeedbackChannelConfig(workspaceDir: string): Feedback
|
|
|
183
183
|
* Safe partial write: preserves unknown sections, validates before write.
|
|
184
184
|
*/
|
|
185
185
|
export declare function updatePrinciplesOutputLanguage(workspaceDir: string, payload: unknown): OutputLanguageResult;
|
|
186
|
+
/**
|
|
187
|
+
* Console-selectable Adaptive hosts (PRI-1127). The SAME append-only entry now
|
|
188
|
+
* serves WorkBuddy: a write touches ONLY the selected host's EXISTING flag.
|
|
189
|
+
* `codex` remains the default so the original card, its API contract and the
|
|
190
|
+
* parallel PRI-1196 Codex work stay untouched.
|
|
191
|
+
*/
|
|
192
|
+
export type AdaptiveActivationHost = 'codex' | 'workbuddy';
|
|
193
|
+
export declare const ADAPTIVE_ACTIVATION_HOST_FLAGS: Readonly<Record<AdaptiveActivationHost, string>>;
|
|
194
|
+
export declare function isAdaptiveActivationHost(value: unknown): value is AdaptiveActivationHost;
|
|
186
195
|
/**
|
|
187
196
|
* The ONE team-confirmed Decisions combination the Console offers on first
|
|
188
197
|
* setup. The endpoint/model/provider/credential-variable are frozen: the entry
|
|
@@ -201,6 +210,8 @@ export declare const ADAPTIVE_ACTIVATION_SERVICE_PRESET: {
|
|
|
201
210
|
export type AdaptiveServicePresetId = typeof ADAPTIVE_ACTIVATION_SERVICE_PRESET.id;
|
|
202
211
|
export interface AdaptiveActivationUpdateResultOk {
|
|
203
212
|
ok: true;
|
|
213
|
+
/** The ONE host whose existing switch was written. */
|
|
214
|
+
host: AdaptiveActivationHost;
|
|
204
215
|
enabled: boolean;
|
|
205
216
|
serviceConfigured: boolean;
|
|
206
217
|
}
|
|
@@ -208,21 +219,6 @@ export interface AdaptiveActivationUpdateResultErr extends ConfigUpdateFailure {
|
|
|
208
219
|
ok: false;
|
|
209
220
|
}
|
|
210
221
|
export type AdaptiveActivationUpdateResult = AdaptiveActivationUpdateResultOk | AdaptiveActivationUpdateResultErr;
|
|
211
|
-
/**
|
|
212
|
-
* Write the workspace's Adaptive Activation settings.
|
|
213
|
-
*
|
|
214
|
-
* Supported payload (both fields optional, at least one required):
|
|
215
|
-
* { enabled?: boolean; service?: 'decisions-openrouter-respan' }
|
|
216
|
-
*
|
|
217
|
-
* Guarantees:
|
|
218
|
-
* - ZERO network: saving a configuration never sends a scoring request;
|
|
219
|
-
* - append-only v1: a non-empty `replaceableActivationIds` refuses BOTH a
|
|
220
|
-
* service write and `enabled: true`, while `enabled: false` always works;
|
|
221
|
-
* - the service section is workspace-scoped and shared with the other hosts,
|
|
222
|
-
* so it is not rewritten from this Codex entry while another host has
|
|
223
|
-
* Adaptive enabled;
|
|
224
|
-
* - enable requires a complete section — it is never "enabled but unusable".
|
|
225
|
-
*/
|
|
226
222
|
export declare function updateAdaptiveActivationSettings(workspaceDir: string, payload: unknown): AdaptiveActivationUpdateResult;
|
|
227
223
|
export interface FeatureFlagUpdateResultOk {
|
|
228
224
|
ok: true;
|