@spellkave/agent-observability 0.0.0-bootstrap → 0.0.0-stage
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/README.md +3 -0
- package/package.json +4 -33
- package/LICENSE +0 -89
- package/src/correlation.ts +0 -84
- package/src/emit.ts +0 -231
- package/src/events.ts +0 -399
- package/src/index.ts +0 -13
- package/src/metrics.ts +0 -677
- package/src/node-memory.ts +0 -73
- package/src/node-metrics.ts +0 -36
- package/src/node-resource.ts +0 -92
- package/src/node-traces.ts +0 -27
- package/src/node.ts +0 -379
- package/src/otel.ts +0 -594
- package/src/reader.ts +0 -122
- package/src/traces.ts +0 -261
- package/src/world-table-event.ts +0 -52
package/src/node-memory.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import type { HostMemorySample, WorldActorMetrics } from "./metrics.ts";
|
|
3
|
-
|
|
4
|
-
function byteCount(raw: string): number | undefined {
|
|
5
|
-
const value = raw.trim();
|
|
6
|
-
if (!/^\d+$/.test(value)) return undefined;
|
|
7
|
-
const bytes = Number(value);
|
|
8
|
-
return Number.isSafeInteger(bytes) ? bytes : undefined;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/** Best-effort cgroup-v2 snapshot. Missing files/unlimited values are absent,
|
|
12
|
-
* not zero. Process RSS includes all workers; other process fields describe
|
|
13
|
-
* the calling isolate. External includes arrayBuffers: never add them twice.
|
|
14
|
-
* No credentials, process arguments, or gameplay state are read. */
|
|
15
|
-
export async function sampleHostMemory(
|
|
16
|
-
read: (path: string) => Promise<string> = (path) => readFile(path, "utf8"),
|
|
17
|
-
memory: () => NodeJS.MemoryUsage = () => process.memoryUsage(),
|
|
18
|
-
): Promise<HostMemorySample> {
|
|
19
|
-
const usage = memory();
|
|
20
|
-
const fields = [
|
|
21
|
-
["cgroupCurrentBytes", "memory.current"],
|
|
22
|
-
["cgroupPeakBytes", "memory.peak"],
|
|
23
|
-
["cgroupLimitBytes", "memory.max"],
|
|
24
|
-
] as const;
|
|
25
|
-
const sample: HostMemorySample = {
|
|
26
|
-
processRssBytes: usage.rss,
|
|
27
|
-
heapUsedBytes: usage.heapUsed,
|
|
28
|
-
heapTotalBytes: usage.heapTotal,
|
|
29
|
-
externalBytes: usage.external,
|
|
30
|
-
arrayBuffersBytes: usage.arrayBuffers,
|
|
31
|
-
};
|
|
32
|
-
await Promise.all(
|
|
33
|
-
fields.map(async ([key, file]) => {
|
|
34
|
-
try {
|
|
35
|
-
const bytes = byteCount(await read(`/sys/fs/cgroup/${file}`));
|
|
36
|
-
if (bytes !== undefined) sample[key] = bytes;
|
|
37
|
-
} catch {
|
|
38
|
-
// Non-Linux and unavailable cgroups retain the process-only sample.
|
|
39
|
-
}
|
|
40
|
-
}),
|
|
41
|
-
);
|
|
42
|
-
return sample;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Independent of NPC cycle completion: a wedged cycle must not freeze the
|
|
46
|
-
* host-memory signal. At most one snapshot is in flight; stop discards it. */
|
|
47
|
-
export function startHostMemorySampler(
|
|
48
|
-
metrics: Pick<WorldActorMetrics, "recordHostMemory">,
|
|
49
|
-
sample: () => Promise<HostMemorySample> = sampleHostMemory,
|
|
50
|
-
intervalMs = 10_000,
|
|
51
|
-
): () => void {
|
|
52
|
-
let stopped = false;
|
|
53
|
-
let pending = false;
|
|
54
|
-
const tick = async () => {
|
|
55
|
-
if (stopped || pending) return;
|
|
56
|
-
pending = true;
|
|
57
|
-
try {
|
|
58
|
-
const value = await sample();
|
|
59
|
-
if (!stopped) metrics.recordHostMemory?.(value);
|
|
60
|
-
} catch {
|
|
61
|
-
// Sampling/export callbacks cannot terminate the observed host.
|
|
62
|
-
} finally {
|
|
63
|
-
pending = false;
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
const timer = setInterval(() => void tick(), intervalMs);
|
|
67
|
-
timer.unref();
|
|
68
|
-
void tick();
|
|
69
|
-
return () => {
|
|
70
|
-
stopped = true;
|
|
71
|
-
clearInterval(timer);
|
|
72
|
-
};
|
|
73
|
-
}
|
package/src/node-metrics.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { createOtlpHttpMetrics, type WorldActorMetrics } from "./metrics.ts";
|
|
2
|
-
import {
|
|
3
|
-
describeExportError,
|
|
4
|
-
parseOtelPairs,
|
|
5
|
-
worldActorResourceAttributes,
|
|
6
|
-
} from "./node-resource.ts";
|
|
7
|
-
|
|
8
|
-
/** Standard OTel environment bootstrap for Node hosts. Metrics stay disabled
|
|
9
|
-
* when no endpoint is configured and never become a gameplay dependency. */
|
|
10
|
-
export function createWorldActorMetricsFromEnv(
|
|
11
|
-
env: NodeJS.ProcessEnv = process.env,
|
|
12
|
-
dimensions: Pick<
|
|
13
|
-
Parameters<typeof createOtlpHttpMetrics>[0],
|
|
14
|
-
| "allowedToolNames"
|
|
15
|
-
| "allowedCycleSteps"
|
|
16
|
-
| "allowedErrorCodes"
|
|
17
|
-
| "serviceName"
|
|
18
|
-
| "logTransportSnapshot"
|
|
19
|
-
> = {},
|
|
20
|
-
): WorldActorMetrics | undefined {
|
|
21
|
-
if (env.SPELLKAVE_OTEL_DISABLED === "1") return undefined;
|
|
22
|
-
const endpoint = env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
23
|
-
if (endpoint === undefined || endpoint.trim() === "") return undefined;
|
|
24
|
-
return createOtlpHttpMetrics({
|
|
25
|
-
endpoint,
|
|
26
|
-
serviceName: env.OTEL_SERVICE_NAME ?? "spellkave-world-actors",
|
|
27
|
-
headers: parseOtelPairs(
|
|
28
|
-
env.OTEL_EXPORTER_OTLP_METRICS_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,
|
|
29
|
-
),
|
|
30
|
-
resourceAttributes: worldActorResourceAttributes(env),
|
|
31
|
-
...dimensions,
|
|
32
|
-
onError: (error) => {
|
|
33
|
-
console.error(`world-actor metrics export failed (${describeExportError(error)})`);
|
|
34
|
-
},
|
|
35
|
-
});
|
|
36
|
-
}
|
package/src/node-resource.ts
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import { OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS } from "./otel.ts";
|
|
2
|
-
|
|
3
|
-
export function parseOtelPairs(value: string | undefined): Record<string, string> {
|
|
4
|
-
const out: Record<string, string> = {};
|
|
5
|
-
if (value === undefined) return out;
|
|
6
|
-
for (const pair of value.split(",")) {
|
|
7
|
-
const separator = pair.indexOf("=");
|
|
8
|
-
if (separator <= 0) continue;
|
|
9
|
-
const key = pair.slice(0, separator).trim();
|
|
10
|
-
const raw = pair.slice(separator + 1).trim();
|
|
11
|
-
if (key === "") continue;
|
|
12
|
-
try {
|
|
13
|
-
out[key] = decodeURIComponent(raw);
|
|
14
|
-
} catch {
|
|
15
|
-
out[key] = raw;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
return out;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** Environment variable carrying the deployed application revision. */
|
|
22
|
-
export const IMAGE_TAG_ENV = "SPELLKAVE_IMAGE_TAG";
|
|
23
|
-
|
|
24
|
-
/** The deployed revision for OTel `service.version`, or undefined when the
|
|
25
|
-
* host did not declare one (local dev) — never a placeholder. */
|
|
26
|
-
export function serviceVersionFromEnv(env: NodeJS.ProcessEnv): string | undefined {
|
|
27
|
-
const tag = env[IMAGE_TAG_ENV]?.trim();
|
|
28
|
-
return tag ? tag : undefined;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Stable host identity wins over generic OTel resource configuration. A
|
|
32
|
-
* multi-world gateway sets this only on the per-world child process; NPC
|
|
33
|
-
* systemd instances derive it from their catalog slug (`%i`). The deployed
|
|
34
|
-
* revision rides along as `service.version` for traces and metrics; the logs
|
|
35
|
-
* projection reads the same env through `createOtlpHttpSink`'s
|
|
36
|
-
* `serviceVersion` (sk-0m4.120.13). */
|
|
37
|
-
export function worldActorResourceAttributes(env: NodeJS.ProcessEnv): Record<string, string> {
|
|
38
|
-
const attributes = parseOtelPairs(env.OTEL_RESOURCE_ATTRIBUTES);
|
|
39
|
-
const worldSlug = env.SPELLKAVE_WORLD_SLUG?.trim();
|
|
40
|
-
if (worldSlug) attributes["spellkave.world_slug"] = worldSlug;
|
|
41
|
-
const serviceVersion = serviceVersionFromEnv(env);
|
|
42
|
-
if (serviceVersion !== undefined) attributes["service.version"] = serviceVersion;
|
|
43
|
-
return attributes;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** The allowlisted subset of `OTEL_RESOURCE_ATTRIBUTES` for the logs sink
|
|
47
|
-
* (sk-jay0.6.38.13). Lets the four Node logs-sink call sites pass one call
|
|
48
|
-
* instead of hand-filtering the raw env var against
|
|
49
|
-
* `OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS` themselves. */
|
|
50
|
-
export function logSinkResourceAttributesFromEnv(env: NodeJS.ProcessEnv): Record<string, string> {
|
|
51
|
-
const attributes = parseOtelPairs(env.OTEL_RESOURCE_ATTRIBUTES);
|
|
52
|
-
const filtered: Record<string, string> = {};
|
|
53
|
-
for (const [key, value] of Object.entries(attributes)) {
|
|
54
|
-
if (OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS.has(key)) filtered[key] = value;
|
|
55
|
-
}
|
|
56
|
-
return filtered;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** One-line description of an export failure, for a console log.
|
|
60
|
-
*
|
|
61
|
-
* Both `name` and `message`, because either alone misleads
|
|
62
|
-
* (sk-jay0.6.15.56.21). Node's `fetch` reports every network-level failure as
|
|
63
|
-
* `TypeError: fetch failed`, so a reporter printing only `error.name` writes
|
|
64
|
-
* "TypeError" — which reads as a code defect and is really a dropped
|
|
65
|
-
* connection. The metrics and traces exporters did exactly that while the logs
|
|
66
|
-
* exporter printed only `message`, so one intermittent network fault appeared
|
|
67
|
-
* in the same pod log under two unrelated-looking descriptions, and the metrics
|
|
68
|
-
* one was unactionable: no type, no reason, no stack.
|
|
69
|
-
*
|
|
70
|
-
* Deliberately no stack and no `cause` message: this string goes to a console
|
|
71
|
-
* that ships to the operator log, and an exporter failure's cause can carry a
|
|
72
|
-
* request URL. The one exception is the cause's `code` when it is a bare
|
|
73
|
-
* error-code token (`UND_ERR_CONNECT_TIMEOUT`, `ECONNRESET`, `EAI_AGAIN`):
|
|
74
|
-
* `fetch failed` alone does not say whether the connect timed out, the peer
|
|
75
|
-
* reset it or DNS failed. A token
|
|
76
|
-
* that matches the pattern cannot carry a URL; anything else is left out.
|
|
77
|
-
*/
|
|
78
|
-
export function describeExportError(error: unknown): string {
|
|
79
|
-
if (!(error instanceof Error)) return typeof error;
|
|
80
|
-
const base = error.message === "" ? error.name : `${error.name}: ${error.message}`;
|
|
81
|
-
const code = causeCode(error);
|
|
82
|
-
return code === undefined ? base : `${base} [${code}]`;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const ERROR_CODE_TOKEN = /^[A-Z][A-Z0-9_]{1,63}$/u;
|
|
86
|
-
|
|
87
|
-
function causeCode(error: Error): string | undefined {
|
|
88
|
-
const cause: unknown = (error as { cause?: unknown }).cause;
|
|
89
|
-
if (typeof cause !== "object" || cause === null) return undefined;
|
|
90
|
-
const code: unknown = (cause as { code?: unknown }).code;
|
|
91
|
-
return typeof code === "string" && ERROR_CODE_TOKEN.test(code) ? code : undefined;
|
|
92
|
-
}
|
package/src/node-traces.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
describeExportError,
|
|
3
|
-
parseOtelPairs,
|
|
4
|
-
worldActorResourceAttributes,
|
|
5
|
-
} from "./node-resource.ts";
|
|
6
|
-
import { createOtlpHttpTracer, type WorldActorTracer } from "./traces.ts";
|
|
7
|
-
|
|
8
|
-
/** Standard OTel environment bootstrap for Node hosts. Disabled when no OTLP
|
|
9
|
-
* endpoint is configured; observability never becomes a gameplay dependency. */
|
|
10
|
-
export function createWorldActorTracerFromEnv(
|
|
11
|
-
env: NodeJS.ProcessEnv = process.env,
|
|
12
|
-
): WorldActorTracer | undefined {
|
|
13
|
-
if (env.SPELLKAVE_OTEL_DISABLED === "1") return undefined;
|
|
14
|
-
const endpoint = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
15
|
-
if (endpoint === undefined || endpoint.trim() === "") return undefined;
|
|
16
|
-
return createOtlpHttpTracer({
|
|
17
|
-
endpoint,
|
|
18
|
-
serviceName: env.OTEL_SERVICE_NAME ?? "spellkave-world-actors",
|
|
19
|
-
headers: parseOtelPairs(
|
|
20
|
-
env.OTEL_EXPORTER_OTLP_TRACES_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS,
|
|
21
|
-
),
|
|
22
|
-
resourceAttributes: worldActorResourceAttributes(env),
|
|
23
|
-
onError: (error) => {
|
|
24
|
-
console.error(`world-actor trace export failed (${describeExportError(error)})`);
|
|
25
|
-
},
|
|
26
|
-
});
|
|
27
|
-
}
|
package/src/node.ts
DELETED
|
@@ -1,379 +0,0 @@
|
|
|
1
|
-
// Node-only surface: the CANONICAL JSONL file sink and the run index over a
|
|
2
|
-
// directory tree (ADR-0074 S2). Kept out of the browser-safe barrel — the
|
|
3
|
-
// gateway sink and readers over in-memory text need no fs.
|
|
4
|
-
//
|
|
5
|
-
// Layout contract: the sink writes ONE standard-named file per run,
|
|
6
|
-
// `agent-run-events.jsonl`, INSIDE a run directory the host already owns
|
|
7
|
-
// (today: the retained-run structure under `.local/campaign-runs`, owned by
|
|
8
|
-
// world-explorer's CampaignArtifactStore). The host owns the tree; this
|
|
9
|
-
// package owns only the file name and its line format — that is what keeps
|
|
10
|
-
// progress-explorer's existing artifact walking working mid-migration.
|
|
11
|
-
import type { Dirent } from "node:fs";
|
|
12
|
-
import {
|
|
13
|
-
appendFileSync,
|
|
14
|
-
mkdirSync,
|
|
15
|
-
readdirSync,
|
|
16
|
-
readFileSync,
|
|
17
|
-
renameSync,
|
|
18
|
-
rmSync,
|
|
19
|
-
statSync,
|
|
20
|
-
writeFileSync,
|
|
21
|
-
} from "node:fs";
|
|
22
|
-
|
|
23
|
-
export * from "./node-memory.ts";
|
|
24
|
-
export * from "./node-metrics.ts";
|
|
25
|
-
export {
|
|
26
|
-
describeExportError,
|
|
27
|
-
IMAGE_TAG_ENV,
|
|
28
|
-
logSinkResourceAttributesFromEnv,
|
|
29
|
-
parseOtelPairs,
|
|
30
|
-
serviceVersionFromEnv,
|
|
31
|
-
} from "./node-resource.ts";
|
|
32
|
-
export * from "./node-traces.ts";
|
|
33
|
-
|
|
34
|
-
import { dirname, join } from "node:path";
|
|
35
|
-
import type { AgentRunSink } from "./emit.ts";
|
|
36
|
-
import type { AgentRunEvent } from "./events.ts";
|
|
37
|
-
import {
|
|
38
|
-
aggregateRunTotals,
|
|
39
|
-
classifyTerminal,
|
|
40
|
-
parseRunEvents,
|
|
41
|
-
type RunTotals,
|
|
42
|
-
type TerminalClassification,
|
|
43
|
-
} from "./reader.ts";
|
|
44
|
-
|
|
45
|
-
/** The one canonical per-run events file name. */
|
|
46
|
-
export const AGENT_RUN_EVENTS_FILENAME = "agent-run-events.jsonl";
|
|
47
|
-
|
|
48
|
-
/** Matches the campaign store's private-artifact posture (0600 files). */
|
|
49
|
-
const PRIVATE_FILE_MODE = 0o600;
|
|
50
|
-
const PRIVATE_DIRECTORY_MODE = 0o700;
|
|
51
|
-
|
|
52
|
-
export interface JsonlFileSinkOptions {
|
|
53
|
-
/**
|
|
54
|
-
* When true, truncate the file on first write of this sink instance so a
|
|
55
|
-
* re-run owns a clean artifact (commit-stable playthroughs). Default false
|
|
56
|
-
* — append remains the historical campaign/session behavior.
|
|
57
|
-
*/
|
|
58
|
-
truncate?: boolean;
|
|
59
|
-
/**
|
|
60
|
-
* Byte cap for the live file. Once a write would take it past the cap the
|
|
61
|
-
* file is rotated to `<path>.1` (replacing any previous generation) and a
|
|
62
|
-
* fresh file starts, so a long-lived appender occupies at most
|
|
63
|
-
* `2 * maxBytes` on disk, except for an event larger than the cap. The default leaves rotation disabled.
|
|
64
|
-
*
|
|
65
|
-
* A single line larger than the cap is still written whole; the sink never
|
|
66
|
-
* splits or drops an event, it only decides where the file boundary falls.
|
|
67
|
-
*/
|
|
68
|
-
maxBytes?: number;
|
|
69
|
-
/**
|
|
70
|
-
* Directory the volume budget is measured over — the root every seat's run
|
|
71
|
-
* directory lives under. Only
|
|
72
|
-
* meaningful together with {@link rootMaxBytes}.
|
|
73
|
-
*/
|
|
74
|
-
rootDir?: string;
|
|
75
|
-
/**
|
|
76
|
-
* Byte budget for the WHOLE tree under {@link rootDir}, enforced on every
|
|
77
|
-
* rotation by deleting rotated generations oldest-first (sk-jay0.6.15.40).
|
|
78
|
-
*
|
|
79
|
-
* A per-seat bound leaves total disk use dependent on the number of
|
|
80
|
-
* seats. Use a shared volume budget to bound retained generations.
|
|
81
|
-
*
|
|
82
|
-
* Live files are counted but never deleted: a live file is an in-flight run
|
|
83
|
-
* and the sink's byte counter would be wrong afterwards. When the live set
|
|
84
|
-
* alone exceeds the budget there is nothing left to prune, and
|
|
85
|
-
* {@link pruneRotatedTranscripts} says so in its result rather than
|
|
86
|
-
* pretending it succeeded — that is the signal that `maxBytes` or the PVC
|
|
87
|
-
* needs revisiting, not a condition this sink can fix.
|
|
88
|
-
*
|
|
89
|
-
* Default: `undefined` (no volume bound) — existing behavior.
|
|
90
|
-
*/
|
|
91
|
-
rootMaxBytes?: number;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/** What one budget enforcement pass did. */
|
|
95
|
-
export interface TranscriptPruneResult {
|
|
96
|
-
/** Bytes under the root before pruning (live + rotated). */
|
|
97
|
-
bytesBefore: number;
|
|
98
|
-
/** Bytes under the root after pruning. */
|
|
99
|
-
bytesAfter: number;
|
|
100
|
-
/** Rotated files deleted, oldest first. */
|
|
101
|
-
deleted: string[];
|
|
102
|
-
/**
|
|
103
|
-
* True when the budget is still exceeded with every rotated generation
|
|
104
|
-
* gone, i.e. the LIVE files alone do not fit. Nothing more can be pruned
|
|
105
|
-
* safely; `maxBytes` is too high for this seat count, or the volume is too
|
|
106
|
-
* small.
|
|
107
|
-
*/
|
|
108
|
-
overBudget: boolean;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Delete rotated run-event generations under `rootDir`, oldest first, until the
|
|
113
|
-
* whole tree fits in `budgetBytes`. Live `agent-run-events.jsonl` files are
|
|
114
|
-
* counted toward the budget and never deleted.
|
|
115
|
-
*
|
|
116
|
-
* Exported for the tests and for an operator one-shot; the sink calls it on
|
|
117
|
-
* rotation.
|
|
118
|
-
*/
|
|
119
|
-
export function pruneRotatedTranscripts(
|
|
120
|
-
rootDir: string,
|
|
121
|
-
budgetBytes: number,
|
|
122
|
-
): TranscriptPruneResult {
|
|
123
|
-
const live: number[] = [];
|
|
124
|
-
const rotated: { path: string; size: number; mtimeMs: number }[] = [];
|
|
125
|
-
walkTranscripts(rootDir, (path, stat) => {
|
|
126
|
-
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
127
|
-
if (name === AGENT_RUN_EVENTS_FILENAME) live.push(stat.size);
|
|
128
|
-
else if (name.startsWith(`${AGENT_RUN_EVENTS_FILENAME}.`))
|
|
129
|
-
rotated.push({ path, size: stat.size, mtimeMs: stat.mtimeMs });
|
|
130
|
-
});
|
|
131
|
-
const liveBytes = live.reduce((sum, size) => sum + size, 0);
|
|
132
|
-
let total = liveBytes + rotated.reduce((sum, file) => sum + file.size, 0);
|
|
133
|
-
const bytesBefore = total;
|
|
134
|
-
const deleted: string[] = [];
|
|
135
|
-
// Oldest first: the newest generation is the one most likely to still be
|
|
136
|
-
// worth reading next to its live file.
|
|
137
|
-
rotated.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
138
|
-
for (const file of rotated) {
|
|
139
|
-
if (total <= budgetBytes) break;
|
|
140
|
-
try {
|
|
141
|
-
rmSync(file.path, { force: true });
|
|
142
|
-
} catch {
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
total -= file.size;
|
|
146
|
-
deleted.push(file.path);
|
|
147
|
-
}
|
|
148
|
-
return { bytesBefore, bytesAfter: total, deleted, overBudget: total > budgetBytes };
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** Depth-first walk of `rootDir`, visiting every regular file. */
|
|
152
|
-
function walkTranscripts(
|
|
153
|
-
rootDir: string,
|
|
154
|
-
visit: (path: string, stat: { size: number; mtimeMs: number }) => void,
|
|
155
|
-
): void {
|
|
156
|
-
let entries: Dirent[];
|
|
157
|
-
try {
|
|
158
|
-
entries = readdirSync(rootDir, { withFileTypes: true });
|
|
159
|
-
} catch {
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
|
-
for (const entry of entries) {
|
|
163
|
-
const path = join(rootDir, entry.name);
|
|
164
|
-
if (entry.isDirectory()) {
|
|
165
|
-
walkTranscripts(path, visit);
|
|
166
|
-
continue;
|
|
167
|
-
}
|
|
168
|
-
if (!entry.isFile()) continue;
|
|
169
|
-
try {
|
|
170
|
-
const stat = statSync(path);
|
|
171
|
-
visit(path, { size: stat.size, mtimeMs: stat.mtimeMs });
|
|
172
|
-
} catch {
|
|
173
|
-
// Raced with another host's rotation; the next pass sees the truth.
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Canonical sink: append one JSON line per event. Writes are synchronous —
|
|
180
|
-
* an emitting run must never lose its tail on process exit, and event volume
|
|
181
|
-
* is tiny (tens of lines per run).
|
|
182
|
-
*/
|
|
183
|
-
export function createJsonlFileSink(
|
|
184
|
-
filePath: string,
|
|
185
|
-
options: JsonlFileSinkOptions = {},
|
|
186
|
-
): AgentRunSink {
|
|
187
|
-
let directoryReady = false;
|
|
188
|
-
let truncated = false;
|
|
189
|
-
const truncate = options.truncate === true;
|
|
190
|
-
const maxBytes =
|
|
191
|
-
options.maxBytes !== undefined && options.maxBytes > 0 ? options.maxBytes : undefined;
|
|
192
|
-
const rootDir = options.rootDir;
|
|
193
|
-
const rootMaxBytes =
|
|
194
|
-
rootDir !== undefined && options.rootMaxBytes !== undefined && options.rootMaxBytes > 0
|
|
195
|
-
? options.rootMaxBytes
|
|
196
|
-
: undefined;
|
|
197
|
-
// Tracked in-process: `statSync` per line would be a syscall per event, and
|
|
198
|
-
// this sink is the hot path of a 24/7 host. Seeded once from the file left
|
|
199
|
-
// by the previous process so a restart cannot reset the budget to zero.
|
|
200
|
-
let liveBytes: number | undefined;
|
|
201
|
-
// True when the file this sink opened was ALREADY over the cap: written by a
|
|
202
|
-
// build that had no rotation, so its size was never part of anyone's budget.
|
|
203
|
-
// Retiring it into `.1` would pin that size on the disk indefinitely, which
|
|
204
|
-
// is the very state this option exists to clear, so it is dropped once.
|
|
205
|
-
// A file WE wrote is always retained, even if one huge line overshot.
|
|
206
|
-
let legacyOversized = false;
|
|
207
|
-
|
|
208
|
-
function rotate(): void {
|
|
209
|
-
if (legacyOversized) {
|
|
210
|
-
rmSync(filePath, { force: true });
|
|
211
|
-
legacyOversized = false;
|
|
212
|
-
} else {
|
|
213
|
-
// POSIX rename replaces `.1` atomically: exactly one old generation.
|
|
214
|
-
renameSync(filePath, `${filePath}.1`);
|
|
215
|
-
}
|
|
216
|
-
liveBytes = 0;
|
|
217
|
-
// Rotation is the only moment this tree grows by a whole generation, so
|
|
218
|
-
// it is the right and cheapest place to enforce the volume budget: once
|
|
219
|
-
// per maxBytes written, never per line.
|
|
220
|
-
if (rootMaxBytes !== undefined && rootDir !== undefined) {
|
|
221
|
-
try {
|
|
222
|
-
const pruned = pruneRotatedTranscripts(rootDir, rootMaxBytes);
|
|
223
|
-
if (pruned.overBudget) {
|
|
224
|
-
// ADR-0002: say it, do not swallow it. Nothing else observes
|
|
225
|
-
// this — the volume filling is exactly the silent failure
|
|
226
|
-
// sk-jay0.6.15.40 records.
|
|
227
|
-
process.stderr.write(
|
|
228
|
-
`${JSON.stringify({
|
|
229
|
-
v: "agent-run-events-prune/v1",
|
|
230
|
-
kind: "transcript_budget_exceeded",
|
|
231
|
-
root: rootDir,
|
|
232
|
-
budget_bytes: rootMaxBytes,
|
|
233
|
-
bytes_after: pruned.bytesAfter,
|
|
234
|
-
deleted: pruned.deleted.length,
|
|
235
|
-
detail:
|
|
236
|
-
"live transcripts alone exceed the budget; lower SPELLKAVE_RUN_EVENTS_MAX_BYTES or grow the volume",
|
|
237
|
-
})}\n`,
|
|
238
|
-
);
|
|
239
|
-
}
|
|
240
|
-
} catch {
|
|
241
|
-
// A failed prune must never take the host down: the write that
|
|
242
|
-
// triggered it still has to land.
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
return {
|
|
248
|
-
write(event: AgentRunEvent) {
|
|
249
|
-
if (!directoryReady) {
|
|
250
|
-
mkdirSync(dirname(filePath), { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
|
|
251
|
-
directoryReady = true;
|
|
252
|
-
}
|
|
253
|
-
const line = `${JSON.stringify(event)}\n`;
|
|
254
|
-
if (truncate && !truncated) {
|
|
255
|
-
writeFileSync(filePath, line, { mode: PRIVATE_FILE_MODE });
|
|
256
|
-
truncated = true;
|
|
257
|
-
liveBytes = Buffer.byteLength(line);
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
if (maxBytes !== undefined) {
|
|
261
|
-
if (liveBytes === undefined) {
|
|
262
|
-
liveBytes = existingSize(filePath);
|
|
263
|
-
legacyOversized = liveBytes > maxBytes;
|
|
264
|
-
}
|
|
265
|
-
// Rotate only a non-empty file: a line bigger than the whole cap
|
|
266
|
-
// would otherwise rotate on every write and never make progress.
|
|
267
|
-
if (liveBytes > 0 && liveBytes + Buffer.byteLength(line) > maxBytes) rotate();
|
|
268
|
-
}
|
|
269
|
-
appendFileSync(filePath, line, { mode: PRIVATE_FILE_MODE });
|
|
270
|
-
if (liveBytes !== undefined) liveBytes += Buffer.byteLength(line);
|
|
271
|
-
},
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/** Size of an existing file, or 0 when it is absent/unreadable. */
|
|
276
|
-
function existingSize(filePath: string): number {
|
|
277
|
-
try {
|
|
278
|
-
return statSync(filePath).size;
|
|
279
|
-
} catch {
|
|
280
|
-
return 0;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** Read + tolerantly parse one run's events file. */
|
|
285
|
-
export function readRunEventsFile(filePath: string): ReturnType<typeof parseRunEvents> {
|
|
286
|
-
return parseRunEvents(readFileSync(filePath, "utf8"));
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/** One run as the index sees it. */
|
|
290
|
-
export interface RunIndexEntry {
|
|
291
|
-
/** Absolute path of the run's events file. */
|
|
292
|
-
file: string;
|
|
293
|
-
run_id: string;
|
|
294
|
-
run_kind: string;
|
|
295
|
-
actor_id: string;
|
|
296
|
-
role: string;
|
|
297
|
-
controller_kind: string;
|
|
298
|
-
driver: string;
|
|
299
|
-
model?: string;
|
|
300
|
-
seed: string;
|
|
301
|
-
/** ts of the first event (run start ordering key). */
|
|
302
|
-
first_ts: string;
|
|
303
|
-
/** ts of the last event. */
|
|
304
|
-
last_ts: string;
|
|
305
|
-
totals: RunTotals;
|
|
306
|
-
terminal: TerminalClassification;
|
|
307
|
-
/** Lines skipped by the tolerant parser. */
|
|
308
|
-
skipped_lines: number;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Run index: walk `root` recursively for `agent-run-events.jsonl` files and
|
|
313
|
-
* summarise each run PER ACTOR — the single consumption path for
|
|
314
|
-
* progress-explorer's index build and the playtest judge (S5). One run's
|
|
315
|
-
* timeline may carry several actors (the LLM player plus deterministic
|
|
316
|
-
* NPC/companion emitters share the run_id and sink); each actor gets its own
|
|
317
|
-
* summary so per-actor totals never bleed into each other.
|
|
318
|
-
*/
|
|
319
|
-
export function buildRunIndex(root: string): RunIndexEntry[] {
|
|
320
|
-
const entries: RunIndexEntry[] = [];
|
|
321
|
-
for (const file of walkForEventFiles(root)) {
|
|
322
|
-
const { events, skipped } = readRunEventsFile(file);
|
|
323
|
-
const byRunActor = new Map<string, AgentRunEvent[]>();
|
|
324
|
-
for (const event of events) {
|
|
325
|
-
const key = `${event.run_id}\u0000${event.actor_id}`;
|
|
326
|
-
const bucket = byRunActor.get(key);
|
|
327
|
-
if (bucket === undefined) byRunActor.set(key, [event]);
|
|
328
|
-
else bucket.push(event);
|
|
329
|
-
}
|
|
330
|
-
for (const runEvents of byRunActor.values()) {
|
|
331
|
-
const first = runEvents[0] as AgentRunEvent;
|
|
332
|
-
const last = runEvents[runEvents.length - 1] as AgentRunEvent;
|
|
333
|
-
entries.push({
|
|
334
|
-
file,
|
|
335
|
-
run_id: first.run_id,
|
|
336
|
-
run_kind: first.run_kind,
|
|
337
|
-
actor_id: first.actor_id,
|
|
338
|
-
role: first.role,
|
|
339
|
-
controller_kind: first.controller_kind,
|
|
340
|
-
driver: first.driver,
|
|
341
|
-
...(first.model !== undefined ? { model: first.model } : {}),
|
|
342
|
-
seed: first.seed,
|
|
343
|
-
first_ts: first.ts,
|
|
344
|
-
last_ts: last.ts,
|
|
345
|
-
totals: aggregateRunTotals(runEvents),
|
|
346
|
-
terminal: classifyTerminal(runEvents),
|
|
347
|
-
skipped_lines: skipped,
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
entries.sort((a, b) => a.first_ts.localeCompare(b.first_ts) || a.run_id.localeCompare(b.run_id));
|
|
352
|
-
return entries;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
function walkForEventFiles(root: string): string[] {
|
|
356
|
-
const files: string[] = [];
|
|
357
|
-
const stack = [root];
|
|
358
|
-
while (stack.length > 0) {
|
|
359
|
-
const dir = stack.pop() as string;
|
|
360
|
-
let names: string[];
|
|
361
|
-
try {
|
|
362
|
-
names = readdirSync(dir);
|
|
363
|
-
} catch {
|
|
364
|
-
continue; // unreadable/removed directory — the index is best-effort
|
|
365
|
-
}
|
|
366
|
-
for (const name of names) {
|
|
367
|
-
const path = join(dir, name);
|
|
368
|
-
let stats: ReturnType<typeof statSync>;
|
|
369
|
-
try {
|
|
370
|
-
stats = statSync(path);
|
|
371
|
-
} catch {
|
|
372
|
-
continue;
|
|
373
|
-
}
|
|
374
|
-
if (stats.isDirectory()) stack.push(path);
|
|
375
|
-
else if (name === AGENT_RUN_EVENTS_FILENAME) files.push(path);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
return files;
|
|
379
|
-
}
|