@quolu/lattice 0.52.2 → 0.52.4
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/package.json +1 -1
- package/src/artifact-contracts-v2.mjs +325 -325
- package/src/artifact-contracts.mjs +895 -895
- package/src/boundary-compiler.mjs +712 -712
- package/src/boundary-observation-compiler-v2.mjs +344 -344
- package/src/bounded-seam.mjs +230 -230
- package/src/bridge-address.mjs +107 -107
- package/src/bridge-cli.mjs +297 -297
- package/src/bridge-config.mjs +346 -346
- package/src/bridge-daemon.mjs +378 -378
- package/src/bridge-hub-protocol.mjs +198 -0
- package/src/bridge-launch-agent.mjs +323 -323
- package/src/bridge-registrar.mjs +102 -102
- package/src/bridge-server.mjs +376 -376
- package/src/cli-help.mjs +308 -308
- package/src/cli-stdio.mjs +40 -40
- package/src/control-compiler.mjs +532 -532
- package/src/dag-chain.mjs +261 -261
- package/src/factory-diagnostics.mjs +188 -188
- package/src/git-process.mjs +72 -0
- package/src/hash-chain.mjs +76 -76
- package/src/hooks-cli.mjs +1057 -1057
- package/src/isolation-runner.mjs +409 -409
- package/src/node-version-guard.mjs +44 -44
- package/src/project-cli.mjs +699 -697
- package/src/project-identity.mjs +130 -130
- package/src/rc1-black-box-oracle.mjs +906 -906
- package/src/rc1-comparison.mjs +154 -154
- package/src/rc1-evidence-bundle.mjs +456 -456
- package/src/rc1-v4-campaign.mjs +708 -708
- package/src/rc1-v4-transform.mjs +467 -467
- package/src/rc1-v5-artifact-set.mjs +855 -855
- package/src/rc1-v5-behavior-evidence.mjs +594 -594
- package/src/rc1-v5-campaign.mjs +797 -797
- package/src/rc1-v5-transform.mjs +421 -421
- package/src/rc1-v6-artifact-set.mjs +807 -807
- package/src/rc1-v6-behavior-evidence.mjs +273 -273
- package/src/rc1-v6-campaign.mjs +623 -623
- package/src/rc1-v6-causal-binding.mjs +473 -473
- package/src/rc1-v6-measurement.mjs +313 -313
- package/src/rc2-artifact-set.mjs +1584 -1584
- package/src/rc2-campaign.mjs +1506 -1506
- package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
- package/src/rc2-delivery-policy-oracle.mjs +134 -134
- package/src/rc2-delivery-policy-transform.mjs +1127 -1127
- package/src/rc2-rc1-transfer-front-end.mjs +511 -511
- package/src/rc3-actual-dogfood.mjs +652 -652
- package/src/rc3-dogfood-scaffold.mjs +315 -315
- package/src/rc3-scripted-campaign.mjs +1383 -1383
- package/src/rc4-stage1-dogfood.mjs +673 -673
- package/src/runtime-adapter-registry.mjs +524 -524
- package/src/runtime-cli.mjs +4588 -4588
- package/src/runtime-contracts.mjs +824 -824
- package/src/runtime-control-store.mjs +604 -604
- package/src/runtime-controller-protocol.mjs +587 -587
- package/src/runtime-decision-verifier.mjs +701 -701
- package/src/runtime-diff-observer.mjs +361 -361
- package/src/runtime-direct-os-observer.mjs +301 -301
- package/src/runtime-driver-state.mjs +166 -166
- package/src/runtime-engine.mjs +779 -779
- package/src/runtime-errors.mjs +356 -356
- package/src/runtime-event-store.mjs +189 -189
- package/src/runtime-front-end.mjs +925 -925
- package/src/runtime-gate-store.mjs +481 -481
- package/src/runtime-hold-recompile.mjs +916 -916
- package/src/runtime-io-sentinel.mjs +391 -391
- package/src/runtime-lifecycle-lock.mjs +294 -294
- package/src/runtime-managed-supervisor.mjs +1490 -1490
- package/src/runtime-multi-epoch-store.mjs +838 -838
- package/src/runtime-projection.mjs +269 -269
- package/src/runtime-pull-intake.mjs +1192 -1192
- package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
- package/src/runtime-scripted-executor.mjs +163 -163
- package/src/runtime-scripted-worktree.mjs +104 -104
- package/src/runtime-seam-resolve.mjs +428 -428
- package/src/runtime-seam-treatment.mjs +173 -173
- package/src/runtime-socket-owner.mjs +125 -125
- package/src/runtime-work-order-contracts.mjs +91 -91
- package/src/runtime-work-order-controller.mjs +1171 -1171
- package/src/runtime-worktree-executor.mjs +199 -199
- package/src/schedulability-compiler-v2.mjs +303 -303
- package/src/schedulability-verifier-v2.mjs +317 -317
- package/src/seam-apply.mjs +549 -549
- package/src/seam-commit-shared.mjs +22 -22
- package/src/seam-commit-transform.mjs +81 -81
- package/src/seam-commit.mjs +18 -18
- package/src/seam-cost.mjs +322 -322
- package/src/seam-derivation.mjs +188 -188
- package/src/seam-gate.mjs +146 -146
- package/src/seam-proposal-contracts.mjs +446 -446
- package/src/seam-proposal-queries.mjs +521 -521
- package/src/seam-proposal.mjs +2011 -2011
- package/src/seam-ref.mjs +33 -33
- package/src/seam-rewrite.mjs +286 -286
- package/src/seam-transform.mjs +554 -554
- package/src/seam-verification.mjs +260 -260
- package/src/sensor-adapter.mjs +432 -432
- package/src/sensor-cli.mjs +139 -139
- package/src/sensor-diff.mjs +661 -661
- package/src/sensor-node-runtime.mjs +53 -53
- package/src/sensor-runtime.mjs +52 -52
- package/src/timestamp-contract.mjs +8 -8
- package/src/todo-audit-pending.mjs +91 -91
- package/src/todo-chain.mjs +178 -178
- package/src/todo-cli.mjs +3143 -3141
- package/src/todo-contracts.mjs +728 -728
- package/src/todo-dashboard-registry.mjs +573 -573
- package/src/todo-dispatch-shape.mjs +190 -190
- package/src/todo-gantt-html-independence.mjs +239 -239
- package/src/todo-gantt-html-shared.mjs +226 -226
- package/src/todo-gantt-html-style.mjs +131 -131
- package/src/todo-gantt-html.mjs +248 -248
- package/src/todo-gantt-layout.mjs +974 -974
- package/src/todo-gantt-live.mjs +361 -361
- package/src/todo-gantt-nested.mjs +263 -263
- package/src/todo-gantt-presentation.mjs +217 -217
- package/src/todo-gantt-scope.mjs +123 -123
- package/src/todo-gantt-svg.mjs +353 -353
- package/src/todo-independence-contracts.mjs +595 -595
- package/src/todo-independence-guidance.mjs +322 -322
- package/src/todo-independence.mjs +640 -640
- package/src/todo-markdown-renderer.mjs +260 -260
- package/src/todo-migration.mjs +448 -448
- package/src/todo-narrative-anchor.mjs +130 -130
- package/src/todo-note-store.mjs +629 -629
- package/src/todo-parallel-candidates.mjs +114 -114
- package/src/todo-revision.mjs +995 -995
- package/src/todo-split.mjs +472 -472
- package/src/todo-status.mjs +690 -690
- package/src/todo-store-git-transaction.mjs +418 -418
- package/src/todo-store.mjs +4360 -4322
- package/src/treatment-compiler.mjs +728 -728
- package/src/treatment-runner.mjs +656 -656
- package/src/witness-scaffold.mjs +180 -180
package/src/runtime-errors.mjs
CHANGED
|
@@ -1,356 +1,356 @@
|
|
|
1
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
3
|
-
existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync,
|
|
4
|
-
} from 'node:fs';
|
|
5
|
-
import { homedir, platform as hostPlatform, arch as hostArch } from 'node:os';
|
|
6
|
-
import { dirname, join } from 'node:path';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* opt-in runtime error store(親plan L6要件。Caveat `caveat.runtime_errors.v1` と同型の工場契約)。
|
|
10
|
-
*
|
|
11
|
-
* - collection/reporting分離: 収集可否は工場共有config
|
|
12
|
-
* `${XDG_CONFIG_HOME:-~/.config}/dotagents/factory-reporter.json` の `collection.enabled` だけが決める。
|
|
13
|
-
* reporting設定はconfig validationの一部だが、本storeは外部送信を一切行わない(送信はdotagents adapter所有)。
|
|
14
|
-
* - 既定OFF: config欠落・malformed・disabledでは state も network も触らない。
|
|
15
|
-
* - privacy by design: 保存するのは固定catalogの `error_code` / `message_template` のみ。
|
|
16
|
-
* 生message・path・引数を保存しない。
|
|
17
|
-
* - retention: fingerprint集約(同一原因はcount/last_seen更新)+ack済みresolvedの30日compact。
|
|
18
|
-
* - POSIX専用: Lattice runtimeはWindows nativeでunsupported(親plan L6)。owner-onlyを証明できない
|
|
19
|
-
* 環境では `store_unsafe` でfail closedする。
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
const RUNTIME_ERRORS_SCHEMA = 'lattice.runtime_errors.v1';
|
|
23
|
-
const DIAGNOSTICS_SCHEMA = 'lattice.runtime_error_diagnostics.v1';
|
|
24
|
-
const PRODUCT = 'lattice';
|
|
25
|
-
const STATE_VERSION = '1.0';
|
|
26
|
-
const MAX_RECORDS = 256;
|
|
27
|
-
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
28
|
-
const LOCK_STALE_MS = 60_000;
|
|
29
|
-
const LOCK_RETRY_MS = 100;
|
|
30
|
-
const LOCK_TIMEOUT_MS = 5_000;
|
|
31
|
-
|
|
32
|
-
const definitions = Object.freeze({
|
|
33
|
-
'LATTICE.SENSOR_EVIDENCE_FAILED': { component: 'sensor_adapter', severity: 'high', template: 'LatticeSensor evidence collection failed' },
|
|
34
|
-
'LATTICE.RUN_STORE_IO_FAILED': { component: 'run_store', severity: 'high', template: 'Lattice run store IO failed' },
|
|
35
|
-
'LATTICE.EVENT_CHAIN_INTEGRITY_FAILED': { component: 'event_store', severity: 'high', template: 'Lattice run event chain integrity check failed' },
|
|
36
|
-
'LATTICE.CLI_INTERNAL_FAILED': { component: 'cli', severity: 'high', template: 'Lattice CLI crashed outside the typed error contract' },
|
|
37
|
-
'LATTICE.MCP_SERVER_FAILED': { component: 'mcp', severity: 'high', template: 'Lattice MCP server failed' },
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
const plain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
41
|
-
const exact = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
42
|
-
const validTime = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
43
|
-
const validVersion = (value) => typeof value === 'string' && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(value);
|
|
44
|
-
const validOs = (value) => typeof value === 'string' && ['darwin', 'linux'].includes(value);
|
|
45
|
-
const validArch = (value) => typeof value === 'string' && ['x64', 'arm64', 'arm'].includes(value);
|
|
46
|
-
|
|
47
|
-
export function defaultFactoryReporterConfigPath(env = process.env) {
|
|
48
|
-
const home = env.HOME || homedir();
|
|
49
|
-
return join(env.XDG_CONFIG_HOME || join(home, '.config'), 'dotagents', 'factory-reporter.json');
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function runtimeErrorsStatePath(env = process.env) {
|
|
53
|
-
const home = env.HOME || homedir();
|
|
54
|
-
return join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'lattice', 'runtime-errors.json');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function canonicalReporting(value) {
|
|
58
|
-
if (!plain(value) || !Object.keys(value).every((key) => ['enabled', 'endpoint', 'credential_file'].includes(key)) || typeof value.enabled !== 'boolean') return false;
|
|
59
|
-
if (value.endpoint !== undefined) {
|
|
60
|
-
if (typeof value.endpoint !== 'string' || value.endpoint.length > 2048) return false;
|
|
61
|
-
try { if (!['http:', 'https:'].includes(new URL(value.endpoint).protocol)) return false; } catch { return false; }
|
|
62
|
-
}
|
|
63
|
-
if (value.credential_file !== undefined && (typeof value.credential_file !== 'string' || value.credential_file.length < 1 || value.credential_file.length > 4096)) return false;
|
|
64
|
-
return !value.enabled || (value.endpoint !== undefined && value.credential_file !== undefined);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function collectionEnabled(options = {}) {
|
|
68
|
-
const env = options.env ?? process.env;
|
|
69
|
-
try {
|
|
70
|
-
const path = options.configPath ?? defaultFactoryReporterConfigPath(env);
|
|
71
|
-
const stats = lstatSync(path);
|
|
72
|
-
if (!stats.isFile() || stats.isSymbolicLink()) return false;
|
|
73
|
-
const config = JSON.parse(readFileSync(path, 'utf8'));
|
|
74
|
-
return plain(config) && exact(config, ['schema_version', 'host', 'collection', 'reporting'])
|
|
75
|
-
&& config.schema_version === '1.0' && plain(config.host) && exact(config.host, ['id', 'profile'])
|
|
76
|
-
&& typeof config.host.id === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(config.host.id)
|
|
77
|
-
&& ['server', 'mac', 'wsl', 'windows-native'].includes(config.host.profile)
|
|
78
|
-
&& plain(config.collection) && exact(config.collection, ['enabled']) && config.collection.enabled === true
|
|
79
|
-
&& canonicalReporting(config.reporting);
|
|
80
|
-
} catch {
|
|
81
|
-
return false;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function runtimeCollectionEnabled(env = process.env, configPath) {
|
|
86
|
-
return collectionEnabled({ env, configPath });
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function fingerprintOf(code) {
|
|
90
|
-
const definition = definitions[code];
|
|
91
|
-
return createHash('sha256').update(`${PRODUCT}\0${definition.component}\0${code}\0${definition.template}`).digest('hex');
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function assertPosix(info, mode) {
|
|
95
|
-
if ((info.mode & 0o777) !== mode || (typeof process.getuid === 'function' && info.uid !== process.getuid())) throw Error('store_unsafe');
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function ensureSafeDir(dir) {
|
|
99
|
-
if (hostPlatform() === 'win32') throw Error('store_unsafe');
|
|
100
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
101
|
-
const stats = lstatSync(dir);
|
|
102
|
-
if (!stats.isDirectory() || stats.isSymbolicLink()) throw Error('store_unsafe');
|
|
103
|
-
assertPosix(stats, 0o700);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function ensureSafeFile(path) {
|
|
107
|
-
const stats = lstatSync(path);
|
|
108
|
-
if (!stats.isFile() || stats.isSymbolicLink()) throw Error('store_unsafe');
|
|
109
|
-
assertPosix(statSync(path), 0o600);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const empty = () => ({ schema: RUNTIME_ERRORS_SCHEMA, next_sequence: 1, acknowledged_through: 0, records: [] });
|
|
113
|
-
|
|
114
|
-
function validate(store) {
|
|
115
|
-
if (!plain(store) || !exact(store, ['schema', 'next_sequence', 'acknowledged_through', 'records'])) throw Error('state_invalid');
|
|
116
|
-
if (store.schema !== RUNTIME_ERRORS_SCHEMA || !Number.isSafeInteger(store.next_sequence) || store.next_sequence < 1
|
|
117
|
-
|| !Number.isSafeInteger(store.acknowledged_through) || store.acknowledged_through < 0 || store.acknowledged_through >= store.next_sequence
|
|
118
|
-
|| !Array.isArray(store.records) || store.records.length > MAX_RECORDS) throw Error('state_invalid');
|
|
119
|
-
const seen = new Set();
|
|
120
|
-
let previous = 0;
|
|
121
|
-
for (const record of store.records) {
|
|
122
|
-
if (!plain(record) || !exact(record, ['product', 'product_version', 'component', 'error_code', 'message_template', 'severity', 'fingerprint', 'count', 'first_seen', 'last_seen', 'state_schema_version', 'os', 'arch', 'status', 'resolved_at', 'reason_code', 'sequence'])) throw Error('state_invalid');
|
|
123
|
-
const definition = definitions[record.error_code];
|
|
124
|
-
if (!definition || record.product !== PRODUCT || !validVersion(record.product_version)
|
|
125
|
-
|| record.component !== definition.component || record.message_template !== definition.template
|
|
126
|
-
|| record.severity !== definition.severity || record.fingerprint !== fingerprintOf(record.error_code)
|
|
127
|
-
|| seen.has(record.fingerprint) || !Number.isSafeInteger(record.count) || record.count < 1
|
|
128
|
-
|| !validTime(record.first_seen) || !validTime(record.last_seen)
|
|
129
|
-
|| Date.parse(record.first_seen) > Date.parse(record.last_seen)
|
|
130
|
-
|| record.state_schema_version !== STATE_VERSION || !validOs(record.os) || !validArch(record.arch)
|
|
131
|
-
|| !Number.isSafeInteger(record.sequence) || record.sequence <= previous || record.sequence >= store.next_sequence
|
|
132
|
-
|| !['open', 'resolved'].includes(record.status)
|
|
133
|
-
|| (record.status === 'open' && (record.resolved_at !== null || record.reason_code !== null))
|
|
134
|
-
|| (record.status === 'resolved' && (!validTime(record.resolved_at) || Date.parse(record.resolved_at) < Date.parse(record.last_seen) || record.reason_code !== 'operator_resolved'))) throw Error('state_invalid');
|
|
135
|
-
seen.add(record.fingerprint);
|
|
136
|
-
previous = record.sequence;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function readStore(path) {
|
|
141
|
-
if (!existsSync(path)) return empty();
|
|
142
|
-
ensureSafeFile(path);
|
|
143
|
-
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
144
|
-
validate(value);
|
|
145
|
-
return value;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function writeStore(path, store) {
|
|
149
|
-
validate(store);
|
|
150
|
-
ensureSafeDir(dirname(path));
|
|
151
|
-
const temporary = join(dirname(path), `.runtime-errors-${process.pid}-${randomBytes(6).toString('hex')}`);
|
|
152
|
-
try {
|
|
153
|
-
writeFileSync(temporary, `${JSON.stringify(store)}\n`, { mode: 0o600, flag: 'wx' });
|
|
154
|
-
assertPosix(statSync(temporary), 0o600);
|
|
155
|
-
renameSync(temporary, path);
|
|
156
|
-
ensureSafeFile(path);
|
|
157
|
-
} finally {
|
|
158
|
-
rmSync(temporary, { force: true });
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function sleepSync(ms) {
|
|
163
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function lock(path, fn) {
|
|
167
|
-
ensureSafeDir(dirname(path));
|
|
168
|
-
const lockPath = `${path}.lock`;
|
|
169
|
-
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
170
|
-
for (;;) {
|
|
171
|
-
try {
|
|
172
|
-
writeFileSync(lockPath, `${process.pid}\n`, { mode: 0o600, flag: 'wx' });
|
|
173
|
-
break;
|
|
174
|
-
} catch (error) {
|
|
175
|
-
if (!plain(error) || error.code !== 'EEXIST') throw error;
|
|
176
|
-
let age = 0;
|
|
177
|
-
try { age = Date.now() - lstatSync(lockPath).mtimeMs; } catch { continue; }
|
|
178
|
-
// crash残置lockの恒久ロックを避ける唯一の明示救済。閾値未満は正当な並行writerとして待つ。
|
|
179
|
-
if (age > LOCK_STALE_MS) { try { unlinkSync(lockPath); } catch {} continue; }
|
|
180
|
-
if (Date.now() >= deadline) throw Error('store_locked');
|
|
181
|
-
sleepSync(LOCK_RETRY_MS);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
try {
|
|
185
|
-
return fn();
|
|
186
|
-
} finally {
|
|
187
|
-
rmSync(lockPath, { force: true });
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function now(options) {
|
|
192
|
-
const value = options.now ? new Date(options.now) : new Date();
|
|
193
|
-
if (Number.isNaN(value.valueOf())) throw Error('invalid_time');
|
|
194
|
-
return value.toISOString();
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function optionsFor(options) {
|
|
198
|
-
const env = options.env ?? process.env;
|
|
199
|
-
return { env, path: options.storePath ?? runtimeErrorsStatePath(env) };
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function requireCursor(value) { if (!Number.isSafeInteger(value) || value < 0) throw Error('invalid_cursor'); }
|
|
203
|
-
function requireLimit(value) { if (!Number.isSafeInteger(value) || value < 1 || value > MAX_RECORDS) throw Error('invalid_limit'); }
|
|
204
|
-
|
|
205
|
-
function snapshot(options = {}) {
|
|
206
|
-
const afterCursor = options.afterCursor ?? 0;
|
|
207
|
-
const limit = options.limit ?? MAX_RECORDS;
|
|
208
|
-
requireCursor(afterCursor);
|
|
209
|
-
requireLimit(limit);
|
|
210
|
-
const enabled = collectionEnabled(options);
|
|
211
|
-
const { path } = optionsFor(options);
|
|
212
|
-
const store = enabled ? readStore(path) : empty();
|
|
213
|
-
if (afterCursor > store.next_sequence - 1) throw Error('invalid_cursor');
|
|
214
|
-
const all = store.records.filter((record) => record.sequence > afterCursor);
|
|
215
|
-
const rows = all.slice(0, limit);
|
|
216
|
-
return {
|
|
217
|
-
schema: RUNTIME_ERRORS_SCHEMA,
|
|
218
|
-
product: PRODUCT,
|
|
219
|
-
version: options.version ?? 'unknown',
|
|
220
|
-
state_schema_version: STATE_VERSION,
|
|
221
|
-
cursor: { high_watermark: store.next_sequence - 1, acknowledged_through: store.acknowledged_through, next: rows.at(-1)?.sequence ?? afterCursor },
|
|
222
|
-
runtime_errors: rows.filter((record) => record.status === 'open').map(({ error_code, component, status, severity, fingerprint, message_template, count, first_seen, last_seen, state_schema_version }) => ({ error_code, component, status, severity, fingerprint, message_template, occurrence_count: count, first_seen, last_seen, state_schema_version })),
|
|
223
|
-
resolutions: rows.filter((record) => record.status === 'resolved').map(({ fingerprint, resolved_at, reason_code }) => ({ fingerprint, resolved_at, reason_code })),
|
|
224
|
-
diagnostics: {
|
|
225
|
-
collection: enabled ? 'enabled' : 'disabled',
|
|
226
|
-
status: enabled ? 'ready' : 'not_applicable',
|
|
227
|
-
total_count: store.records.length,
|
|
228
|
-
pending_count: store.records.filter((record) => record.sequence > store.acknowledged_through).length,
|
|
229
|
-
truncated: all.length > rows.length,
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
export function runtimeErrorsSnapshot(afterCursor = 0, limit = MAX_RECORDS, options = {}) {
|
|
235
|
-
return snapshot({ ...options, afterCursor, limit });
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
export function runtimeErrorsDiagnostics(options = {}) {
|
|
239
|
-
if (!collectionEnabled(options)) {
|
|
240
|
-
return { schema: DIAGNOSTICS_SCHEMA, collection: 'disabled', status: 'not_applicable', total_count: 0, open_count: 0, pending_count: 0, high_watermark: 0, acknowledged_through: 0 };
|
|
241
|
-
}
|
|
242
|
-
try {
|
|
243
|
-
const { path } = optionsFor(options);
|
|
244
|
-
const store = readStore(path);
|
|
245
|
-
return {
|
|
246
|
-
schema: DIAGNOSTICS_SCHEMA,
|
|
247
|
-
collection: 'enabled',
|
|
248
|
-
status: 'ready',
|
|
249
|
-
total_count: store.records.length,
|
|
250
|
-
open_count: store.records.filter((record) => record.status === 'open').length,
|
|
251
|
-
pending_count: store.records.filter((record) => record.sequence > store.acknowledged_through).length,
|
|
252
|
-
high_watermark: store.next_sequence - 1,
|
|
253
|
-
acknowledged_through: store.acknowledged_through,
|
|
254
|
-
};
|
|
255
|
-
} catch {
|
|
256
|
-
return { schema: DIAGNOSTICS_SCHEMA, collection: 'enabled', status: 'unavailable', total_count: 0, open_count: 0, pending_count: 0, high_watermark: 0, acknowledged_through: 0 };
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
export function recordRuntimeError(code, options = {}) {
|
|
261
|
-
if (!collectionEnabled(options)) return { status: 'disabled' };
|
|
262
|
-
const definition = definitions[code];
|
|
263
|
-
if (!definition) throw Error('unknown_runtime_code');
|
|
264
|
-
const { path } = optionsFor(options);
|
|
265
|
-
return lock(path, () => {
|
|
266
|
-
const store = readStore(path);
|
|
267
|
-
const key = fingerprintOf(code);
|
|
268
|
-
const sequence = store.next_sequence++;
|
|
269
|
-
const time = now(options);
|
|
270
|
-
const version = options.version ?? '0.0.0';
|
|
271
|
-
const os = options.os ?? hostPlatform();
|
|
272
|
-
const arch = options.arch ?? hostArch();
|
|
273
|
-
if (!validVersion(version) || !validOs(os) || !validArch(arch)) throw Error('invalid_runtime_metadata');
|
|
274
|
-
const existing = store.records.find((record) => record.fingerprint === key);
|
|
275
|
-
if (existing) {
|
|
276
|
-
existing.product_version = version;
|
|
277
|
-
existing.os = os;
|
|
278
|
-
existing.arch = arch;
|
|
279
|
-
existing.count += 1;
|
|
280
|
-
existing.last_seen = time;
|
|
281
|
-
existing.sequence = sequence;
|
|
282
|
-
existing.status = 'open';
|
|
283
|
-
existing.resolved_at = null;
|
|
284
|
-
existing.reason_code = null;
|
|
285
|
-
} else {
|
|
286
|
-
if (store.records.length >= MAX_RECORDS) throw Error('store_overflow');
|
|
287
|
-
store.records.push({
|
|
288
|
-
product: PRODUCT, product_version: version, component: definition.component, error_code: code,
|
|
289
|
-
message_template: definition.template, severity: definition.severity, fingerprint: key,
|
|
290
|
-
count: 1, first_seen: time, last_seen: time, state_schema_version: STATE_VERSION,
|
|
291
|
-
os, arch, status: 'open', resolved_at: null, reason_code: null, sequence,
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
store.records.sort((a, b) => a.sequence - b.sequence);
|
|
295
|
-
writeStore(path, store);
|
|
296
|
-
return { status: 'recorded', fingerprint: key, sequence };
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
export function observeRuntimeError(code, options = {}) {
|
|
301
|
-
try {
|
|
302
|
-
recordRuntimeError(code, options);
|
|
303
|
-
} catch {
|
|
304
|
-
try { process.stderr.write('[lattice:runtime-errors] store_unavailable\n'); } catch { /* best-effort */ }
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
export function acknowledgeRuntimeErrors(cursor, options = {}) {
|
|
309
|
-
requireCursor(cursor);
|
|
310
|
-
if (!collectionEnabled(options)) return snapshot({ ...options, afterCursor: cursor });
|
|
311
|
-
const { path } = optionsFor(options);
|
|
312
|
-
lock(path, () => {
|
|
313
|
-
const store = readStore(path);
|
|
314
|
-
if (cursor >= store.next_sequence) throw Error('invalid_cursor');
|
|
315
|
-
store.acknowledged_through = Math.max(store.acknowledged_through, cursor);
|
|
316
|
-
writeStore(path, store);
|
|
317
|
-
});
|
|
318
|
-
return snapshot(options);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export function setRuntimeErrorStatus(fingerprintValue, status, options = {}) {
|
|
322
|
-
if (!/^[0-9a-f]{64}$/.test(fingerprintValue)) throw Error('invalid_fingerprint');
|
|
323
|
-
if (!['open', 'resolved'].includes(status)) throw Error('invalid_status');
|
|
324
|
-
if (!collectionEnabled(options)) return snapshot(options);
|
|
325
|
-
const { path } = optionsFor(options);
|
|
326
|
-
lock(path, () => {
|
|
327
|
-
const store = readStore(path);
|
|
328
|
-
const record = store.records.find((entry) => entry.fingerprint === fingerprintValue);
|
|
329
|
-
if (!record) throw Error('fingerprint_not_found');
|
|
330
|
-
if (record.status === status) return;
|
|
331
|
-
record.status = status;
|
|
332
|
-
record.resolved_at = status === 'resolved' ? now(options) : null;
|
|
333
|
-
record.reason_code = status === 'resolved' ? 'operator_resolved' : null;
|
|
334
|
-
record.sequence = store.next_sequence++;
|
|
335
|
-
store.records.sort((a, b) => a.sequence - b.sequence);
|
|
336
|
-
writeStore(path, store);
|
|
337
|
-
});
|
|
338
|
-
return snapshot(options);
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
export function compactRuntimeErrors(options = {}) {
|
|
342
|
-
if (!collectionEnabled(options)) return snapshot(options);
|
|
343
|
-
const { path } = optionsFor(options);
|
|
344
|
-
lock(path, () => {
|
|
345
|
-
const store = readStore(path);
|
|
346
|
-
const cutoff = Date.parse(now(options)) - RETENTION_MS;
|
|
347
|
-
store.records = store.records.filter((record) => !(record.status === 'resolved'
|
|
348
|
-
&& record.sequence <= store.acknowledged_through
|
|
349
|
-
&& record.resolved_at !== null
|
|
350
|
-
&& Date.parse(record.resolved_at) <= cutoff));
|
|
351
|
-
writeStore(path, store);
|
|
352
|
-
});
|
|
353
|
-
return snapshot(options);
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
export const runtimeErrorsInternal = { validate, definitions, fingerprintOf };
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync,
|
|
4
|
+
} from 'node:fs';
|
|
5
|
+
import { homedir, platform as hostPlatform, arch as hostArch } from 'node:os';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* opt-in runtime error store(親plan L6要件。Caveat `caveat.runtime_errors.v1` と同型の工場契約)。
|
|
10
|
+
*
|
|
11
|
+
* - collection/reporting分離: 収集可否は工場共有config
|
|
12
|
+
* `${XDG_CONFIG_HOME:-~/.config}/dotagents/factory-reporter.json` の `collection.enabled` だけが決める。
|
|
13
|
+
* reporting設定はconfig validationの一部だが、本storeは外部送信を一切行わない(送信はdotagents adapter所有)。
|
|
14
|
+
* - 既定OFF: config欠落・malformed・disabledでは state も network も触らない。
|
|
15
|
+
* - privacy by design: 保存するのは固定catalogの `error_code` / `message_template` のみ。
|
|
16
|
+
* 生message・path・引数を保存しない。
|
|
17
|
+
* - retention: fingerprint集約(同一原因はcount/last_seen更新)+ack済みresolvedの30日compact。
|
|
18
|
+
* - POSIX専用: Lattice runtimeはWindows nativeでunsupported(親plan L6)。owner-onlyを証明できない
|
|
19
|
+
* 環境では `store_unsafe` でfail closedする。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const RUNTIME_ERRORS_SCHEMA = 'lattice.runtime_errors.v1';
|
|
23
|
+
const DIAGNOSTICS_SCHEMA = 'lattice.runtime_error_diagnostics.v1';
|
|
24
|
+
const PRODUCT = 'lattice';
|
|
25
|
+
const STATE_VERSION = '1.0';
|
|
26
|
+
const MAX_RECORDS = 256;
|
|
27
|
+
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
28
|
+
const LOCK_STALE_MS = 60_000;
|
|
29
|
+
const LOCK_RETRY_MS = 100;
|
|
30
|
+
const LOCK_TIMEOUT_MS = 5_000;
|
|
31
|
+
|
|
32
|
+
const definitions = Object.freeze({
|
|
33
|
+
'LATTICE.SENSOR_EVIDENCE_FAILED': { component: 'sensor_adapter', severity: 'high', template: 'LatticeSensor evidence collection failed' },
|
|
34
|
+
'LATTICE.RUN_STORE_IO_FAILED': { component: 'run_store', severity: 'high', template: 'Lattice run store IO failed' },
|
|
35
|
+
'LATTICE.EVENT_CHAIN_INTEGRITY_FAILED': { component: 'event_store', severity: 'high', template: 'Lattice run event chain integrity check failed' },
|
|
36
|
+
'LATTICE.CLI_INTERNAL_FAILED': { component: 'cli', severity: 'high', template: 'Lattice CLI crashed outside the typed error contract' },
|
|
37
|
+
'LATTICE.MCP_SERVER_FAILED': { component: 'mcp', severity: 'high', template: 'Lattice MCP server failed' },
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const plain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
41
|
+
const exact = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
42
|
+
const validTime = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
|
|
43
|
+
const validVersion = (value) => typeof value === 'string' && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(value);
|
|
44
|
+
const validOs = (value) => typeof value === 'string' && ['darwin', 'linux'].includes(value);
|
|
45
|
+
const validArch = (value) => typeof value === 'string' && ['x64', 'arm64', 'arm'].includes(value);
|
|
46
|
+
|
|
47
|
+
export function defaultFactoryReporterConfigPath(env = process.env) {
|
|
48
|
+
const home = env.HOME || homedir();
|
|
49
|
+
return join(env.XDG_CONFIG_HOME || join(home, '.config'), 'dotagents', 'factory-reporter.json');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function runtimeErrorsStatePath(env = process.env) {
|
|
53
|
+
const home = env.HOME || homedir();
|
|
54
|
+
return join(env.XDG_STATE_HOME || join(home, '.local', 'state'), 'lattice', 'runtime-errors.json');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function canonicalReporting(value) {
|
|
58
|
+
if (!plain(value) || !Object.keys(value).every((key) => ['enabled', 'endpoint', 'credential_file'].includes(key)) || typeof value.enabled !== 'boolean') return false;
|
|
59
|
+
if (value.endpoint !== undefined) {
|
|
60
|
+
if (typeof value.endpoint !== 'string' || value.endpoint.length > 2048) return false;
|
|
61
|
+
try { if (!['http:', 'https:'].includes(new URL(value.endpoint).protocol)) return false; } catch { return false; }
|
|
62
|
+
}
|
|
63
|
+
if (value.credential_file !== undefined && (typeof value.credential_file !== 'string' || value.credential_file.length < 1 || value.credential_file.length > 4096)) return false;
|
|
64
|
+
return !value.enabled || (value.endpoint !== undefined && value.credential_file !== undefined);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function collectionEnabled(options = {}) {
|
|
68
|
+
const env = options.env ?? process.env;
|
|
69
|
+
try {
|
|
70
|
+
const path = options.configPath ?? defaultFactoryReporterConfigPath(env);
|
|
71
|
+
const stats = lstatSync(path);
|
|
72
|
+
if (!stats.isFile() || stats.isSymbolicLink()) return false;
|
|
73
|
+
const config = JSON.parse(readFileSync(path, 'utf8'));
|
|
74
|
+
return plain(config) && exact(config, ['schema_version', 'host', 'collection', 'reporting'])
|
|
75
|
+
&& config.schema_version === '1.0' && plain(config.host) && exact(config.host, ['id', 'profile'])
|
|
76
|
+
&& typeof config.host.id === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(config.host.id)
|
|
77
|
+
&& ['server', 'mac', 'wsl', 'windows-native'].includes(config.host.profile)
|
|
78
|
+
&& plain(config.collection) && exact(config.collection, ['enabled']) && config.collection.enabled === true
|
|
79
|
+
&& canonicalReporting(config.reporting);
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function runtimeCollectionEnabled(env = process.env, configPath) {
|
|
86
|
+
return collectionEnabled({ env, configPath });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function fingerprintOf(code) {
|
|
90
|
+
const definition = definitions[code];
|
|
91
|
+
return createHash('sha256').update(`${PRODUCT}\0${definition.component}\0${code}\0${definition.template}`).digest('hex');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function assertPosix(info, mode) {
|
|
95
|
+
if ((info.mode & 0o777) !== mode || (typeof process.getuid === 'function' && info.uid !== process.getuid())) throw Error('store_unsafe');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function ensureSafeDir(dir) {
|
|
99
|
+
if (hostPlatform() === 'win32') throw Error('store_unsafe');
|
|
100
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
101
|
+
const stats = lstatSync(dir);
|
|
102
|
+
if (!stats.isDirectory() || stats.isSymbolicLink()) throw Error('store_unsafe');
|
|
103
|
+
assertPosix(stats, 0o700);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function ensureSafeFile(path) {
|
|
107
|
+
const stats = lstatSync(path);
|
|
108
|
+
if (!stats.isFile() || stats.isSymbolicLink()) throw Error('store_unsafe');
|
|
109
|
+
assertPosix(statSync(path), 0o600);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const empty = () => ({ schema: RUNTIME_ERRORS_SCHEMA, next_sequence: 1, acknowledged_through: 0, records: [] });
|
|
113
|
+
|
|
114
|
+
function validate(store) {
|
|
115
|
+
if (!plain(store) || !exact(store, ['schema', 'next_sequence', 'acknowledged_through', 'records'])) throw Error('state_invalid');
|
|
116
|
+
if (store.schema !== RUNTIME_ERRORS_SCHEMA || !Number.isSafeInteger(store.next_sequence) || store.next_sequence < 1
|
|
117
|
+
|| !Number.isSafeInteger(store.acknowledged_through) || store.acknowledged_through < 0 || store.acknowledged_through >= store.next_sequence
|
|
118
|
+
|| !Array.isArray(store.records) || store.records.length > MAX_RECORDS) throw Error('state_invalid');
|
|
119
|
+
const seen = new Set();
|
|
120
|
+
let previous = 0;
|
|
121
|
+
for (const record of store.records) {
|
|
122
|
+
if (!plain(record) || !exact(record, ['product', 'product_version', 'component', 'error_code', 'message_template', 'severity', 'fingerprint', 'count', 'first_seen', 'last_seen', 'state_schema_version', 'os', 'arch', 'status', 'resolved_at', 'reason_code', 'sequence'])) throw Error('state_invalid');
|
|
123
|
+
const definition = definitions[record.error_code];
|
|
124
|
+
if (!definition || record.product !== PRODUCT || !validVersion(record.product_version)
|
|
125
|
+
|| record.component !== definition.component || record.message_template !== definition.template
|
|
126
|
+
|| record.severity !== definition.severity || record.fingerprint !== fingerprintOf(record.error_code)
|
|
127
|
+
|| seen.has(record.fingerprint) || !Number.isSafeInteger(record.count) || record.count < 1
|
|
128
|
+
|| !validTime(record.first_seen) || !validTime(record.last_seen)
|
|
129
|
+
|| Date.parse(record.first_seen) > Date.parse(record.last_seen)
|
|
130
|
+
|| record.state_schema_version !== STATE_VERSION || !validOs(record.os) || !validArch(record.arch)
|
|
131
|
+
|| !Number.isSafeInteger(record.sequence) || record.sequence <= previous || record.sequence >= store.next_sequence
|
|
132
|
+
|| !['open', 'resolved'].includes(record.status)
|
|
133
|
+
|| (record.status === 'open' && (record.resolved_at !== null || record.reason_code !== null))
|
|
134
|
+
|| (record.status === 'resolved' && (!validTime(record.resolved_at) || Date.parse(record.resolved_at) < Date.parse(record.last_seen) || record.reason_code !== 'operator_resolved'))) throw Error('state_invalid');
|
|
135
|
+
seen.add(record.fingerprint);
|
|
136
|
+
previous = record.sequence;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function readStore(path) {
|
|
141
|
+
if (!existsSync(path)) return empty();
|
|
142
|
+
ensureSafeFile(path);
|
|
143
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
144
|
+
validate(value);
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function writeStore(path, store) {
|
|
149
|
+
validate(store);
|
|
150
|
+
ensureSafeDir(dirname(path));
|
|
151
|
+
const temporary = join(dirname(path), `.runtime-errors-${process.pid}-${randomBytes(6).toString('hex')}`);
|
|
152
|
+
try {
|
|
153
|
+
writeFileSync(temporary, `${JSON.stringify(store)}\n`, { mode: 0o600, flag: 'wx' });
|
|
154
|
+
assertPosix(statSync(temporary), 0o600);
|
|
155
|
+
renameSync(temporary, path);
|
|
156
|
+
ensureSafeFile(path);
|
|
157
|
+
} finally {
|
|
158
|
+
rmSync(temporary, { force: true });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function sleepSync(ms) {
|
|
163
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function lock(path, fn) {
|
|
167
|
+
ensureSafeDir(dirname(path));
|
|
168
|
+
const lockPath = `${path}.lock`;
|
|
169
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
170
|
+
for (;;) {
|
|
171
|
+
try {
|
|
172
|
+
writeFileSync(lockPath, `${process.pid}\n`, { mode: 0o600, flag: 'wx' });
|
|
173
|
+
break;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (!plain(error) || error.code !== 'EEXIST') throw error;
|
|
176
|
+
let age = 0;
|
|
177
|
+
try { age = Date.now() - lstatSync(lockPath).mtimeMs; } catch { continue; }
|
|
178
|
+
// crash残置lockの恒久ロックを避ける唯一の明示救済。閾値未満は正当な並行writerとして待つ。
|
|
179
|
+
if (age > LOCK_STALE_MS) { try { unlinkSync(lockPath); } catch {} continue; }
|
|
180
|
+
if (Date.now() >= deadline) throw Error('store_locked');
|
|
181
|
+
sleepSync(LOCK_RETRY_MS);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
return fn();
|
|
186
|
+
} finally {
|
|
187
|
+
rmSync(lockPath, { force: true });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function now(options) {
|
|
192
|
+
const value = options.now ? new Date(options.now) : new Date();
|
|
193
|
+
if (Number.isNaN(value.valueOf())) throw Error('invalid_time');
|
|
194
|
+
return value.toISOString();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function optionsFor(options) {
|
|
198
|
+
const env = options.env ?? process.env;
|
|
199
|
+
return { env, path: options.storePath ?? runtimeErrorsStatePath(env) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function requireCursor(value) { if (!Number.isSafeInteger(value) || value < 0) throw Error('invalid_cursor'); }
|
|
203
|
+
function requireLimit(value) { if (!Number.isSafeInteger(value) || value < 1 || value > MAX_RECORDS) throw Error('invalid_limit'); }
|
|
204
|
+
|
|
205
|
+
function snapshot(options = {}) {
|
|
206
|
+
const afterCursor = options.afterCursor ?? 0;
|
|
207
|
+
const limit = options.limit ?? MAX_RECORDS;
|
|
208
|
+
requireCursor(afterCursor);
|
|
209
|
+
requireLimit(limit);
|
|
210
|
+
const enabled = collectionEnabled(options);
|
|
211
|
+
const { path } = optionsFor(options);
|
|
212
|
+
const store = enabled ? readStore(path) : empty();
|
|
213
|
+
if (afterCursor > store.next_sequence - 1) throw Error('invalid_cursor');
|
|
214
|
+
const all = store.records.filter((record) => record.sequence > afterCursor);
|
|
215
|
+
const rows = all.slice(0, limit);
|
|
216
|
+
return {
|
|
217
|
+
schema: RUNTIME_ERRORS_SCHEMA,
|
|
218
|
+
product: PRODUCT,
|
|
219
|
+
version: options.version ?? 'unknown',
|
|
220
|
+
state_schema_version: STATE_VERSION,
|
|
221
|
+
cursor: { high_watermark: store.next_sequence - 1, acknowledged_through: store.acknowledged_through, next: rows.at(-1)?.sequence ?? afterCursor },
|
|
222
|
+
runtime_errors: rows.filter((record) => record.status === 'open').map(({ error_code, component, status, severity, fingerprint, message_template, count, first_seen, last_seen, state_schema_version }) => ({ error_code, component, status, severity, fingerprint, message_template, occurrence_count: count, first_seen, last_seen, state_schema_version })),
|
|
223
|
+
resolutions: rows.filter((record) => record.status === 'resolved').map(({ fingerprint, resolved_at, reason_code }) => ({ fingerprint, resolved_at, reason_code })),
|
|
224
|
+
diagnostics: {
|
|
225
|
+
collection: enabled ? 'enabled' : 'disabled',
|
|
226
|
+
status: enabled ? 'ready' : 'not_applicable',
|
|
227
|
+
total_count: store.records.length,
|
|
228
|
+
pending_count: store.records.filter((record) => record.sequence > store.acknowledged_through).length,
|
|
229
|
+
truncated: all.length > rows.length,
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function runtimeErrorsSnapshot(afterCursor = 0, limit = MAX_RECORDS, options = {}) {
|
|
235
|
+
return snapshot({ ...options, afterCursor, limit });
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function runtimeErrorsDiagnostics(options = {}) {
|
|
239
|
+
if (!collectionEnabled(options)) {
|
|
240
|
+
return { schema: DIAGNOSTICS_SCHEMA, collection: 'disabled', status: 'not_applicable', total_count: 0, open_count: 0, pending_count: 0, high_watermark: 0, acknowledged_through: 0 };
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
const { path } = optionsFor(options);
|
|
244
|
+
const store = readStore(path);
|
|
245
|
+
return {
|
|
246
|
+
schema: DIAGNOSTICS_SCHEMA,
|
|
247
|
+
collection: 'enabled',
|
|
248
|
+
status: 'ready',
|
|
249
|
+
total_count: store.records.length,
|
|
250
|
+
open_count: store.records.filter((record) => record.status === 'open').length,
|
|
251
|
+
pending_count: store.records.filter((record) => record.sequence > store.acknowledged_through).length,
|
|
252
|
+
high_watermark: store.next_sequence - 1,
|
|
253
|
+
acknowledged_through: store.acknowledged_through,
|
|
254
|
+
};
|
|
255
|
+
} catch {
|
|
256
|
+
return { schema: DIAGNOSTICS_SCHEMA, collection: 'enabled', status: 'unavailable', total_count: 0, open_count: 0, pending_count: 0, high_watermark: 0, acknowledged_through: 0 };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function recordRuntimeError(code, options = {}) {
|
|
261
|
+
if (!collectionEnabled(options)) return { status: 'disabled' };
|
|
262
|
+
const definition = definitions[code];
|
|
263
|
+
if (!definition) throw Error('unknown_runtime_code');
|
|
264
|
+
const { path } = optionsFor(options);
|
|
265
|
+
return lock(path, () => {
|
|
266
|
+
const store = readStore(path);
|
|
267
|
+
const key = fingerprintOf(code);
|
|
268
|
+
const sequence = store.next_sequence++;
|
|
269
|
+
const time = now(options);
|
|
270
|
+
const version = options.version ?? '0.0.0';
|
|
271
|
+
const os = options.os ?? hostPlatform();
|
|
272
|
+
const arch = options.arch ?? hostArch();
|
|
273
|
+
if (!validVersion(version) || !validOs(os) || !validArch(arch)) throw Error('invalid_runtime_metadata');
|
|
274
|
+
const existing = store.records.find((record) => record.fingerprint === key);
|
|
275
|
+
if (existing) {
|
|
276
|
+
existing.product_version = version;
|
|
277
|
+
existing.os = os;
|
|
278
|
+
existing.arch = arch;
|
|
279
|
+
existing.count += 1;
|
|
280
|
+
existing.last_seen = time;
|
|
281
|
+
existing.sequence = sequence;
|
|
282
|
+
existing.status = 'open';
|
|
283
|
+
existing.resolved_at = null;
|
|
284
|
+
existing.reason_code = null;
|
|
285
|
+
} else {
|
|
286
|
+
if (store.records.length >= MAX_RECORDS) throw Error('store_overflow');
|
|
287
|
+
store.records.push({
|
|
288
|
+
product: PRODUCT, product_version: version, component: definition.component, error_code: code,
|
|
289
|
+
message_template: definition.template, severity: definition.severity, fingerprint: key,
|
|
290
|
+
count: 1, first_seen: time, last_seen: time, state_schema_version: STATE_VERSION,
|
|
291
|
+
os, arch, status: 'open', resolved_at: null, reason_code: null, sequence,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
store.records.sort((a, b) => a.sequence - b.sequence);
|
|
295
|
+
writeStore(path, store);
|
|
296
|
+
return { status: 'recorded', fingerprint: key, sequence };
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function observeRuntimeError(code, options = {}) {
|
|
301
|
+
try {
|
|
302
|
+
recordRuntimeError(code, options);
|
|
303
|
+
} catch {
|
|
304
|
+
try { process.stderr.write('[lattice:runtime-errors] store_unavailable\n'); } catch { /* best-effort */ }
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function acknowledgeRuntimeErrors(cursor, options = {}) {
|
|
309
|
+
requireCursor(cursor);
|
|
310
|
+
if (!collectionEnabled(options)) return snapshot({ ...options, afterCursor: cursor });
|
|
311
|
+
const { path } = optionsFor(options);
|
|
312
|
+
lock(path, () => {
|
|
313
|
+
const store = readStore(path);
|
|
314
|
+
if (cursor >= store.next_sequence) throw Error('invalid_cursor');
|
|
315
|
+
store.acknowledged_through = Math.max(store.acknowledged_through, cursor);
|
|
316
|
+
writeStore(path, store);
|
|
317
|
+
});
|
|
318
|
+
return snapshot(options);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function setRuntimeErrorStatus(fingerprintValue, status, options = {}) {
|
|
322
|
+
if (!/^[0-9a-f]{64}$/.test(fingerprintValue)) throw Error('invalid_fingerprint');
|
|
323
|
+
if (!['open', 'resolved'].includes(status)) throw Error('invalid_status');
|
|
324
|
+
if (!collectionEnabled(options)) return snapshot(options);
|
|
325
|
+
const { path } = optionsFor(options);
|
|
326
|
+
lock(path, () => {
|
|
327
|
+
const store = readStore(path);
|
|
328
|
+
const record = store.records.find((entry) => entry.fingerprint === fingerprintValue);
|
|
329
|
+
if (!record) throw Error('fingerprint_not_found');
|
|
330
|
+
if (record.status === status) return;
|
|
331
|
+
record.status = status;
|
|
332
|
+
record.resolved_at = status === 'resolved' ? now(options) : null;
|
|
333
|
+
record.reason_code = status === 'resolved' ? 'operator_resolved' : null;
|
|
334
|
+
record.sequence = store.next_sequence++;
|
|
335
|
+
store.records.sort((a, b) => a.sequence - b.sequence);
|
|
336
|
+
writeStore(path, store);
|
|
337
|
+
});
|
|
338
|
+
return snapshot(options);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function compactRuntimeErrors(options = {}) {
|
|
342
|
+
if (!collectionEnabled(options)) return snapshot(options);
|
|
343
|
+
const { path } = optionsFor(options);
|
|
344
|
+
lock(path, () => {
|
|
345
|
+
const store = readStore(path);
|
|
346
|
+
const cutoff = Date.parse(now(options)) - RETENTION_MS;
|
|
347
|
+
store.records = store.records.filter((record) => !(record.status === 'resolved'
|
|
348
|
+
&& record.sequence <= store.acknowledged_through
|
|
349
|
+
&& record.resolved_at !== null
|
|
350
|
+
&& Date.parse(record.resolved_at) <= cutoff));
|
|
351
|
+
writeStore(path, store);
|
|
352
|
+
});
|
|
353
|
+
return snapshot(options);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export const runtimeErrorsInternal = { validate, definitions, fingerprintOf };
|