@principles/host-runtime 4.3.0 → 4.4.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.
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import * as path from 'node:path';
|
|
21
21
|
import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
|
|
22
22
|
import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
|
|
23
|
+
import { createHostIntentDocReader } from './intent-doc-reader.js';
|
|
23
24
|
/** Quiet flag that owns the L3 half of the ladder. */
|
|
24
25
|
export const DIAGNOSTICIAN_AUTO_RUN_FLAG = 'openclaw_diagnostician_consumer';
|
|
25
26
|
/** Owner string used for the diagnostics this module starts. */
|
|
@@ -69,6 +70,11 @@ export async function runPendingDiagnosticianOnce(options) {
|
|
|
69
70
|
owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
|
|
70
71
|
effectiveConfig: config.effective,
|
|
71
72
|
getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
|
|
73
|
+
// PRI-1233 / SPEC §9.2: the L3 consumer executes admitted tasks, so it
|
|
74
|
+
// is where Stage A actually runs for governance-admitted pains — the
|
|
75
|
+
// neutral host reader must ride along or admission would never capture
|
|
76
|
+
// a snapshot on this path. Flag-off keeps zero filesystem access.
|
|
77
|
+
intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
|
|
72
78
|
});
|
|
73
79
|
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
74
80
|
if (executed.status === 'failed') {
|
|
@@ -35,10 +35,11 @@ import fs from 'node:fs';
|
|
|
35
35
|
import path from 'node:path';
|
|
36
36
|
import { randomUUID } from 'node:crypto';
|
|
37
37
|
import Database from 'better-sqlite3';
|
|
38
|
-
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId,
|
|
38
|
+
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
|
|
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,
|
|
@@ -1880,10 +1887,6 @@ export async function ensureGovernanceDiagnosticianTask(input) {
|
|
|
1880
1887
|
: {}),
|
|
1881
1888
|
recordObservability: true,
|
|
1882
1889
|
});
|
|
1883
|
-
// recordPain (async) leaves a cached bridge holding open SQLite
|
|
1884
|
-
// handles; this seam runs per reconciliation cycle under the Slice C
|
|
1885
|
-
// worker, so release it immediately (hook processes exit anyway).
|
|
1886
|
-
await disposePainSignalBridgesForWorkspace(workspaceDir).catch(() => undefined);
|
|
1887
1890
|
if (result.status === 'failed') {
|
|
1888
1891
|
// Concurrent-ensure race (hook redelivery × worker reconcile): both
|
|
1889
1892
|
// callers passed the getTask probe before either committed, and the
|
package/dist/index.d.ts
CHANGED
|
@@ -146,3 +146,4 @@ export { createCodexArtificerTrustedFactsPort } from './codex-artificer-trusted-
|
|
|
146
146
|
export { revalidateAdaptivePrinciple, createAdaptivePrincipleRevalidator, type AdaptivePrincipleReader } from './adaptive-principle-revalidation.js';
|
|
147
147
|
export * from './adaptive-journal-reconciliation.js';
|
|
148
148
|
export * from './adaptive-behavior-linkage.js';
|
|
149
|
+
export * from './intent-doc-reader.js';
|
package/dist/index.js
CHANGED
|
@@ -425,3 +425,7 @@ export { revalidateAdaptivePrinciple, createAdaptivePrincipleRevalidator } from
|
|
|
425
425
|
export * from './adaptive-journal-reconciliation.js';
|
|
426
426
|
// PRI-1114: read-only behavior evidence linkage (no writes, no model runs).
|
|
427
427
|
export * from './adaptive-behavior-linkage.js';
|
|
428
|
+
// PRI-1229 / SPEC-PD-INTENT-UNIFICATION-001 §9.3: neutral host IntentDocReader
|
|
429
|
+
// shared by PD CLI (pain record / diagnose / pain retry) and governance
|
|
430
|
+
// admission. Business semantics stay in Core; this is the I/O adapter only.
|
|
431
|
+
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -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.10.1",
|
|
39
|
+
"@principles/install-layout": "^0.8.3",
|
|
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": "57948395d8f4c8763027b95dd3e9463cba846bce"
|
|
57
57
|
}
|