@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.
@@ -1,27 +1,49 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { HarnessSdkError } from '@anureo/sdk'
3
3
 
4
- /** Workflow JSON data shape. The encoder also checks runtime properties and rejects cycles. */
5
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
6
5
  [key: string]: JsonValue
7
6
  }
8
7
 
9
- /** Encode strict JSON with sorted object keys for persistence and cache identity.
10
- * Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
11
- * arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
12
- * Shared acyclic references encode by value. Encoding never calls toJSON. */
13
8
  export function canonicalJson(value: unknown): string {
14
- return encodeJson(value, new Set())
9
+ const ancestors = new Set<object>()
10
+ const invalid = (): never => { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE') }
11
+ function encode(item: unknown): string {
12
+ if (item === null) return 'null'
13
+ if (typeof item === 'string' || typeof item === 'boolean') return JSON.stringify(item)
14
+ if (typeof item === 'number') return Number.isFinite(item) ? JSON.stringify(item) : invalid()
15
+ if (typeof item !== 'object' || ancestors.has(item)) return invalid()
16
+ if (Reflect.ownKeys(item).some(key => typeof key !== 'string')) return invalid()
17
+ const descriptors = Object.getOwnPropertyDescriptors(item)
18
+ const keys = Object.keys(descriptors)
19
+ ancestors.add(item)
20
+ try {
21
+ if (Array.isArray(item)) {
22
+ if (keys.length !== item.length + 1) return invalid()
23
+ const values: string[] = []
24
+ for (let i = 0; i < item.length; i++) {
25
+ const field = descriptors[String(i)]
26
+ if (!field || !field.enumerable || !('value' in field)) return invalid()
27
+ values.push(encode(field.value))
28
+ }
29
+ return `[${values.join(',')}]`
30
+ }
31
+ const prototype = Object.getPrototypeOf(item)
32
+ if (prototype !== Object.prototype && prototype !== null) return invalid()
33
+ return `{${keys.sort().map(key => {
34
+ const field = descriptors[key]!
35
+ if (!field.enumerable || !('value' in field)) return invalid()
36
+ return `${JSON.stringify(key)}:${encode(field.value)}`
37
+ }).join(',')}}`
38
+ } finally { ancestors.delete(item) }
39
+ }
40
+ return encode(value)
15
41
  }
16
42
 
17
- /** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
18
- * Shared references are copied by value. */
19
43
  export function jsonCopy<T>(value: T): T {
20
44
  return JSON.parse(canonicalJson(value)) as T
21
45
  }
22
46
 
23
- /** Deeply freeze an already validated, acyclic JSON value in place and return it.
24
- * prepareRun passes an owned copy for workflow to expose to the body. */
25
47
  export function freezeJson<T>(value: T): T {
26
48
  if (value && typeof value === 'object') {
27
49
  for (const child of Object.values(value)) freezeJson(child)
@@ -30,54 +52,6 @@ export function freezeJson<T>(value: T): T {
30
52
  return value
31
53
  }
32
54
 
33
- /** Hash canonical JSON as lowercase SHA-256 hex. record and verifyRecord agree on this encoding
34
- * for record payloads, and FileRunHandle.finish and loadSourceJournal use it for result.json.
35
- * Unsupported values throw as in canonicalJson. */
36
55
  export function digest(value: unknown): string {
37
56
  return createHash('sha256').update(canonicalJson(value)).digest('hex')
38
57
  }
39
-
40
- /** Track only the current ancestry so repeated references encode normally while cycles reject. */
41
- function encodeJson(item: unknown, ancestors: Set<object>): string {
42
- if (item === null) return 'null'
43
- if (typeof item === 'string' || typeof item === 'boolean') return JSON.stringify(item)
44
- if (typeof item === 'number') return Number.isFinite(item) ? JSON.stringify(item) : invalidJson()
45
- if (typeof item !== 'object' || ancestors.has(item)) return invalidJson()
46
- if (Reflect.ownKeys(item).some(key => typeof key !== 'string')) return invalidJson()
47
- const descriptors = Object.getOwnPropertyDescriptors(item)
48
- ancestors.add(item)
49
- try {
50
- return Array.isArray(item)
51
- ? encodeArray(item, descriptors, ancestors)
52
- : encodeObject(item, descriptors, ancestors)
53
- } finally {
54
- ancestors.delete(item)
55
- }
56
- }
57
-
58
- /** Dense array slots must be the only own properties besides length to avoid silent data loss. */
59
- function encodeArray(item: unknown[], descriptors: Record<string, PropertyDescriptor>, ancestors: Set<object>): string {
60
- if (Object.keys(descriptors).length !== item.length + 1) return invalidJson()
61
- const values: string[] = []
62
- for (let i = 0; i < item.length; i++) {
63
- values.push(encodeDataProperty(descriptors[String(i)], ancestors))
64
- }
65
- return `[${values.join(',')}]`
66
- }
67
-
68
- /** Restrict objects to plain data and sort their keys so insertion order cannot change identity. */
69
- function encodeObject(item: object, descriptors: Record<string, PropertyDescriptor>, ancestors: Set<object>): string {
70
- const prototype = Object.getPrototypeOf(item)
71
- if (prototype !== Object.prototype && prototype !== null) return invalidJson()
72
- return `{${Object.keys(descriptors).sort().map(key =>
73
- `${JSON.stringify(key)}:${encodeDataProperty(descriptors[key], ancestors)}`
74
- ).join(',')}}`
75
- }
76
-
77
- /** Inspect descriptors instead of reading properties so getters never supply persisted data. */
78
- function encodeDataProperty(field: PropertyDescriptor | undefined, ancestors: Set<object>): string {
79
- if (!field || !field.enumerable || !('value' in field)) return invalidJson()
80
- return encodeJson(field.value, ancestors)
81
- }
82
-
83
- function invalidJson(): never { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE') }
@@ -1,97 +1,77 @@
1
+ import { constants } from 'node:fs'
2
+ import { open, lstat } from 'node:fs/promises'
1
3
  import { z } from 'zod'
2
4
  import { HarnessSdkError } from '@anureo/sdk'
3
- import { digest, type JsonValue } from './json'
5
+ import { canonicalJson, digest, type JsonValue } from './json'
4
6
 
5
- /** Validated manifest shape; its digest and referenced result still require separate verification. */
6
- export type Manifest = z.output<typeof manifestSchema>
7
-
8
- /** Persist only failure classification from workflow aborts, without diagnostic text. */
9
- export type StoredFailure = z.output<typeof failureSchema>
10
-
11
- /** Internal validated event persisted before dispatch or before exposing an agent outcome. */
12
- export type JournalEvent = z.output<typeof journalEventSchema>
13
-
14
- /** Reject unusable recovery material without treating corruption as an empty cache. */
15
- export function invalidCheckpoint(): never { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID') }
16
-
17
- /** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
18
- * recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
19
- export function record<T extends object>(value: T): T & { recordDigest: string } {
20
- return { ...value, recordDigest: digest(value) }
21
- }
22
-
23
- /** Return parsed lock or manifest data after verifying the payload digest. A schema
24
- * mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
25
- * yield strict JSON with a recordDigest field. */
26
- export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
27
- const parsed = schema.safeParse(value)
28
- if (!parsed.success) return invalidCheckpoint()
29
- const { recordDigest, ...payload } = parsed.data as Record<string, unknown>
30
- if (digest(payload) !== recordDigest) return invalidCheckpoint()
31
- return parsed.data
32
- }
33
-
34
- /** File names and version used by the target writer and the compatible-source reader. */
35
- export const checkpointFormat = {
36
- version: 2,
37
- lock: 'writer.lock',
38
- manifest: 'run.json',
39
- journal: 'journal.json',
40
- result: 'result.json',
41
- } as const
42
-
43
- /** Check target and source basenames before joining paths. Reject blanks, separators,
44
- * control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
45
- * support caller-assigned CLI basenames. */
7
+ // Caller-assigned IDs also support existing CLI output basenames (including Unicode/spaces).
46
8
  export const runIdSchema = z.string().min(1).refine(value => value !== '.' && value !== '..'
47
9
  && value.trim().length > 0 && !/[\\/\x00-\x1f\x7f]/.test(value) && Buffer.byteLength(value) <= 255)
48
-
49
- // The exported record schemas evaluate their component schemas during initialization.
50
- /** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
51
- const uuidSchema = z.string().uuid()
10
+ export const uuidSchema = z.string().uuid()
52
11
  const hashSchema = z.string().regex(/^[a-f0-9]{64}$/)
53
-
54
- /** Format-v2 writer claim. Replay checks host/PID liveness. Release checks the held inode. */
55
- export const lockSchema = z.strictObject({
56
- checkpointFormatVersion: z.literal(checkpointFormat.version), token: uuidSchema, hostname: z.string(),
57
- pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
58
- })
59
-
60
- /** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
61
- const failureSchema = z.strictObject({
62
- code: z.string(),
63
- retryable: z.boolean(),
64
- /** The failure left execution's outcome uncertain. */
65
- outcomeUnknown: z.boolean(),
66
- /** Resource release failed even if execution itself had a known outcome. */
67
- cleanupFailed: z.boolean(),
68
- })
69
-
70
12
  const jsonSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([
71
13
  z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
72
14
  ]))
15
+ export const failureSchema = z.strictObject({
16
+ code: z.string(), retryable: z.boolean(), outcomeUnknown: z.boolean(), cleanupFailed: z.boolean(),
17
+ })
73
18
  const identitySchema = z.strictObject({
74
19
  runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
75
20
  })
76
-
77
- /** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
78
- * and checks resultDigest against result.json for completed and incomplete runs. */
79
21
  export const manifestSchema = z.strictObject({
80
- checkpointFormatVersion: z.literal(checkpointFormat.version),
22
+ checkpointFormatVersion: z.literal(2),
81
23
  identity: identitySchema, createdAt: z.string().datetime(),
82
24
  resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
83
25
  status: z.enum(['running', 'completed', 'incomplete', 'failed']),
84
26
  resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
85
27
  })
86
-
87
- /** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
88
- const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/)
89
-
90
- /** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
91
- * The chained key determines reuse. The execution UUID is recorded as agentId. */
28
+ export const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/)
92
29
  export const journalEventSchema = z.discriminatedUnion('type', [
93
- z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema }),
30
+ z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema,
31
+ inputHookRevision: z.string().refine(value => value.trim().length > 0).optional() }),
94
32
  z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
95
33
  z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
96
34
  code: z.string().min(1), outcomeUnknown: z.boolean() }),
97
35
  ])
36
+ export const lockSchema = z.strictObject({
37
+ checkpointFormatVersion: z.literal(2), token: uuidSchema, hostname: z.string(),
38
+ pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
39
+ })
40
+ export type Manifest = z.output<typeof manifestSchema>
41
+
42
+ export function invalidCheckpoint(): never { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID') }
43
+
44
+ export function record<T extends object>(value: T): T & { recordDigest: string } {
45
+ return { ...value, recordDigest: digest(value) }
46
+ }
47
+
48
+ export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
49
+ const parsed = schema.safeParse(value)
50
+ if (!parsed.success) return invalidCheckpoint()
51
+ const { recordDigest, ...payload } = parsed.data as Record<string, unknown>
52
+ if (digest(payload) !== recordDigest) return invalidCheckpoint()
53
+ return parsed.data
54
+ }
55
+
56
+ /** Only ENOENT represents missing data; links, bad JSON and bad schemas are never cache misses. */
57
+ export async function readJson(path: string): Promise<JsonValue> {
58
+ const before = await lstat(path)
59
+ if (!before.isFile()) return invalidCheckpoint()
60
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
61
+ try {
62
+ const current = await file.stat()
63
+ if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
64
+ const text = await file.readFile('utf8')
65
+ let value: unknown
66
+ try { value = JSON.parse(text); canonicalJson(value) } catch { return invalidCheckpoint() }
67
+ return value as JsonValue
68
+ } finally { await file.close() }
69
+ }
70
+
71
+ export async function regularDirectory(path: string): Promise<void> {
72
+ if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
73
+ }
74
+
75
+ export function missing(cause: unknown): boolean {
76
+ return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
77
+ }
@@ -1,49 +1,11 @@
1
- import { lstat } from 'node:fs/promises'
1
+ import { HarnessSdkError } from '@anureo/sdk'
2
2
  import { hostname } from 'node:os'
3
3
  import { join } from 'node:path'
4
- import { HarnessSdkError } from '@anureo/sdk'
5
- import { readJson } from './checkpoint-files'
6
4
  import { digest } from './json'
7
- import {
8
- checkpointFormat, invalidCheckpoint, journalEventSchema, lockSchema, manifestSchema, verifyRecord,
9
- type JournalEvent, type Manifest,
10
- } from './records'
5
+ import { journalEventSchema, lockSchema, manifestSchema, invalidCheckpoint, missing,
6
+ readJson, regularDirectory, verifyRecord, type Manifest } from './records'
7
+ import type { JournalEvent } from './journal'
11
8
 
12
- /** Load an inactive source run's validated events without modifying its files.
13
- * publishInitialRun calls this while holding the target lock, then copies the events
14
- * into the new journal. A mismatched run ID or invalid required record rejects as
15
- * WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
16
- * A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
17
- * Completed and incomplete sources must have a result matching the manifest digest.
18
- * Other filesystem errors propagate for storage error normalization.
19
- * The caller supplies a separate target directory. This check acquires no source lock. */
20
- export async function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]> {
21
- await regularDirectory(directory)
22
- await assertInactive(directory)
23
- const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, checkpointFormat.manifest)))
24
- assertCompatibleIdentity(manifest.identity, identity)
25
- const raw = await requiredJson(join(directory, checkpointFormat.journal))
26
- const parsed = journalEventSchema.array().safeParse(raw)
27
- if (!parsed.success) invalidCheckpoint()
28
- if (manifest.status === 'completed' || manifest.status === 'incomplete') {
29
- if (digest(await requiredJson(join(directory, checkpointFormat.result))) !== manifest.resultDigest) invalidCheckpoint()
30
- }
31
- return parsed.data
32
- }
33
-
34
- type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>
35
-
36
- /** Check that the manifest belongs to the selected run before checking workflow compatibility.
37
- * A misplaced manifest is checkpoint corruption even if its workflow name or revision differs. */
38
- function assertCompatibleIdentity(actual: SourceIdentity, expected: SourceIdentity): void {
39
- if (actual.runId !== expected.runId) invalidCheckpoint()
40
- if (actual.name !== expected.name || actual.revision !== expected.revision) {
41
- throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN')
42
- }
43
- }
44
-
45
- /** Map missing required files and symlink races reported as ELOOP to invalid checkpoints.
46
- * Other failures reach openFileRun for storage error normalization. */
47
9
  async function requiredJson(path: string) {
48
10
  try { return await readJson(path) }
49
11
  catch (cause) {
@@ -52,40 +14,36 @@ async function requiredJson(path: string) {
52
14
  }
53
15
  }
54
16
 
55
- /** Permit an absent writer lock or a validated local claim whose PID no longer exists.
56
- * An invalid lock rejects through verifyRecord. A valid lock that fails the liveness
57
- * check blocks loadSourceJournal before it reads the manifest. */
58
17
  async function assertInactive(directory: string): Promise<void> {
59
18
  let lock
60
- try {
61
- lock = verifyRecord(lockSchema, await readJson(join(directory, checkpointFormat.lock)))
62
- } catch (cause) {
63
- if (missing(cause)) return
64
- throw cause
19
+ try { lock = verifyRecord(lockSchema, await readJson(join(directory, 'writer.lock'))) }
20
+ catch (cause) { if (missing(cause)) return; throw cause }
21
+ if (lock.hostname === hostname()) {
22
+ try { process.kill(lock.pid, 0) }
23
+ catch (cause) { if ((cause as NodeJS.ErrnoException).code === 'ESRCH') return }
65
24
  }
66
- if (!localWriterExited(lock)) throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
25
+ // A reused PID is conservatively considered active. Never infer backend termination.
26
+ throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
67
27
  }
68
28
 
69
- /** Only a local PID probe returning ESRCH proves the recorded process is gone.
70
- * A foreign host, live or reused PID, or refused probe leaves inactivity unproven.
71
- * This evidence is limited to the writer process and cannot confirm backend termination. */
72
- function localWriterExited(lock: { hostname: string; pid: number }): boolean {
73
- if (lock.hostname !== hostname()) return false
74
- try {
75
- process.kill(lock.pid, 0)
76
- return false
77
- } catch (cause) {
78
- return (cause as NodeJS.ErrnoException).code === 'ESRCH'
29
+ /** Loads a finished or crashed source run's journal for cache replay. */
30
+ export async function loadSourceJournal(
31
+ directory: string,
32
+ identity: { name: string; revision: string; runId: string },
33
+ ): Promise<JournalEvent[]> {
34
+ await regularDirectory(directory)
35
+ await assertInactive(directory)
36
+ // A format-v1 (explicit step) run directory fails manifest validation here.
37
+ const manifest: Manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, 'run.json')))
38
+ if (manifest.identity.runId !== identity.runId) invalidCheckpoint()
39
+ if (manifest.identity.name !== identity.name || manifest.identity.revision !== identity.revision) {
40
+ throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN')
79
41
  }
80
- }
81
-
82
- /** Reject a symlink or other non-directory source before loadSourceJournal reads its lock.
83
- * Filesystem errors propagate to openFileRun for normalization. */
84
- async function regularDirectory(path: string): Promise<void> {
85
- if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
86
- }
87
-
88
- /** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
89
- function missing(cause: unknown): boolean {
90
- return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
42
+ const raw = await requiredJson(join(directory, 'journal.json'))
43
+ const parsed = journalEventSchema.array().safeParse(raw)
44
+ if (!parsed.success) invalidCheckpoint()
45
+ if (manifest.status === 'completed' || manifest.status === 'incomplete') {
46
+ if (digest(await requiredJson(join(directory, 'result.json'))) !== manifest.resultDigest) invalidCheckpoint()
47
+ }
48
+ return parsed.data
91
49
  }