@principles/host-runtime 4.3.1 → 4.5.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/adaptive-background-append.d.ts +6 -0
- package/dist/adaptive-background-append.js +4 -1
- package/dist/adaptive-decision-protocol.d.ts +18 -2
- package/dist/adaptive-decision-protocol.js +39 -9
- package/dist/adaptive-principle-context-reader.d.ts +79 -0
- package/dist/adaptive-principle-context-reader.js +303 -0
- package/dist/adaptive-priority-provider.d.ts +33 -0
- package/dist/adaptive-priority-provider.js +68 -2
- package/dist/adaptive-selection.d.ts +16 -0
- package/dist/adaptive-selection.js +23 -1
- package/dist/codex-legacy-registration.js +10 -2
- package/dist/conversation-ingestion/pipeline.d.ts +8 -0
- package/dist/conversation-ingestion/pipeline.js +179 -7
- package/dist/degraded-enforcement-marker.js +16 -2
- package/dist/diagnostician-auto-run.js +10 -0
- package/dist/governance-observation-store.d.ts +44 -0
- package/dist/governance-observation-store.js +84 -1
- package/dist/governance-signal-admission.js +7 -0
- package/dist/governance-trajectory-turn-reader.d.ts +30 -0
- package/dist/governance-trajectory-turn-reader.js +47 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +10 -0
- package/dist/intent-doc-reader.d.ts +70 -0
- package/dist/intent-doc-reader.js +292 -0
- package/dist/product-telemetry/service.js +86 -20
- package/package.json +4 -4
|
@@ -399,7 +399,17 @@ function applyObservation({ db, rolloutRowId, input, workspaceDir, maxVisibleTex
|
|
|
399
399
|
fill('phase', boundedString(input.phase, MAX_TEXT_BOUND));
|
|
400
400
|
fill('tool_use_id', boundedString(input.toolUseId, MAX_TEXT_BOUND));
|
|
401
401
|
fill('transcript_tool_call_id', boundedString(input.transcriptToolCallId, MAX_TEXT_BOUND));
|
|
402
|
-
|
|
402
|
+
// A terminal retention class (expired / quarantined) must not regain a body
|
|
403
|
+
// through replay enrichment — the same P2-review rule the tool-facts path
|
|
404
|
+
// below already enforces. Without this guard an expired row whose text was
|
|
405
|
+
// NULLed by retention could be refilled by a later catch-up replay of the
|
|
406
|
+
// same logical key, and the turn reader would then serve post-retention
|
|
407
|
+
// text into a diagnosis context.
|
|
408
|
+
const replayRetentionClass = rowField(existing, 'retention_class');
|
|
409
|
+
const replayRowActive = replayRetentionClass === 'operational' || replayRetentionClass === 'promoted';
|
|
410
|
+
if (replayRowActive) {
|
|
411
|
+
fill('visible_text', input.visibleText !== undefined ? boundVisibleText(input.visibleText) : null);
|
|
412
|
+
}
|
|
403
413
|
const incomingFacts = input.toolFacts !== undefined ? safeJson({ facts: sanitizeValue(input.toolFacts, 0, workspaceDir) }) : null;
|
|
404
414
|
// Cross-window tool completion (P1): the call row is partial and the result
|
|
405
415
|
// arrives under the same logical key from a later decode window. Merge the
|
|
@@ -801,6 +811,71 @@ export function listGovernanceUncheckpointedSessions(args) {
|
|
|
801
811
|
close();
|
|
802
812
|
}
|
|
803
813
|
}
|
|
814
|
+
/**
|
|
815
|
+
* PRI-1265: retained turn texts for ONE session, oldest-first — the read side
|
|
816
|
+
* behind the shared TrajectoryTurnReader adapter (CLI diagnose/pain retry,
|
|
817
|
+
* Codex/WorkBuddy workers, host-runtime auto-run). Review-round hardening
|
|
818
|
+
* (2026-11-18):
|
|
819
|
+
* - ONLY `retention_class IN ('operational','promoted')` rows are served —
|
|
820
|
+
* a replay can refill an expired row's body through the enrichment path,
|
|
821
|
+
* so `visible_text IS NOT NULL` alone is not a retention verdict;
|
|
822
|
+
* - the NEWEST `limit` turns are returned (the reported/last turn must not
|
|
823
|
+
* fall off a long session's window just because it is recent);
|
|
824
|
+
* - exact `rollout_identity` rows win over `root_session_id` rows, so a
|
|
825
|
+
* subagent rollout (whose root_session_id points at its parent thread)
|
|
826
|
+
* is never mixed into the parent's own conversation;
|
|
827
|
+
* - an optional `hostKind` keeps verification per-host (session ids are
|
|
828
|
+
* unique per `(host_kind, rollout_identity)`, not globally).
|
|
829
|
+
*/
|
|
830
|
+
export function listGovernanceTurnTexts(input) {
|
|
831
|
+
if (input.sessionId.trim().length === 0)
|
|
832
|
+
return { ok: true, turns: [] };
|
|
833
|
+
const opened = openStore(input.workspaceDir, input.databaseFactory);
|
|
834
|
+
if (!('db' in opened))
|
|
835
|
+
return opened;
|
|
836
|
+
const { db, close } = opened;
|
|
837
|
+
try {
|
|
838
|
+
const limit = Math.min(Math.max(input.limit ?? 200, 1), 2000);
|
|
839
|
+
const newestThenAsc = (identityColumn) => db.prepare('SELECT id, source_ordinal, visible_text, observed_at FROM ('
|
|
840
|
+
+ `SELECT id, source_ordinal, visible_text, observed_at, source_order FROM governance_observations `
|
|
841
|
+
+ `WHERE kind = ? AND ${identityColumn} = ? AND visible_text IS NOT NULL `
|
|
842
|
+
+ `AND retention_class IN ('operational', 'promoted')`
|
|
843
|
+
+ `${input.hostKind !== undefined ? ' AND host_kind = ?' : ''} `
|
|
844
|
+
+ 'ORDER BY observed_at DESC, source_order DESC, id DESC LIMIT ?'
|
|
845
|
+
+ ') ORDER BY observed_at ASC, source_order ASC, id ASC').all(...(input.hostKind !== undefined
|
|
846
|
+
? [input.kind, input.sessionId, input.hostKind, limit]
|
|
847
|
+
: [input.kind, input.sessionId, limit]));
|
|
848
|
+
// Exact session rows first; the root_session_id fallback keeps historical
|
|
849
|
+
// (pre-rollout-identity) rows readable but can no longer drag another
|
|
850
|
+
// rollout's turns (e.g. a subagent's) into this session's context.
|
|
851
|
+
let rows = newestThenAsc('rollout_identity');
|
|
852
|
+
if (rows.length === 0)
|
|
853
|
+
rows = newestThenAsc('root_session_id');
|
|
854
|
+
const turns = [];
|
|
855
|
+
for (const row of rows) {
|
|
856
|
+
const id = Number(rowField(row, 'id'));
|
|
857
|
+
const visibleText = rowField(row, 'visible_text');
|
|
858
|
+
const observedAt = rowField(row, 'observed_at');
|
|
859
|
+
if (!Number.isFinite(id) || typeof visibleText !== 'string' || typeof observedAt !== 'string')
|
|
860
|
+
continue;
|
|
861
|
+
const sourceOrdinal = rowField(row, 'source_ordinal');
|
|
862
|
+
turns.push({
|
|
863
|
+
id,
|
|
864
|
+
sourceOrdinal: typeof sourceOrdinal === 'number' ? sourceOrdinal : turns.length,
|
|
865
|
+
visibleText,
|
|
866
|
+
observedAt,
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
return { ok: true, turns };
|
|
870
|
+
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
873
|
+
return { ok: false, reason: `governance_turn_texts_failed:${detail}`, nextAction: 'Inspect the workspace trajectory.db; the diagnosis context window degraded to no trajectory fallback.' };
|
|
874
|
+
}
|
|
875
|
+
finally {
|
|
876
|
+
close();
|
|
877
|
+
}
|
|
878
|
+
}
|
|
804
879
|
export function listGovernanceObservations(input) {
|
|
805
880
|
const opened = openStore(input.workspaceDir, input.databaseFactory);
|
|
806
881
|
if (!('db' in opened))
|
|
@@ -813,6 +888,14 @@ export function listGovernanceObservations(input) {
|
|
|
813
888
|
conditions.push('rollout_identity = ?');
|
|
814
889
|
values.push(input.rolloutIdentity);
|
|
815
890
|
}
|
|
891
|
+
if (input.hostKind !== undefined) {
|
|
892
|
+
conditions.push('host_kind = ?');
|
|
893
|
+
values.push(input.hostKind);
|
|
894
|
+
}
|
|
895
|
+
if (input.hostTurnId !== undefined) {
|
|
896
|
+
conditions.push('host_turn_id = ?');
|
|
897
|
+
values.push(input.hostTurnId);
|
|
898
|
+
}
|
|
816
899
|
if (input.retentionClass !== undefined) {
|
|
817
900
|
conditions.push('retention_class = ?');
|
|
818
901
|
values.push(input.retentionClass);
|
|
@@ -39,6 +39,7 @@ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, P
|
|
|
39
39
|
import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
|
|
40
40
|
import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
|
|
41
41
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
42
|
+
import { createHostIntentDocReader } from './intent-doc-reader.js';
|
|
42
43
|
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
43
44
|
// ─── Shared detector constants (one truth for both hosts) ───────────────────
|
|
44
45
|
export const GOVERNANCE_STRONG_PAIN_SCORE = 70;
|
|
@@ -1859,6 +1860,12 @@ export async function ensureGovernanceDiagnosticianTask(input) {
|
|
|
1859
1860
|
asyncMode: true,
|
|
1860
1861
|
effectiveConfig: config.effective,
|
|
1861
1862
|
getEnvVar: (name) => process.env[name],
|
|
1863
|
+
// PRI-1233 / SPEC §9.2: governance-admitted pains capture the Stage A
|
|
1864
|
+
// intent snapshot through the neutral host reader bound to the
|
|
1865
|
+
// ADMITTED workspace and ITS freshly loaded effectiveConfig. The
|
|
1866
|
+
// marker, canonical pain id, task id and idempotency semantics above
|
|
1867
|
+
// are untouched; a reader failure degrades inside Stage A only.
|
|
1868
|
+
intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
|
|
1862
1869
|
});
|
|
1863
1870
|
const result = await service.recordPain({
|
|
1864
1871
|
painId: input.canonicalPainId,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1265: a TrajectoryTurnReader over the workspace's governance observation
|
|
3
|
+
* store (trajectory.db) — the SAME authorized store conversation ingestion
|
|
4
|
+
* writes. OpenClaw's hook passes its own TrajectoryDatabase adapter; Codex /
|
|
5
|
+
* WorkBuddy workers and the pd-cli diagnosis entries had NO reader at all, so
|
|
6
|
+
* a bound session with stored turns still produced a context window without
|
|
7
|
+
* the original text. This adapter closes that gap with one implementation the
|
|
8
|
+
* CLI (`pd diagnose run`, `pd pain retry`), the Codex/WorkBuddy workers and
|
|
9
|
+
* the host-runtime auto-run all inject.
|
|
10
|
+
*
|
|
11
|
+
* Read semantics (fail-open to [] — the assembler records the empty fallback
|
|
12
|
+
* as an ambiguity note, rc-9):
|
|
13
|
+
* - user turns: `kind='user_turn'` rows with retained `visible_text`;
|
|
14
|
+
* - assistant turns: `kind='assistant_turn'` rows with retained text;
|
|
15
|
+
* - a session matches by `root_session_id` OR `rollout_identity` (Codex
|
|
16
|
+
* rollout uuid / WorkBuddy sessionId), so either spelling of the same
|
|
17
|
+
* session resolves;
|
|
18
|
+
* - expired/quarantined rows are excluded naturally: retention NULLed their
|
|
19
|
+
* text at write time (PRI-1179), so nothing new is re-derived here.
|
|
20
|
+
*/
|
|
21
|
+
import type { TrajectoryTurnReader } from '@principles/core/runtime';
|
|
22
|
+
/**
|
|
23
|
+
* Build the governance-observation-backed turn reader for a workspace. The
|
|
24
|
+
* returned object is cheap to construct per invocation; each list call opens
|
|
25
|
+
* the store read (no cached handle across worker cycles, so a replaced
|
|
26
|
+
* database mid-run can never serve stale turns).
|
|
27
|
+
*/
|
|
28
|
+
export declare function createGovernanceTrajectoryTurnReader(args: {
|
|
29
|
+
readonly workspaceDir: string;
|
|
30
|
+
}): TrajectoryTurnReader;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { listGovernanceTurnTexts } from './governance-observation-store.js';
|
|
2
|
+
/** Bound on turns per list call — the assembler bounds the window again. */
|
|
3
|
+
const MAX_TURNS_PER_SESSION = 200;
|
|
4
|
+
function readTurnRows(workspaceDir, kind, sessionId) {
|
|
5
|
+
if (sessionId.trim().length === 0)
|
|
6
|
+
return [];
|
|
7
|
+
const result = listGovernanceTurnTexts({
|
|
8
|
+
workspaceDir,
|
|
9
|
+
kind,
|
|
10
|
+
sessionId,
|
|
11
|
+
limit: MAX_TURNS_PER_SESSION,
|
|
12
|
+
});
|
|
13
|
+
// Unreadable store: the empty result surfaces as an assembler ambiguity
|
|
14
|
+
// note ("no turns found"), never as a fabricated window.
|
|
15
|
+
return result.ok ? result.turns : [];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Build the governance-observation-backed turn reader for a workspace. The
|
|
19
|
+
* returned object is cheap to construct per invocation; each list call opens
|
|
20
|
+
* the store read (no cached handle across worker cycles, so a replaced
|
|
21
|
+
* database mid-run can never serve stale turns).
|
|
22
|
+
*/
|
|
23
|
+
export function createGovernanceTrajectoryTurnReader(args) {
|
|
24
|
+
return {
|
|
25
|
+
listUserTurnsForSession(sessionId) {
|
|
26
|
+
return readTurnRows(args.workspaceDir, 'user_turn', sessionId).map((row, index) => ({
|
|
27
|
+
id: row.id,
|
|
28
|
+
turnIndex: row.sourceOrdinal >= 0 ? row.sourceOrdinal : index,
|
|
29
|
+
rawExcerpt: row.visibleText,
|
|
30
|
+
correctionDetected: false,
|
|
31
|
+
correctionCue: null,
|
|
32
|
+
createdAt: row.observedAt,
|
|
33
|
+
}));
|
|
34
|
+
},
|
|
35
|
+
listAssistantTurns(sessionId) {
|
|
36
|
+
return readTurnRows(args.workspaceDir, 'assistant_turn', sessionId).map((row) => ({
|
|
37
|
+
id: row.id,
|
|
38
|
+
sessionId,
|
|
39
|
+
runId: '',
|
|
40
|
+
provider: '',
|
|
41
|
+
model: '',
|
|
42
|
+
sanitizedText: row.visibleText,
|
|
43
|
+
createdAt: row.observedAt,
|
|
44
|
+
}));
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -14,10 +14,12 @@ export * from './prompt-injection-event-evidence.js';
|
|
|
14
14
|
export * from './prompt-injection-budget-observation.js';
|
|
15
15
|
export * from './rulecode-event-collection.js';
|
|
16
16
|
export * from './pd-config.js';
|
|
17
|
+
export { resolvePdHome } from '@principles/install-layout';
|
|
17
18
|
export * from './production-rulehost-gate.js';
|
|
18
19
|
export * from './rule-implementation-runtime.js';
|
|
19
20
|
export * from './production-pain-evidence.js';
|
|
20
21
|
export * from './governance-observation-store.js';
|
|
22
|
+
export * from './governance-trajectory-turn-reader.js';
|
|
21
23
|
export * from './trajectory-retention.js';
|
|
22
24
|
export * from './conversation-ingestion/index.js';
|
|
23
25
|
export * from './governance-signal-admission.js';
|
|
@@ -146,3 +148,4 @@ export { createCodexArtificerTrustedFactsPort } from './codex-artificer-trusted-
|
|
|
146
148
|
export { revalidateAdaptivePrinciple, createAdaptivePrincipleRevalidator, type AdaptivePrincipleReader } from './adaptive-principle-revalidation.js';
|
|
147
149
|
export * from './adaptive-journal-reconciliation.js';
|
|
148
150
|
export * from './adaptive-behavior-linkage.js';
|
|
151
|
+
export * from './intent-doc-reader.js';
|
package/dist/index.js
CHANGED
|
@@ -25,10 +25,16 @@ export * from './prompt-injection-budget-observation.js';
|
|
|
25
25
|
// review and the Console Owner review (5B deduplication).
|
|
26
26
|
export * from './rulecode-event-collection.js';
|
|
27
27
|
export * from './pd-config.js';
|
|
28
|
+
// PD Home path authority is surfaced through host-runtime so host plugins do
|
|
29
|
+
// not need a second dependency or a private home-directory resolver.
|
|
30
|
+
export { resolvePdHome } from '@principles/install-layout';
|
|
28
31
|
export * from './production-rulehost-gate.js';
|
|
29
32
|
export * from './rule-implementation-runtime.js';
|
|
30
33
|
export * from './production-pain-evidence.js';
|
|
31
34
|
export * from './governance-observation-store.js';
|
|
35
|
+
// PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
|
|
36
|
+
// pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
|
|
37
|
+
export * from './governance-trajectory-turn-reader.js';
|
|
32
38
|
// SPEC-PD-TR-001: trajectory retention I/O boundary (lock + marker + export
|
|
33
39
|
// list + explicit VACUUM). The policy/batch engine is pure and lives in
|
|
34
40
|
// `@principles/core/runtime`.
|
|
@@ -425,3 +431,7 @@ export { revalidateAdaptivePrinciple, createAdaptivePrincipleRevalidator } from
|
|
|
425
431
|
export * from './adaptive-journal-reconciliation.js';
|
|
426
432
|
// PRI-1114: read-only behavior evidence linkage (no writes, no model runs).
|
|
427
433
|
export * from './adaptive-behavior-linkage.js';
|
|
434
|
+
// PRI-1229 / SPEC-PD-INTENT-UNIFICATION-001 §9.3: neutral host IntentDocReader
|
|
435
|
+
// shared by PD CLI (pain record / diagnose / pain retry) and governance
|
|
436
|
+
// admission. Business semantics stay in Core; this is the I/O adapter only.
|
|
437
|
+
export * from './intent-doc-reader.js';
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1229 / SPEC-PD-INTENT-UNIFICATION-001 §9.3 — neutral host IntentDocReader.
|
|
3
|
+
*
|
|
4
|
+
* A host-neutral adapter implementing Core's `IntentDocReader` port for the
|
|
5
|
+
* production entry points that live outside the OpenClaw plugin: PD CLI
|
|
6
|
+
* (pain record / diagnose / pain retry) and host-runtime governance admission.
|
|
7
|
+
*
|
|
8
|
+
* Why a separate thin adapter instead of sharing the plugin's
|
|
9
|
+
* `safeReadIntentDoc()` (SPEC §9.3 rule 4): the plugin package is a
|
|
10
|
+
* host-specific delivery unit (ClawHub tarball) and must never become a
|
|
11
|
+
* dependency of pd-cli or host-runtime — that would invert the dependency
|
|
12
|
+
* direction. All BUSINESS logic stays in Core and is shared by every entry
|
|
13
|
+
* point (no second copy):
|
|
14
|
+
* - flag predicate: `isIntentAnchoringEnabled(effectiveConfig)`
|
|
15
|
+
* - content hash: `computeIntentContentHash(raw)`
|
|
16
|
+
* - path naming: `getIntentFilename(lang)`
|
|
17
|
+
* This module only performs the file read and maps it onto the Core port
|
|
18
|
+
* result — the same responsibility split as the plugin-side adapter.
|
|
19
|
+
*
|
|
20
|
+
* Contract (SPEC §12 / §13.1, mirroring the plugin reader):
|
|
21
|
+
* - Flag check FIRST from the entry-provided effectiveConfig. Flag off →
|
|
22
|
+
* `flag_disabled` WITHOUT any filesystem or cache access.
|
|
23
|
+
* - 32KB cap enforced on the actually-read bytes (single open descriptor:
|
|
24
|
+
* no stat-then-read TOCTOU; the fixed buffer also bounds a file that
|
|
25
|
+
* grows while being read).
|
|
26
|
+
* - `not_found` / `oversized` / `read_error` degrade with structured
|
|
27
|
+
* reason + nextAction. NEVER throws.
|
|
28
|
+
* - TTL + mtime cache keyed `${workspaceDir}:${lang}` — the same mechanism
|
|
29
|
+
* as the plugin reader (SPEC §12.1: 60s TTL, mtime verified).
|
|
30
|
+
*/
|
|
31
|
+
import { type EffectivePdConfig, type IntentDocReader, type IntentLang } from '@principles/core/runtime';
|
|
32
|
+
/**
|
|
33
|
+
* Reset the intent doc cache for test isolation (same semantics as the
|
|
34
|
+
* plugin reader's resetIntentDocCacheForTest).
|
|
35
|
+
*/
|
|
36
|
+
export declare function resetHostIntentDocCacheForTest(workspaceDir?: string, lang?: IntentLang): void;
|
|
37
|
+
/**
|
|
38
|
+
* Detect which language's INTENT file exists on disk (zh-CN first, then en,
|
|
39
|
+
* default zh-CN) — the same resolution the OpenClaw plugin adapter applies.
|
|
40
|
+
*
|
|
41
|
+
* Filesystem-touching by design: callers MUST only invoke it when the
|
|
42
|
+
* intent_engineering flag is already known to be on, so flag-off keeps the
|
|
43
|
+
* zero-file-access contract.
|
|
44
|
+
*/
|
|
45
|
+
export declare function resolveHostIntentLang(workspaceDir: string): IntentLang;
|
|
46
|
+
export interface HostIntentDocReaderOptions {
|
|
47
|
+
/** Absolute path to the workspace root the reader is bound to. */
|
|
48
|
+
readonly workspaceDir: string;
|
|
49
|
+
/**
|
|
50
|
+
* Effective PD config from the CURRENT production entry point. The flag
|
|
51
|
+
* predicate (`isIntentAnchoringEnabled`) is Core-owned — this adapter never
|
|
52
|
+
* re-reads config and never re-implements the flag decision.
|
|
53
|
+
*/
|
|
54
|
+
readonly effectiveConfig: EffectivePdConfig | undefined;
|
|
55
|
+
/** Explicit language binding. When omitted, resolved lazily per read. */
|
|
56
|
+
readonly lang?: IntentLang;
|
|
57
|
+
/** Optional logger for debug-level diagnostics. */
|
|
58
|
+
readonly logger?: {
|
|
59
|
+
debug?: (msg: string) => void;
|
|
60
|
+
warn?: (msg: string) => void;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Create an IntentDocReader bound to a specific workspace.
|
|
65
|
+
*
|
|
66
|
+
* The returned reader is a closure over (workspaceDir, effectiveConfig, lang)
|
|
67
|
+
* — each `readIntentDoc()` call re-evaluates the Core flag predicate against
|
|
68
|
+
* the captured config, then reads through the TTL+mtime cache.
|
|
69
|
+
*/
|
|
70
|
+
export declare function createHostIntentDocReader(options: HostIntentDocReaderOptions): IntentDocReader;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1229 / SPEC-PD-INTENT-UNIFICATION-001 §9.3 — neutral host IntentDocReader.
|
|
3
|
+
*
|
|
4
|
+
* A host-neutral adapter implementing Core's `IntentDocReader` port for the
|
|
5
|
+
* production entry points that live outside the OpenClaw plugin: PD CLI
|
|
6
|
+
* (pain record / diagnose / pain retry) and host-runtime governance admission.
|
|
7
|
+
*
|
|
8
|
+
* Why a separate thin adapter instead of sharing the plugin's
|
|
9
|
+
* `safeReadIntentDoc()` (SPEC §9.3 rule 4): the plugin package is a
|
|
10
|
+
* host-specific delivery unit (ClawHub tarball) and must never become a
|
|
11
|
+
* dependency of pd-cli or host-runtime — that would invert the dependency
|
|
12
|
+
* direction. All BUSINESS logic stays in Core and is shared by every entry
|
|
13
|
+
* point (no second copy):
|
|
14
|
+
* - flag predicate: `isIntentAnchoringEnabled(effectiveConfig)`
|
|
15
|
+
* - content hash: `computeIntentContentHash(raw)`
|
|
16
|
+
* - path naming: `getIntentFilename(lang)`
|
|
17
|
+
* This module only performs the file read and maps it onto the Core port
|
|
18
|
+
* result — the same responsibility split as the plugin-side adapter.
|
|
19
|
+
*
|
|
20
|
+
* Contract (SPEC §12 / §13.1, mirroring the plugin reader):
|
|
21
|
+
* - Flag check FIRST from the entry-provided effectiveConfig. Flag off →
|
|
22
|
+
* `flag_disabled` WITHOUT any filesystem or cache access.
|
|
23
|
+
* - 32KB cap enforced on the actually-read bytes (single open descriptor:
|
|
24
|
+
* no stat-then-read TOCTOU; the fixed buffer also bounds a file that
|
|
25
|
+
* grows while being read).
|
|
26
|
+
* - `not_found` / `oversized` / `read_error` degrade with structured
|
|
27
|
+
* reason + nextAction. NEVER throws.
|
|
28
|
+
* - TTL + mtime cache keyed `${workspaceDir}:${lang}` — the same mechanism
|
|
29
|
+
* as the plugin reader (SPEC §12.1: 60s TTL, mtime verified).
|
|
30
|
+
*/
|
|
31
|
+
import * as fs from 'node:fs';
|
|
32
|
+
import * as path from 'node:path';
|
|
33
|
+
import { INTENT_MAX_BYTES, computeIntentContentHash, getIntentFilename, isIntentAnchoringEnabled, } from '@principles/core/runtime';
|
|
34
|
+
/** True when a filesystem call failed because the path does not exist. */
|
|
35
|
+
function isEnoent(err) {
|
|
36
|
+
if (!(err instanceof Error))
|
|
37
|
+
return false;
|
|
38
|
+
const descriptor = Object.getOwnPropertyDescriptor(err, 'code');
|
|
39
|
+
return descriptor?.value === 'ENOENT';
|
|
40
|
+
}
|
|
41
|
+
const INTENT_DIR = '.principles';
|
|
42
|
+
const INTENT_CACHE_TTL_MS = 60_000; // 1 minute (SPEC §12.1, same as plugin reader)
|
|
43
|
+
/**
|
|
44
|
+
* PR #2684 P1: how many times a single readIntentDoc() call may re-open the
|
|
45
|
+
* file when the stability check fails (writer rewriting the file while we
|
|
46
|
+
* read). Bounded, not a sleep-and-hope loop: after the budget is exhausted
|
|
47
|
+
* the read degrades to the structured read_error result (rc-9) rather than
|
|
48
|
+
* caching possibly-torn content.
|
|
49
|
+
*/
|
|
50
|
+
const INTENT_STABILITY_RETRIES = 2;
|
|
51
|
+
const _intentDocCache = new Map();
|
|
52
|
+
function identityOf(bigStat) {
|
|
53
|
+
return {
|
|
54
|
+
dev: bigStat.dev,
|
|
55
|
+
ino: bigStat.ino,
|
|
56
|
+
size: bigStat.size,
|
|
57
|
+
// Full ns precision (CodeRabbit PR #2684 r2): truncating to milliseconds
|
|
58
|
+
// would miss an in-place same-millisecond rewrite whose size is unchanged.
|
|
59
|
+
mtimeNs: bigStat.mtimeNs,
|
|
60
|
+
ctimeNs: bigStat.ctimeNs,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function sameIdentity(a, b) {
|
|
64
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size
|
|
65
|
+
&& a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Reset the intent doc cache for test isolation (same semantics as the
|
|
69
|
+
* plugin reader's resetIntentDocCacheForTest).
|
|
70
|
+
*/
|
|
71
|
+
export function resetHostIntentDocCacheForTest(workspaceDir, lang) {
|
|
72
|
+
if (workspaceDir === undefined) {
|
|
73
|
+
_intentDocCache.clear();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (lang !== undefined) {
|
|
77
|
+
_intentDocCache.delete(`${workspaceDir}:${lang}`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const prefix = `${workspaceDir}:`;
|
|
81
|
+
for (const key of _intentDocCache.keys()) {
|
|
82
|
+
if (key.startsWith(prefix))
|
|
83
|
+
_intentDocCache.delete(key);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// ── Language resolution ───────────────────────────────────────────────────────
|
|
87
|
+
/**
|
|
88
|
+
* Detect which language's INTENT file exists on disk (zh-CN first, then en,
|
|
89
|
+
* default zh-CN) — the same resolution the OpenClaw plugin adapter applies.
|
|
90
|
+
*
|
|
91
|
+
* Filesystem-touching by design: callers MUST only invoke it when the
|
|
92
|
+
* intent_engineering flag is already known to be on, so flag-off keeps the
|
|
93
|
+
* zero-file-access contract.
|
|
94
|
+
*/
|
|
95
|
+
export function resolveHostIntentLang(workspaceDir) {
|
|
96
|
+
const zhPath = path.join(workspaceDir, INTENT_DIR, getIntentFilename('zh-CN'));
|
|
97
|
+
if (fs.existsSync(zhPath))
|
|
98
|
+
return 'zh-CN';
|
|
99
|
+
const enPath = path.join(workspaceDir, INTENT_DIR, getIntentFilename('en'));
|
|
100
|
+
if (fs.existsSync(enPath))
|
|
101
|
+
return 'en';
|
|
102
|
+
return 'zh-CN';
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Create an IntentDocReader bound to a specific workspace.
|
|
106
|
+
*
|
|
107
|
+
* The returned reader is a closure over (workspaceDir, effectiveConfig, lang)
|
|
108
|
+
* — each `readIntentDoc()` call re-evaluates the Core flag predicate against
|
|
109
|
+
* the captured config, then reads through the TTL+mtime cache.
|
|
110
|
+
*/
|
|
111
|
+
export function createHostIntentDocReader(options) {
|
|
112
|
+
const { workspaceDir, effectiveConfig, logger } = options;
|
|
113
|
+
const { lang: boundLang } = options;
|
|
114
|
+
return {
|
|
115
|
+
readIntentDoc() {
|
|
116
|
+
// SPEC §12 / §13.1 — flag check FIRST, from the entry-provided config.
|
|
117
|
+
// Flag off → no filesystem access, no cache access.
|
|
118
|
+
if (!isIntentAnchoringEnabled(effectiveConfig)) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
found: false,
|
|
122
|
+
flagEnabled: false,
|
|
123
|
+
reason: 'flag_disabled',
|
|
124
|
+
nextAction: 'Enable the intent_engineering feature flag in .pd/config.yaml to read the INTENT document.',
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
// Language is resolved lazily (AFTER the flag gate) so a flag-off read
|
|
128
|
+
// performs zero filesystem probes.
|
|
129
|
+
const lang = boundLang ?? resolveHostIntentLang(workspaceDir);
|
|
130
|
+
const cacheKey = `${workspaceDir}:${lang}`;
|
|
131
|
+
const filePath = path.resolve(workspaceDir, INTENT_DIR, getIntentFilename(lang));
|
|
132
|
+
const now = Date.now();
|
|
133
|
+
const cached = _intentDocCache.get(cacheKey);
|
|
134
|
+
if (cached && (now - cached.loadedAt) < INTENT_CACHE_TTL_MS) {
|
|
135
|
+
try {
|
|
136
|
+
// PR #2684 P1: cache-hit validation checks FILE IDENTITY, not just
|
|
137
|
+
// mtime — a same-length rewrite or an atomic replace that kept the
|
|
138
|
+
// size would otherwise pass an mtime-only check on filesystems with
|
|
139
|
+
// coarse timestamps. dev+ino+size+mtimeMs(+ctimeMs) must all match.
|
|
140
|
+
const stat = fs.statSync(filePath, { bigint: true });
|
|
141
|
+
if (sameIdentity(identityOf(stat), cached.identity)) {
|
|
142
|
+
return { ok: true, found: true, flagEnabled: true, doc: cached.reference };
|
|
143
|
+
}
|
|
144
|
+
// Identity mismatch → fall through to the fresh-read path.
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// File deleted since caching — fall through to the fresh-read path
|
|
148
|
+
// (which will report not_found). Never serve a doc for a gone file.
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// PR #2684 P1: bounded re-read loop. A writer that rewrites/atomically
|
|
152
|
+
// replaces the file WHILE we read it can invalidate every consistency
|
|
153
|
+
// check of that attempt; we retry a bounded number of times and, if the
|
|
154
|
+
// file never stabilizes, degrade to the structured read_error result
|
|
155
|
+
// instead of caching torn content (rc-3 / rc-9).
|
|
156
|
+
for (let attempt = 0; attempt <= INTENT_STABILITY_RETRIES; attempt += 1) {
|
|
157
|
+
try {
|
|
158
|
+
// Open once and let ENOENT be the not-found signal — a path-based
|
|
159
|
+
// existsSync before the open is a check/use race.
|
|
160
|
+
let fd;
|
|
161
|
+
try {
|
|
162
|
+
fd = fs.openSync(filePath, 'r');
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
if (!isEnoent(err))
|
|
166
|
+
throw err;
|
|
167
|
+
_intentDocCache.delete(cacheKey);
|
|
168
|
+
return {
|
|
169
|
+
ok: false,
|
|
170
|
+
found: false,
|
|
171
|
+
flagEnabled: true,
|
|
172
|
+
reason: 'not_found',
|
|
173
|
+
nextAction: `Create .principles/${getIntentFilename(lang)} using "pd intent init".`,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const openStat = fs.fstatSync(fd, { bigint: true });
|
|
178
|
+
if (openStat.size > BigInt(INTENT_MAX_BYTES)) {
|
|
179
|
+
_intentDocCache.delete(cacheKey);
|
|
180
|
+
return {
|
|
181
|
+
ok: false,
|
|
182
|
+
found: true,
|
|
183
|
+
flagEnabled: true,
|
|
184
|
+
reason: 'oversized',
|
|
185
|
+
nextAction: `${getIntentFilename(lang)} exceeds ${INTENT_MAX_BYTES} bytes (${openStat.size} bytes). Reduce content.`,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
// Read at most INTENT_MAX_BYTES + 1 bytes on the SAME descriptor:
|
|
189
|
+
// the fixed buffer prevents concurrent growth from turning the size
|
|
190
|
+
// check into an unbounded allocation.
|
|
191
|
+
const buffer = Buffer.allocUnsafe(INTENT_MAX_BYTES + 1);
|
|
192
|
+
const bytesRead = fs.readSync(fd, buffer, 0, buffer.byteLength, 0);
|
|
193
|
+
const finalStat = fs.fstatSync(fd, { bigint: true });
|
|
194
|
+
if (bytesRead > INTENT_MAX_BYTES || finalStat.size > BigInt(INTENT_MAX_BYTES)) {
|
|
195
|
+
_intentDocCache.delete(cacheKey);
|
|
196
|
+
return {
|
|
197
|
+
ok: false,
|
|
198
|
+
found: true,
|
|
199
|
+
flagEnabled: true,
|
|
200
|
+
reason: 'oversized',
|
|
201
|
+
nextAction: `${getIntentFilename(lang)} exceeds ${INTENT_MAX_BYTES} bytes (${Math.max(Number(openStat.size), Number(finalStat.size), bytesRead)} bytes observed). Reduce content.`,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const raw = buffer.toString('utf8', 0, bytesRead);
|
|
205
|
+
// PR #2684 P1 (Owner directive): the bytes may be TORN even when
|
|
206
|
+
// the size matches — a writer that rewrites the file in place to
|
|
207
|
+
// NEW content of the SAME length, or atomically replaces the path
|
|
208
|
+
// mid-read, leaves `raw` describing a file that no longer exists.
|
|
209
|
+
// Stability requires ALL of:
|
|
210
|
+
// a) full metadata equality (dev/ino/size/mtime/ctime) between
|
|
211
|
+
// the pre-read and post-read fstat of the SAME descriptor —
|
|
212
|
+
// a same-length rewrite bumps mtime, an atomic replace makes
|
|
213
|
+
// the fd point at an unlinked inode whose link count dropped;
|
|
214
|
+
// b) the PATH still resolves to the SAME dev/ino the fd holds —
|
|
215
|
+
// an atomic replace leaves the fd on the old inode while the
|
|
216
|
+
// path now names the new one;
|
|
217
|
+
// c) bytesRead equals the file size (complete, not torn read).
|
|
218
|
+
// Any failure → serve the bytes read but do NOT cache, and retry
|
|
219
|
+
// within the bounded budget; exhausted → structured read_error.
|
|
220
|
+
const postPathStat = fs.statSync(filePath, { bigint: true });
|
|
221
|
+
const stable = sameIdentity(identityOf(openStat), identityOf(finalStat))
|
|
222
|
+
&& finalStat.dev === postPathStat.dev
|
|
223
|
+
&& finalStat.ino === postPathStat.ino
|
|
224
|
+
&& BigInt(bytesRead) === finalStat.size;
|
|
225
|
+
const reference = {
|
|
226
|
+
raw,
|
|
227
|
+
contentHash: computeIntentContentHash(raw),
|
|
228
|
+
path: filePath,
|
|
229
|
+
};
|
|
230
|
+
if (!stable) {
|
|
231
|
+
if (attempt < INTENT_STABILITY_RETRIES) {
|
|
232
|
+
continue; // bounded re-read — try again from a fresh open
|
|
233
|
+
}
|
|
234
|
+
// Budget exhausted: never cache torn content, and do not present
|
|
235
|
+
// possibly-mixed bytes as a successful read (rc-3).
|
|
236
|
+
_intentDocCache.delete(cacheKey);
|
|
237
|
+
logger?.warn?.(`[host-runtime:intent] read unstable after ${attempt + 1} attempts: workspace=${workspaceDir}, lang=${lang}`);
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
found: true,
|
|
241
|
+
flagEnabled: true,
|
|
242
|
+
reason: 'read_error',
|
|
243
|
+
nextAction: `${getIntentFilename(lang)} kept changing while being read (concurrent writer). Retry; if this recurs, stop the writer process first.`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
_intentDocCache.set(cacheKey, {
|
|
247
|
+
reference,
|
|
248
|
+
identity: identityOf(finalStat),
|
|
249
|
+
loadedAt: now,
|
|
250
|
+
});
|
|
251
|
+
return { ok: true, found: true, flagEnabled: true, doc: reference };
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
fs.closeSync(fd);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
// PR #2684 P1: a stability retry that hits a transient fs error
|
|
259
|
+
// (e.g. the path vanished mid-retry because of an atomic replace)
|
|
260
|
+
// is retried within the same budget; ENOENT on the FIRST open is
|
|
261
|
+
// handled above, so reaching here mid-loop means the file was
|
|
262
|
+
// removed while we were re-reading — treat as unstable and retry;
|
|
263
|
+
// if the budget is exhausted, degrade below exactly like any other
|
|
264
|
+
// real read failure (never throw — ERR-002).
|
|
265
|
+
if (attempt < INTENT_STABILITY_RETRIES && isEnoent(err)) {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
_intentDocCache.delete(cacheKey);
|
|
269
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
270
|
+
logger?.warn?.(`[host-runtime:intent] read failed: workspace=${workspaceDir}, lang=${lang}, error=${message}`);
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
found: false,
|
|
274
|
+
flagEnabled: true,
|
|
275
|
+
reason: 'read_error',
|
|
276
|
+
nextAction: `Check filesystem permissions for .principles/${getIntentFilename(lang)}.`,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
// Unreachable: every loop iteration either returns or continues, and the
|
|
281
|
+
// stability-exhausted branch returns inside the loop. Kept so the
|
|
282
|
+
// compiler sees a terminating return for IntentDocReadResult.
|
|
283
|
+
return {
|
|
284
|
+
ok: false,
|
|
285
|
+
found: true,
|
|
286
|
+
flagEnabled: true,
|
|
287
|
+
reason: 'read_error',
|
|
288
|
+
nextAction: `${getIntentFilename(lang)} kept changing while being read (concurrent writer). Retry.`,
|
|
289
|
+
};
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|