@arcforge/types 2.0.100 → 2.0.102

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.
@@ -0,0 +1,123 @@
1
+ import type { AxonError } from "../../error"
2
+
3
+ /**
4
+ * The span convention: every bracketed operation in the runtime declares
5
+ * itself through these helpers, so a family cannot ship a missing half —
6
+ * the triad is generated, not hand-written three times and hoped over.
7
+ *
8
+ * ```
9
+ * <namespace>:<operation>:start opening facts
10
+ * <namespace>:<operation>:complete + durationMs
11
+ * <namespace>:<operation>:failed + error: AxonError
12
+ * <namespace>:<operation>:interrupted cancellation — never an error
13
+ * ```
14
+ *
15
+ * This is a load-bearing contract, not a naming preference. Two consumers
16
+ * derive meaning from the suffix alone and break silently on a family that
17
+ * invents its own verbs:
18
+ *
19
+ * - The flame graph pairs bars by stripping `:start`/`:complete`/`:failed`
20
+ * and stack-matching within a run (see apps/fleet's toFlameData). A
21
+ * family named `loaded`/`spawned`/`restarting` is simply invisible to it.
22
+ * - classifyEvent / isLogEventType read the type namespace and suffix as
23
+ * the whole classification (envelope.ts rule 3).
24
+ *
25
+ * WHY THIS AND NOT SPAN IDS. Nesting is recovered by bracket-matching, not
26
+ * by a parent pointer: the session is one file with one serialized writer
27
+ * (so disk order IS commit order, and `time.seq` is authoritative), and the
28
+ * scheduler admits one wake at a time. Within a run there is exactly one
29
+ * logical thread of execution, so "what happened inside this span" is
30
+ * exactly "the events between its start and its end, in seq order". That
31
+ * is not an approximation — given one writer and one wake it is exact,
32
+ * which is why `parentSpanId` was removed rather than plumbed (see
33
+ * envelope.ts). `spanId` survives only for operations that genuinely
34
+ * interleave with a concurrent sibling — engine calls today.
35
+ */
36
+
37
+ /**
38
+ * A bracketed operation: start / complete / failed.
39
+ *
40
+ * `durationMs` is added to BOTH ends here rather than repeated per family,
41
+ * so every span in the system is measurable by construction however it
42
+ * settled. A failed operation still took time, and a reader sizing a bar or
43
+ * hunting a slow path cares about the failures most of all — "the call that
44
+ * blew up after 30s" is a different problem from "the call that blew up
45
+ * instantly".
46
+ *
47
+ * The failure payload DEFAULTS to `{ error: AxonError }` — rule 4 of the
48
+ * envelope, and what a family should want unless it has a specific reason
49
+ * otherwise. Passing `Failed` explicitly REPLACES that default rather than
50
+ * intersecting with it, because the two real exceptions in this system
51
+ * both need to substitute the payload, not extend it:
52
+ *
53
+ * - `kernel:engine:failed` carries `AxonEngineFault` — a richer domain
54
+ * shape (code, provider, model, retryable) that drives the retry loop.
55
+ * - `kernel:run:failed` carries `{}` — err()'s sink already committed the
56
+ * canonical error at the throw site; repeating it would log one failure
57
+ * twice under two names.
58
+ *
59
+ * Substitution rather than extension keeps those honest: the exception is
60
+ * visible at the declaration, not buried as an `error` field nobody fills.
61
+ *
62
+ * @example
63
+ * type Boot = AxonSpan<"axon:boot", { version: string }>
64
+ * // axon:boot:start { version: string }
65
+ * // axon:boot:complete { durationMs: number }
66
+ * // axon:boot:failed { error: AxonError } ← default
67
+ *
68
+ * @example
69
+ * type Engine = AxonSpan<"kernel:engine", {}, {}, { fault: AxonEngineFault }>
70
+ * // kernel:engine:failed { fault: AxonEngineFault } ← substituted
71
+ */
72
+ export type AxonSpan<Name extends string, Start = {}, Complete = {}, Failed = { error: AxonError }> =
73
+ & { [K in `${Name}:start`]: Start }
74
+ & { [K in `${Name}:complete`]: Complete & { durationMs: number } }
75
+ & { [K in `${Name}:failed`]: Failed & { durationMs: number } }
76
+
77
+ /**
78
+ * The fourth state, for operations that can be cancelled.
79
+ *
80
+ * Interruption is a SETTLED OUTCOME, not a failure: a wake ended by Escape,
81
+ * Ctrl+C, or shutdown did what it was told. It must never render as an
82
+ * error, and devtools must never conflate the two — hence a distinct
83
+ * suffix rather than a `reason` discriminant inside `:failed`.
84
+ *
85
+ * Applied at every level cancellation is observable: kernel:run,
86
+ * cognet:tick, cognet:phase, cognet:system, capsule:cmd.
87
+ */
88
+ export type AxonInterrupted<Name extends string, P = {}> = {
89
+ [K in `${Name}:interrupted`]: P
90
+ }
91
+
92
+ /** A span that can also be cancelled — the four-state form. */
93
+ export type AxonCancellableSpan<Name extends string, Start = {}, Complete = {}, Failed = {}, Interrupted = {}> =
94
+ & AxonSpan<Name, Start, Complete, Failed>
95
+ & AxonInterrupted<Name, Interrupted>
96
+
97
+ /** The span suffixes, in the one place a suffix-matching reader should derive them from. */
98
+ export const SPAN_SUFFIXES = [":start", ":complete", ":failed", ":interrupted"] as const
99
+
100
+ /** The suffixes that END a span — the closing half of a bracket. */
101
+ export const SPAN_END_SUFFIXES = [":complete", ":failed", ":interrupted"] as const
102
+
103
+ /** True for the opening half of a span bracket. */
104
+ export function isSpanStart(type: string): boolean {
105
+ return type.endsWith(":start")
106
+ }
107
+
108
+ /** True for any closing half of a span bracket (complete, failed, or interrupted). */
109
+ export function isSpanEnd(type: string): boolean {
110
+ return SPAN_END_SUFFIXES.some(suffix => type.endsWith(suffix))
111
+ }
112
+
113
+ /**
114
+ * The stem shared by one span's members — `"kernel:run:start"` → `"kernel:run"`.
115
+ * Returns the type unchanged when it is not a span member, so a caller can
116
+ * use it as a grouping key over a mixed stream without pre-filtering.
117
+ */
118
+ export function spanStem(type: string): string {
119
+ for (const suffix of SPAN_SUFFIXES) {
120
+ if (type.endsWith(suffix)) return type.slice(0, -suffix.length)
121
+ }
122
+ return type
123
+ }
@@ -19,6 +19,10 @@ export type { AxonOutputEvent, AxonOutputType } from "./events/stdio/output"
19
19
  export type { AxonChunk, StimulusRef } from "./events/stdio/shared"
20
20
  export type { AxonLogEvents } from "./events/log"
21
21
  export { LOG_EVENT_SUFFIXES, isLogEventType } from "./events/log"
22
+ export type { AxonSpan, AxonInterrupted, AxonCancellableSpan } from "./events/span"
23
+ export { SPAN_SUFFIXES, SPAN_END_SUFFIXES, isSpanStart, isSpanEnd, spanStem } from "./events/span"
24
+ export type { ReadableEvent, ReadNode, SpanNode, LeafNode } from "./read"
25
+ export { readSession, formatSession, isSpanNode } from "./read"
22
26
  export type { BenchEvent, BenchEventContext, BenchEventMap } from "./events/bench"
23
27
  export type {
24
28
  AxonTestEvent,
@@ -0,0 +1,173 @@
1
+ import { isSpanEnd, isSpanStart, spanStem } from "./events/span"
2
+
3
+ /**
4
+ * The session reader — turns the flat JSONL back into the nested shape of
5
+ * what actually happened.
6
+ *
7
+ * This is what the span vocabulary is FOR. Because the session is one file
8
+ * with one serialized writer (disk order IS commit order, `time.seq`
9
+ * authoritative) and the scheduler admits one wake at a time, nesting is
10
+ * exactly time containment: a span's parent is the innermost span still
11
+ * open when it started. That is not a heuristic — given one writer and one
12
+ * logical thread of execution it is an exact reconstruction, which is why
13
+ * this needs no parentSpanId and why none is ever emitted (see envelope.ts).
14
+ *
15
+ * An agent author debugging a bad tick wants "what happened inside this
16
+ * phase, in order" — not a flat 400-line stream. That is this function.
17
+ */
18
+
19
+ /** The minimum an event must have to be readable — satisfied by every AxonEvent. */
20
+ export type ReadableEvent = {
21
+ type: string
22
+ time: { seq: number; ms: number }
23
+ context: { runId?: string }
24
+ data: Record<string, unknown>
25
+ }
26
+
27
+ export type SpanNode<E extends ReadableEvent = ReadableEvent> = {
28
+ /** The family, e.g. "kernel:run" — the triad's shared stem. */
29
+ stem: string
30
+ /** What distinguishes this bracket from its siblings (tick number, phase name, command id). */
31
+ key: string
32
+ /** How the span settled. "open" means it never closed — a truncated log or a crash mid-span. */
33
+ outcome: "complete" | "failed" | "interrupted" | "open"
34
+ start: E
35
+ /** Absent while the span is open. */
36
+ end?: E
37
+ durationMs?: number
38
+ /** Nested spans and bare events, in the order they occurred. */
39
+ children: ReadNode<E>[]
40
+ }
41
+
42
+ /** A bare event — one that isn't half of a bracket. */
43
+ export type LeafNode<E extends ReadableEvent = ReadableEvent> = {
44
+ stem: null
45
+ event: E
46
+ }
47
+
48
+ export type ReadNode<E extends ReadableEvent = ReadableEvent> = SpanNode<E> | LeafNode<E>
49
+
50
+ export function isSpanNode<E extends ReadableEvent>(node: ReadNode<E>): node is SpanNode<E> {
51
+ return node.stem !== null
52
+ }
53
+
54
+ /**
55
+ * What names THIS bracket among its siblings of the same stem.
56
+ *
57
+ * Every span family that can have concurrent or repeated siblings puts its
58
+ * discriminator in the payload (tick number, phase name, command id) — the
59
+ * one exception being engine calls, which carry a stamped spanId because
60
+ * two can genuinely interleave. Families with neither are singular per run
61
+ * and key on the empty string.
62
+ */
63
+ function bracketKey(event: ReadableEvent): string {
64
+ const d = event.data
65
+ const parts: string[] = []
66
+ for (const field of ["tick", "phase", "system", "id", "procId", "namespace", "name", "fn"] as const) {
67
+ const value = d[field]
68
+ if (typeof value === "string" || typeof value === "number") parts.push(`${field}:${value}`)
69
+ }
70
+ const spanId = (event.context as { spanId?: string }).spanId
71
+ if (spanId) parts.push(`span:${spanId}`)
72
+ return parts.join("|")
73
+ }
74
+
75
+ function outcomeOf(type: string): "complete" | "failed" | "interrupted" {
76
+ if (type.endsWith(":failed")) return "failed"
77
+ if (type.endsWith(":interrupted")) return "interrupted"
78
+ return "complete"
79
+ }
80
+
81
+ /**
82
+ * Rebuild the tree.
83
+ *
84
+ * Events are read in `time.seq` order (sorted here so a caller can pass the
85
+ * three session views concatenated without pre-merging). A `:start` pushes
86
+ * a span; a matching end pops it and everything between becomes its
87
+ * children. Spans still open at the end of input stay `outcome: "open"` —
88
+ * an honest report of a truncated log, never silently dropped or
89
+ * force-closed.
90
+ *
91
+ * An end with no matching start (reading a window that began mid-span) is
92
+ * kept as a leaf rather than discarded: the log said it happened, so the
93
+ * reader says it happened.
94
+ */
95
+ export function readSession<E extends ReadableEvent>(events: readonly E[]): ReadNode<E>[] {
96
+ const ordered = [...events].sort((a, b) => a.time.seq - b.time.seq)
97
+
98
+ const roots: ReadNode<E>[] = []
99
+ const stack: SpanNode<E>[] = []
100
+ const siblings = () => (stack.length > 0 ? stack[stack.length - 1]!.children : roots)
101
+
102
+ for (const event of ordered) {
103
+ if (isSpanStart(event.type)) {
104
+ const node: SpanNode<E> = {
105
+ stem: spanStem(event.type),
106
+ key: bracketKey(event),
107
+ outcome: "open",
108
+ start: event,
109
+ children: [],
110
+ }
111
+ siblings().push(node)
112
+ stack.push(node)
113
+ continue
114
+ }
115
+
116
+ if (isSpanEnd(event.type)) {
117
+ const stem = spanStem(event.type)
118
+ const key = bracketKey(event)
119
+ // Search from the innermost outward: a well-formed log closes the
120
+ // top of the stack, but a family that failed to close an inner
121
+ // span must not swallow its parent's end event.
122
+ const depth = findOpen(stack, stem, key)
123
+ if (depth !== -1) {
124
+ // Anything still open inside this one never closed — pop it
125
+ // too, leaving its outcome as "open" so the gap is visible.
126
+ const node = stack[depth]!
127
+ stack.length = depth
128
+ node.outcome = outcomeOf(event.type)
129
+ node.end = event
130
+ const durationMs = event.data.durationMs
131
+ if (typeof durationMs === "number") node.durationMs = durationMs
132
+ continue
133
+ }
134
+ }
135
+
136
+ siblings().push({ stem: null, event })
137
+ }
138
+
139
+ return roots
140
+ }
141
+
142
+ /** Innermost open span matching stem+key, or -1. */
143
+ function findOpen<E extends ReadableEvent>(stack: SpanNode<E>[], stem: string, key: string): number {
144
+ for (let i = stack.length - 1; i >= 0; i--) {
145
+ const node = stack[i]!
146
+ if (node.stem === stem && node.key === key) return i
147
+ }
148
+ return -1
149
+ }
150
+
151
+ /**
152
+ * Render the tree as indented text — the view an agent author actually
153
+ * reads when a tick went wrong. Deliberately plain: one line per node,
154
+ * outcome and duration where they exist.
155
+ */
156
+ export function formatSession<E extends ReadableEvent>(nodes: readonly ReadNode<E>[], indent = 0): string {
157
+ const pad = " ".repeat(indent)
158
+ const lines: string[] = []
159
+
160
+ for (const node of nodes) {
161
+ if (!isSpanNode(node)) {
162
+ lines.push(`${pad}· ${node.event.type}`)
163
+ continue
164
+ }
165
+ const duration = node.durationMs !== undefined ? ` ${node.durationMs}ms` : ""
166
+ const outcome = node.outcome === "complete" ? "" : ` [${node.outcome}]`
167
+ const key = node.key ? ` (${node.key})` : ""
168
+ lines.push(`${pad}▸ ${node.stem}${key}${duration}${outcome}`)
169
+ if (node.children.length > 0) lines.push(formatSession(node.children, indent + 1))
170
+ }
171
+
172
+ return lines.join("\n")
173
+ }
@@ -1,69 +0,0 @@
1
- import type { EngineRef } from "../engine"
2
- import type { BenchValue } from "./value"
3
-
4
- export type BenchFactorKind =
5
- | "agent"
6
- | "model"
7
- | "cognet"
8
- | "dataset"
9
- | "toolset"
10
- | "environment"
11
- | "judge"
12
- | "value"
13
-
14
- export type BenchFactorRole = "subject" | "control" | "input" | "assessor"
15
-
16
- export type BenchFactorValue<T> = {
17
- /** Stable within the factor; used in cell identities. */
18
- id: string
19
- label?: string
20
- description?: string
21
- value: T
22
- }
23
-
24
- type Factor<K extends BenchFactorKind, T> = {
25
- id: string
26
- label: string
27
- description?: string
28
- kind: K
29
- role: BenchFactorRole
30
- /** One value is a held constant; two or more form a matrix axis. */
31
- values: BenchFactorValue<T>[]
32
- }
33
-
34
- export type BenchFactor =
35
- | Factor<"agent", { ref: string }>
36
- | Factor<"model", { engine: EngineRef }>
37
- | Factor<"cognet", { ref: string }>
38
- | Factor<"dataset", { ref: string; split?: string }>
39
- | Factor<"toolset", { refs: string[] }>
40
- | Factor<"environment", { env: Record<string, string> }>
41
- | Factor<"judge", { ref: string; rubric?: string }>
42
- | Factor<"value", BenchValue>
43
-
44
- export type BenchFactorSelection = {
45
- factorId: string
46
- kind: BenchFactorKind
47
- valueId: string
48
- }
49
-
50
- /** A raw Cartesian coordinate before values are resolved and pinned. */
51
- export type BenchCoordinate = {
52
- id: string
53
- factors: BenchFactorSelection[]
54
- }
55
-
56
- /** Manifest-safe identity of a selected value. Secret values are never included. */
57
- export type BenchResolvedFactor = BenchFactorSelection & {
58
- role: BenchFactorRole
59
- label: string
60
- /** Immutable registry version, content hash, or canonical value hash. */
61
- pin: string
62
- }
63
-
64
- /** One fully resolved coordinate, including both swept and constant factors. */
65
- export type BenchCell = {
66
- id: string
67
- factors: BenchResolvedFactor[]
68
- }
69
-