@anureo/workflow 0.3.1 → 0.3.3

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.
@@ -3,229 +3,123 @@ import { z } from 'zod'
3
3
  import { HarnessSdkError } from '@anureo/sdk'
4
4
  import type { JsonObject } from '@anureo/protocol'
5
5
 
6
- /** Package-internal schema and parser for agent execution and journal replay. */
7
6
  export interface AgentOutputSchema<S extends z.ZodObject = z.ZodObject> {
8
- /**
9
- * Closed draft-07 object schema. agentSubmission sends it or embeds it in the JSON-text
10
- * prompt, and memoizedAgent includes it in the journal key.
11
- */
12
7
  schema: JsonObject
13
- /**
14
- * Validate a complete JSON object before Zod can strip extra fields or fill omitted fields.
15
- * Resolve with the typed value after local Zod checks, including async refinements.
16
- * Blank text, malformed JSON and schema mismatches reject with AGENT_STRUCTURED_OUTPUT_MISSING,
17
- * AGENT_STRUCTURED_OUTPUT_NOT_JSON and AGENT_STRUCTURED_OUTPUT_INVALID, respectively. Exceptions
18
- * from Zod reject with AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED and omit the original cause.
19
- * observeAgentTurn awaits this parser after a completed turn and captures rejections so
20
- * executeAgent can release the session before settlement. For a typed cache hit,
21
- * replayAgentResult passes the saved value as canonical JSON and propagates the outcome.
22
- */
23
8
  parse(text: string): Promise<z.output<S>>
24
9
  }
25
10
 
26
- /**
27
- * Prepare a portable Zod object as a draft-07 schema and a parser for its inferred output.
28
- * Require closed objects and required JSON fields, including fields with JSON-compatible defaults.
29
- * Conversion schemas and other unsupported shapes synchronously throw INVALID_PARAMS with a
30
- * rule code in details.rule.
31
- * memoizedAgent prepares the pair before reserving a journal key and uses it for typed replay.
32
- * executeAgent prepares its own pair before opening a session. On a journal miss this happens
33
- * after the started record is published and dispatch is rechecked.
34
- */
35
- export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
36
- const { schema, validate } = compilePortableSchema(source)
37
- return {
38
- schema,
39
- async parse(text) {
40
- const value = parseRawOutput(text, validate)
41
- let parsed: z.ZodSafeParseResult<z.output<S>>
42
- try {
43
- parsed = await source.safeParseAsync(value)
44
- } catch {
45
- throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED')
46
- }
47
- if (!parsed.success) {
48
- throw outputMismatch(parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })))
49
- }
50
- return parsed.data
51
- },
52
- }
53
- }
54
-
55
- /**
56
- * Decode a single JSON object and check its raw fields before parse awaits Zod.
57
- * Throw the missing, malformed or invalid output error synchronously, copying any available
58
- * Ajv issue paths and codes into the invalid output error.
59
- */
60
- function parseRawOutput(text: string, validate: ValidateFunction): unknown {
61
- if (!text.trim()) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING')
62
- let value: unknown
63
- try {
64
- value = JSON.parse(text)
65
- } catch {
66
- throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON')
67
- }
68
- if (!value || typeof value !== 'object' || Array.isArray(value) || !validate(value)) {
69
- const issues = validate.errors?.map(error => ({ path: error.instancePath, code: error.keyword })) ?? []
70
- throw outputMismatch(issues)
71
- }
72
- return value
73
- }
74
-
75
- /** Use the same failure envelope for Ajv and Zod with only issue paths and codes. */
76
- function outputMismatch(issues: Array<{ path: string | PropertyKey[]; code: string }>): HarnessSdkError {
77
- return new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false, { issues })
11
+ class SchemaParameterError extends HarnessSdkError {
12
+ constructor(rule: string) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }) }
78
13
  }
79
14
 
80
- /**
81
- * Give prepareOutputSchema a detached draft-07 schema and a synchronous validator. Check the
82
- * Zod source before conversion, then check the emitted schema before compiling it with Ajv.
83
- * Preserve preflight rule codes and replace unexpected conversion, callback or Ajv exceptions
84
- * with INVALID_PARAMS. Ajv checks fields as supplied and leaves format assertions to Zod.
85
- */
86
- function compilePortableSchema(source: z.ZodObject): { schema: JsonObject; validate: ValidateFunction } {
87
- if (!(source instanceof z.ZodObject)) rejectSchema('objectRootRequired')
88
- try {
89
- checkPortableZodSource(source)
90
- const schema = structuredClone(z.toJSONSchema(source, {
91
- target: 'draft-7',
92
- io: 'output',
93
- unrepresentable: 'throw',
94
- })) as JsonObject
95
- delete schema.$schema
96
- if (schema.type !== 'object') rejectSchema('objectRootRequired')
97
- checkPortableJsonSchema(schema)
98
- const validate = new Ajv({
99
- allErrors: true,
100
- validateFormats: false,
101
- multipleOfPrecision: 6,
102
- logger: false,
103
- }).compile(schema)
104
- return { schema, validate }
105
- } catch (cause) {
106
- if (cause instanceof SchemaParameterError) throw cause
107
- rejectSchema('invalidOrUnrepresentableSchema')
108
- }
15
+ function invalid(rule: string): never {
16
+ throw new SchemaParameterError(rule)
109
17
  }
110
18
 
111
- /** Reject conversions and nonportable types in the source graph before Zod's output-mode converter can hide them. */
112
- function checkPortableZodSource(root: z.ZodObject): void {
19
+ /** Zod's converter can hide input-side transforms in output mode. Check the original graph too. */
20
+ function checkZod(root: z.ZodObject): void {
113
21
  const seen = new WeakSet<object>()
114
- const nonportableTypes = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
22
+ const rejected = new Set(['optional', 'record', 'tuple', 'pipe', 'transform', 'catch', 'prefault',
115
23
  'date', 'bigint', 'symbol', 'map', 'set', 'nan', 'undefined', 'void', 'custom', 'function', 'promise', 'file'])
116
- /** Follow definition fields once per node, including lazy schemas. Getter failures reach compilePortableSchema. */
117
- function visitZodNode(value: unknown): void {
24
+ function visit(value: unknown): void {
118
25
  if (!value || typeof value !== 'object' || seen.has(value)) return
119
26
  seen.add(value)
120
- if (!(value instanceof z.ZodType)) {
121
- for (const child of Object.values(value)) visitZodNode(child)
122
- return
123
- }
124
-
125
- const def = value._zod.def
126
- if (nonportableTypes.has(def.type) || ('coerce' in def && def.coerce)) {
127
- rejectSchema('valueConversionOrNonportableType')
128
- }
129
- if (def.checks?.some(check => check._zod.def.check === 'overwrite')) rejectSchema('valueConversion')
130
- if (value instanceof z.ZodLazy) visitZodNode(value._zod.def.getter())
131
- // Skip the checks list when walking child schemas because refinements can be ZodCustom instances.
132
- for (const [key, child] of Object.entries(def)) {
133
- if (key !== 'checks') visitZodNode(child)
27
+ if (value instanceof z.ZodType) {
28
+ const def = value._zod.def
29
+ if (rejected.has(def.type) || ('coerce' in def && def.coerce)) invalid('valueConversionOrNonportableType')
30
+ if (def.checks?.some(check => check._zod.def.check === 'overwrite')) invalid('valueConversion')
31
+ if (value instanceof z.ZodLazy) visit(value._zod.def.getter())
32
+ // Refinement checks can themselves be ZodCustom instances; they validate, not convert.
33
+ for (const [key, child] of Object.entries(def)) if (key !== 'checks') visit(child)
34
+ } else {
35
+ for (const child of Object.values(value)) visit(child)
134
36
  }
135
37
  }
136
- visitZodNode(root)
38
+ visit(root)
137
39
  }
138
40
 
139
- /**
140
- * Reject portability violations before Ajv compiles the generated schema. Follow only
141
- * subschema keywords because examples, defaults and enum values may contain schema-like keys.
142
- */
143
- function checkPortableJsonSchema(node: unknown): void {
144
- if (!node || typeof node !== 'object' || Array.isArray(node)) return
145
- const schema = node as JsonObject
146
- if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) {
147
- rejectSchema('externalOrAsyncSchema')
148
- }
149
- checkObjectProperties(schema)
150
- if (Array.isArray(schema.items) || schema.prefixItems) rejectSchema('tuple')
151
- checkSchemaBounds(schema)
152
-
153
- for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
154
- const children = schema[key]
155
- if (children && typeof children === 'object' && !Array.isArray(children)) {
156
- Object.values(children).forEach(checkPortableJsonSchema)
41
+ /** Walk schema locations, never examples/defaults/enum data that may contain schema-like keys. */
42
+ function checkJsonSchema(root: JsonObject): void {
43
+ function visit(node: unknown): void {
44
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return
45
+ const schema = node as JsonObject
46
+ if (schema.$async || (typeof schema.$ref === 'string' && !schema.$ref.startsWith('#'))) invalid('externalOrAsyncSchema')
47
+ if (schema.type === 'object' || (Array.isArray(schema.type) && schema.type.includes('object'))) {
48
+ if (schema.additionalProperties !== false) invalid('openObject')
49
+ const properties = schema.properties as JsonObject | undefined
50
+ const required = new Set(Array.isArray(schema.required) ? schema.required : [])
51
+ if (properties && Object.keys(properties).some(key => !required.has(key))) invalid('optionalProperty')
52
+ const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
53
+ ? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u')) : []
54
+ if (Array.isArray(schema.required) && schema.required.some(key => typeof key === 'string'
55
+ && !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)))) invalid('unsatisfiableRequired')
157
56
  }
57
+ if (Array.isArray(schema.items) || schema.prefixItems) invalid('tuple')
58
+ const type = schema.type
59
+ const pairs: Array<[string, string]> = type === 'string' ? [['minLength', 'maxLength']] : type === 'array' ? [['minItems', 'maxItems']]
60
+ : type === 'object' ? [['minProperties', 'maxProperties']] : []
61
+ for (const [min, max] of pairs) {
62
+ const lower = schema[min], upper = schema[max]
63
+ if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) invalid('unsatisfiableBounds')
64
+ }
65
+ if (type === 'number' || type === 'integer') {
66
+ const minimum = typeof schema.minimum === 'number' ? schema.minimum : -Infinity
67
+ const exclusiveMinimum = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : -Infinity
68
+ const lower = Math.max(minimum, exclusiveMinimum)
69
+ const maximum = typeof schema.maximum === 'number' ? schema.maximum : Infinity
70
+ const exclusiveMaximum = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : Infinity
71
+ const upper = Math.min(maximum, exclusiveMaximum)
72
+ const boundsCrossed = lower > upper
73
+ const equalBoundsExcludeValue = lower === upper
74
+ && (schema.exclusiveMinimum === lower || schema.exclusiveMaximum === upper)
75
+ if (boundsCrossed || equalBoundsExcludeValue) invalid('unsatisfiableBounds')
76
+ }
77
+ for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependentSchemas']) {
78
+ const children = schema[key]
79
+ if (children && typeof children === 'object' && !Array.isArray(children)) Object.values(children).forEach(visit)
80
+ }
81
+ for (const key of ['allOf', 'anyOf', 'oneOf']) {
82
+ const children = schema[key]
83
+ if (Array.isArray(children)) children.forEach(visit)
84
+ }
85
+ for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) visit(schema[key])
158
86
  }
159
- for (const key of ['allOf', 'anyOf', 'oneOf']) {
160
- const children = schema[key]
161
- if (Array.isArray(children)) children.forEach(checkPortableJsonSchema)
162
- }
163
- for (const key of ['items', 'contains', 'additionalProperties', 'propertyNames', 'not', 'if', 'then', 'else']) {
164
- checkPortableJsonSchema(schema[key])
165
- }
166
- }
167
-
168
- /** Check closure and requiredness before testing whether explicit properties or patterns admit each required key. */
169
- function checkObjectProperties(schema: JsonObject): void {
170
- if (schema.type !== 'object' && !(Array.isArray(schema.type) && schema.type.includes('object'))) return
171
- if (schema.additionalProperties !== false) rejectSchema('openObject')
172
- const properties = schema.properties as JsonObject | undefined
173
- const requiredKeys = Array.isArray(schema.required) ? schema.required : undefined
174
- const required = new Set(requiredKeys)
175
- if (properties && Object.keys(properties).some(key => !required.has(key))) rejectSchema('optionalProperty')
176
-
177
- const patterns = schema.patternProperties && typeof schema.patternProperties === 'object'
178
- ? Object.keys(schema.patternProperties).map(pattern => new RegExp(pattern, 'u'))
179
- : []
180
- const impossibleRequiredKey = requiredKeys?.some(key =>
181
- typeof key === 'string' && !Object.hasOwn(properties ?? {}, key) && !patterns.some(pattern => pattern.test(key)),
182
- )
183
- if (impossibleRequiredKey) {
184
- rejectSchema('unsatisfiableRequired')
185
- }
186
- }
187
-
188
- /** Check bounds for the declared type because other types' keywords do not constrain the instance. */
189
- function checkSchemaBounds(schema: JsonObject): void {
190
- switch (schema.type) {
191
- case 'string': return checkSizeBounds(schema.minLength, schema.maxLength)
192
- case 'array': return checkSizeBounds(schema.minItems, schema.maxItems)
193
- case 'object': return checkSizeBounds(schema.minProperties, schema.maxProperties)
194
- case 'number':
195
- case 'integer': return checkNumericBounds(schema)
196
- }
87
+ visit(root)
197
88
  }
198
89
 
199
- /** Reject contradictory sizes. Ajv checks the validity of the individual keyword values. */
200
- function checkSizeBounds(lower: unknown, upper: unknown): void {
201
- if (typeof lower === 'number' && typeof upper === 'number' && lower > upper) {
202
- rejectSchema('unsatisfiableBounds')
90
+ export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
91
+ if (!(source instanceof z.ZodObject)) invalid('objectRootRequired')
92
+ let schema: JsonObject
93
+ let validate: ValidateFunction
94
+ try {
95
+ checkZod(source)
96
+ schema = structuredClone(z.toJSONSchema(source, { target: 'draft-7', io: 'output', unrepresentable: 'throw' })) as JsonObject
97
+ delete schema.$schema
98
+ if (schema.type !== 'object') invalid('objectRootRequired')
99
+ checkJsonSchema(schema)
100
+ validate = new Ajv({ allErrors: true, validateFormats: false, multipleOfPrecision: 6, logger: false }).compile(schema)
101
+ } catch (cause) {
102
+ if (cause instanceof SchemaParameterError) throw cause
103
+ invalid('invalidOrUnrepresentableSchema')
203
104
  }
204
- }
205
-
206
- /** Reject crossed bounds or a shared endpoint excluded by either bound. */
207
- function checkNumericBounds(schema: JsonObject): void {
208
- const { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = schema
209
- const lower = Math.max(
210
- typeof minimum === 'number' ? minimum : -Infinity,
211
- typeof exclusiveMinimum === 'number' ? exclusiveMinimum : -Infinity,
212
- )
213
- const upper = Math.min(
214
- typeof maximum === 'number' ? maximum : Infinity,
215
- typeof exclusiveMaximum === 'number' ? exclusiveMaximum : Infinity,
216
- )
217
- const equalBoundsExcludeValue = lower === upper && (exclusiveMinimum === lower || exclusiveMaximum === upper)
218
- if (lower > upper || equalBoundsExcludeValue) {
219
- rejectSchema('unsatisfiableBounds')
105
+ return {
106
+ schema,
107
+ async parse(text) {
108
+ if (!text.trim()) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_MISSING')
109
+ let value: unknown
110
+ try { value = JSON.parse(text) } catch { throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON') }
111
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !validate(value)) {
112
+ throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false,
113
+ { issues: validate.errors?.map(error => ({ path: error.instancePath, code: error.keyword })) ?? [] })
114
+ }
115
+ // User refinements may throw independently of an ordinary validation mismatch.
116
+ let parsed: z.ZodSafeParseResult<z.output<S>>
117
+ try { parsed = await source.safeParseAsync(value) } catch {
118
+ throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_VALIDATION_FAILED')
119
+ }
120
+ if (!parsed.success) throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_INVALID', 'Agent output does not match its schema', false, false,
121
+ { issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })) })
122
+ return parsed.data
123
+ },
220
124
  }
221
125
  }
222
-
223
- /** Distinguish preflight rule failures from exceptions raised during conversion or compilation. */
224
- class SchemaParameterError extends HarnessSdkError {
225
- constructor(rule: string) { super('INVALID_PARAMS', 'Unsupported agent output schema', false, false, { rule }) }
226
- }
227
-
228
- /** Stop preflight with the rule code compilePortableSchema can carry through sanitization. */
229
- function rejectSchema(rule: string): never {
230
- throw new SchemaParameterError(rule)
231
- }
@@ -79,7 +79,6 @@ test('snapshots the callbacks before one callback mutates the input array', asyn
79
79
  expect(await parallel(callbacks)).toEqual([1, 2])
80
80
  })
81
81
 
82
- /** Compile-only assertions for positional inference and nullable failures; never invoked at runtime. */
83
82
  function checkTypes() {
84
83
  const values = parallel([() => 1, async () => 'two', () => true])
85
84
  const tuple: Promise<[number | null, string | null, boolean | null]> = values
package/src/parallel.ts CHANGED
@@ -1,33 +1,15 @@
1
- /**
2
- * Start a batch of zero-argument callbacks and collect their awaited results in input order.
3
- * After validation, invoke the callbacks in array order before returning the promise. Wait for
4
- * every callback result to settle before resolving. Tuple inputs preserve the awaited type at each position,
5
- * and an empty batch resolves to `[]`.
6
- *
7
- * A synchronous throw or rejection produces `null` at that position, just like an explicit `null`
8
- * result. Other falsy values are preserved. Handle errors inside a callback to retain the original
9
- * cause. The caller owns concurrency limits, cancellation, retries and resource cleanup, and each
10
- * callback should return the work the batch needs to await.
11
- *
12
- * The function snapshots the task array and rejects with `TypeError` for a non-array argument
13
- * or a non-function entry before invoking any callback.
14
- */
1
+ /** Await every callback and preserve input positions, using null for failed tasks. */
15
2
  export async function parallel<const Tasks extends readonly (() => unknown)[]>(
16
3
  tasks: Tasks,
17
- ): Promise<ParallelResults<Tasks>> {
4
+ ): Promise<{ -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null }> {
18
5
  if (!Array.isArray(tasks)) throw new TypeError('parallel expects an array of functions')
19
6
  const callbacks = [...tasks]
20
- for (const callback of callbacks) {
21
- if (typeof callback !== 'function') {
22
- throw new TypeError('parallel expects functions, not promises; wrap each call in () => task()')
23
- }
7
+ for (const task of callbacks) {
8
+ if (typeof task !== 'function') throw new TypeError('parallel expects functions, not promises; wrap each call in () => task()')
24
9
  }
25
10
  // An async wrapper captures synchronous throws without skipping later callbacks.
26
- const settledCallbacks = await Promise.allSettled(callbacks.map(async callback => callback()))
27
- return settledCallbacks.map(result => result.status === 'fulfilled' ? result.value : null) as ParallelResults<Tasks>
28
- }
29
-
30
- /** Preserve each callback's awaited type and allow a failed callback to yield null in any slot. */
31
- type ParallelResults<Tasks extends readonly (() => unknown)[]> = {
32
- -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null
11
+ const results = await Promise.allSettled(callbacks.map(async task => task()))
12
+ return results.map(result => result.status === 'fulfilled' ? result.value : null) as {
13
+ -readonly [K in keyof Tasks]: Awaited<ReturnType<Tasks[K]>> | null
14
+ }
33
15
  }
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { open, rename, unlink } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+ import { canonicalJson } from './json'
5
+
6
+ /** Windows supports file flushes, but Node does not provide directory fsync there. */
7
+ export async function syncDirectory(path: string): Promise<void> {
8
+ if (process.platform === 'win32') return
9
+ const directory = await open(path, 'r')
10
+ try { await directory.sync() } finally { await directory.close() }
11
+ }
12
+
13
+ export async function atomicPublish(path: string, value: unknown): Promise<void> {
14
+ const text = `${canonicalJson(value)}\n`
15
+ const temporary = `${path}.${randomUUID()}.tmp`
16
+ let temporaryExists = false
17
+ try {
18
+ const file = await open(temporary, 'wx', 0o600)
19
+ temporaryExists = true
20
+ try { await file.writeFile(text, 'utf8'); await file.sync() }
21
+ finally { await file.close() }
22
+ await rename(temporary, path)
23
+ temporaryExists = false
24
+ await syncDirectory(dirname(path))
25
+ } catch (cause) {
26
+ if (temporaryExists) {
27
+ try { await unlink(temporary) }
28
+ catch (cleanup) { throw new AggregateError([cause, cleanup], 'Atomic publish failed') }
29
+ }
30
+ throw cause
31
+ }
32
+ }
@@ -1,29 +1,63 @@
1
- import { createHash } from 'node:crypto'
2
- import { atomicPublish, storageError } from './checkpoint-files'
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { z } from 'zod'
3
+ import { HarnessSdkError } from '@anureo/sdk'
4
+ import { atomicPublish } from './atomic'
3
5
  import { canonicalJson, jsonCopy, type JsonValue } from './json'
4
- import type { JournalEvent } from './records'
6
+ import { journalEventSchema } from './records'
7
+
8
+ export type JournalEvent = z.output<typeof journalEventSchema>
9
+
10
+ export interface PriorFailure {
11
+ code: string
12
+ outcomeUnknown: boolean
13
+ }
14
+
15
+ /** Last result wins per key; started without terminal marks a respawnable call. */
16
+ export interface JournalIndex {
17
+ results: Map<string, JsonValue>
18
+ started: Set<string>
19
+ failures: Map<string, PriorFailure>
20
+ inputHookRevisions: Map<string, string | undefined>
21
+ }
22
+
23
+ export function indexJournal(events: readonly JournalEvent[]): JournalIndex {
24
+ const index: JournalIndex = { results: new Map(), started: new Set(), failures: new Map(), inputHookRevisions: new Map() }
25
+ for (const event of events) {
26
+ index.started.delete(event.key)
27
+ index.failures.delete(event.key)
28
+ index.results.delete(event.key)
29
+ if (event.type === 'started') {
30
+ index.started.add(event.key)
31
+ index.inputHookRevisions.set(event.key, event.inputHookRevision)
32
+ }
33
+ else if (event.type === 'failed') index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown })
34
+ else index.results.set(event.key, event.result)
35
+ }
36
+ return index
37
+ }
5
38
 
6
39
  /**
7
- * Internal agent-call journal created by publishInitialRun for a new run and exposed
8
- * by workflow through the ambient run context.
9
- * memoizedAgent reserves keys in invocation order and checks replay. On a miss,
10
- * executeJournaledAgent awaits markers before dispatch and settlement. Each key hashes its
11
- * predecessor, prompt and semantic options, so upstream changes invalidate later call identities.
12
- * workflow drains registered agent work before final publication and releases the writer
13
- * lock through the run handle.
40
+ * Appended agent-call journal. Cache identity is a chain: each call's key hashes
41
+ * the previous key, the prompt, and the canonical semantic options, so any
42
+ * upstream change invalidates the whole downstream prefix automatically.
14
43
  */
15
44
  export class AgentJournal {
16
- /** Copy validated source events into a new run's journal; construction performs no file I/O. */
45
+ private readonly events: JournalEvent[] = []
46
+ private readonly index: JournalIndex
47
+ private previousKey = ''
48
+ private reuseOpen = true
49
+ private publishQueue: Promise<void> = Promise.resolve()
50
+
17
51
  constructor(
18
52
  private readonly path: string,
19
53
  source: readonly JournalEvent[],
54
+ /** Memory-only journals keep their event/index state but never touch the filesystem. */
55
+ private readonly persist = true,
20
56
  ) {
21
57
  this.events.push(...jsonCopy(source))
22
58
  this.index = indexJournal(this.events)
23
59
  }
24
60
 
25
- /** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
26
- * Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
27
61
  nextKey(prompt: string, canonicalOptions: JsonValue): string {
28
62
  const key = `v1:${createHash('sha256')
29
63
  .update(this.previousKey).update('\0')
@@ -33,79 +67,54 @@ export class AgentJournal {
33
67
  return key
34
68
  }
35
69
 
36
- /** Decide how memoizedAgent should handle the reserved key. A replay carries an isolated
37
- * result for the caller to validate. A miss closes result reuse unless the source left this
38
- * key at started. Even after reuse closes, an exact-key failure with an unknown outcome
39
- * requires reconciliation before memoizedAgent can dispatch. */
40
- resolveCall(key: string): JournalDecision {
41
- if (this.reuseOpen) {
42
- const result = this.index.results.get(key)
43
- if (result !== undefined) return { action: 'replay', result: jsonCopy(result) }
70
+ /** Check the source of a matching logical call before cache lookup or execution. */
71
+ resumeConflict(key: string, inputHookRevision: string | undefined): HarnessSdkError | undefined {
72
+ if (this.index.failures.get(key)?.outcomeUnknown) {
73
+ return new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
74
+ 'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
75
+ }
76
+ if (this.index.inputHookRevisions.has(key) && this.index.inputHookRevisions.get(key) !== inputHookRevision) {
77
+ return new HarnessSdkError('WORKFLOW_INPUT_POLICY_CHANGED')
44
78
  }
45
- if (!this.index.started.has(key)) this.reuseOpen = false
46
- return this.index.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
47
79
  }
48
80
 
49
- /** Queue a copied event and await serialized atomic publication before indexing terminal data.
50
- * executeJournaledAgent awaits started before dispatch and terminals before settlement. Keep the
51
- * event unchanged until settlement and its result payload immutable while the lookup retains it.
52
- * On publication failure the event stays in the in-memory snapshot. Non-SDK I/O failures
53
- * reject as WORKFLOW_STORAGE_FAILED, which RunState records to stop later dispatch. */
54
- async append(event: JournalEvent): Promise<void> {
55
- this.events.push(jsonCopy(event))
56
- // Concurrent callers must not race atomic renames: an earlier snapshot
57
- // landing last would silently drop later events from the published file.
58
- const publish = this.publishQueue.catch(() => {}).then(async () => {
59
- try {
60
- await atomicPublish(this.path, this.events)
61
- } catch (cause) {
62
- throw storageError(cause)
63
- }
64
- })
65
- this.publishQueue = publish
66
- await publish
67
- if (event.type !== 'started') indexTerminalEvent(this.index, event)
81
+ /** Returns a copy of the cached result, or undefined when this call must execute. */
82
+ resultFor(key: string): JsonValue | undefined {
83
+ if (!this.reuseOpen) return undefined
84
+ const result = this.index.results.get(key)
85
+ return result === undefined ? undefined : jsonCopy(result)
68
86
  }
69
87
 
70
- private readonly events: JournalEvent[] = []
71
- private readonly index: JournalIndex
72
- private previousKey = ''
73
- private reuseOpen = true
74
- private publishQueue: Promise<void> = Promise.resolve()
75
- }
76
-
77
- /** Result handling stays with memoizedAgent, which owns validation, dispatch and rejection. */
78
- type JournalDecision = { action: 'replay'; result: JsonValue } | { action: 'execute' | 'reconcile' }
79
-
80
- /** Replay lookup built from validated events. A key left at started can be respawned. */
81
- interface JournalIndex {
82
- results: Map<string, JsonValue>
83
- started: Set<string>
84
- uncertain: Set<string>
85
- }
88
+ /**
89
+ * Marks a cache miss. A source entry with only `started` (crash during a call)
90
+ * is a respawnable prefix: it stays reuse-eligible for later calls, matching
91
+ * the "longest unchanged prefix" semantics.
92
+ */
93
+ beginExecution(key: string): void {
94
+ if (!this.index.started.has(key)) this.reuseOpen = false
95
+ }
86
96
 
87
- /** Fold validated events in file order. Clear the earlier entry for each key so a newer
88
- * start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
89
- function indexJournal(events: readonly JournalEvent[]): JournalIndex {
90
- const index: JournalIndex = { results: new Map(), started: new Set(), uncertain: new Set() }
91
- for (const event of events) {
92
- index.started.delete(event.key)
93
- index.uncertain.delete(event.key)
94
- index.results.delete(event.key)
95
- if (event.type === 'started') index.started.add(event.key)
96
- else indexTerminalEvent(index, event)
97
+ async append(event: JournalEvent): Promise<void> {
98
+ this.events.push(jsonCopy(event))
99
+ if (this.persist) {
100
+ // Concurrent callers must not race atomic renames: an earlier snapshot
101
+ // landing last would silently drop later events from the published file.
102
+ const publish = this.publishQueue.catch(() => {}).then(async () => {
103
+ try { await atomicPublish(this.path, this.events) }
104
+ catch (cause) {
105
+ if (cause instanceof HarnessSdkError) throw cause
106
+ throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
107
+ }
108
+ })
109
+ this.publishQueue = publish
110
+ await publish
111
+ }
112
+ if (event.type === 'started') this.index.inputHookRevisions.set(event.key, event.inputHookRevision)
113
+ else if (event.type === 'result') this.index.results.set(event.key, event.result)
114
+ else if (event.type === 'failed') this.index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown })
97
115
  }
98
- return index
99
116
  }
100
117
 
101
- /** Populate the terminal lookup. The replay fold clears superseded entries before calling
102
- * this helper. Live append retains the source prefix markers for miss handling. */
103
- function indexTerminalEvent(index: JournalIndex, event: Exclude<JournalEvent, { type: 'started' }>): void {
104
- if (event.type === 'result') {
105
- index.results.set(event.key, event.result)
106
- } else if (event.outcomeUnknown) {
107
- index.uncertain.add(event.key)
108
- } else {
109
- index.uncertain.delete(event.key)
110
- }
118
+ export function newAgentId(): string {
119
+ return randomUUID()
111
120
  }