@danypops/vehicle-core 0.17.0 → 0.18.0

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.
Files changed (125) hide show
  1. package/README.md +12 -0
  2. package/dist/{vehicle-approvals.d.ts → approvals/approval.d.ts} +4 -11
  3. package/dist/{vehicle-approvals.js → approvals/approval.js} +33 -23
  4. package/dist/approvals/index.d.ts +1 -0
  5. package/dist/approvals/index.js +1 -0
  6. package/dist/client/client.d.ts +29 -0
  7. package/dist/client/client.js +1 -0
  8. package/dist/client/index.d.ts +1 -0
  9. package/dist/client/index.js +1 -0
  10. package/dist/content/content.d.ts +32 -0
  11. package/dist/content/content.js +25 -0
  12. package/dist/content/index.d.ts +1 -0
  13. package/dist/content/index.js +1 -0
  14. package/dist/{vehicle-errors.d.ts → errors/error.d.ts} +10 -9
  15. package/dist/errors/index.d.ts +1 -0
  16. package/dist/errors/index.js +1 -0
  17. package/dist/events/event.d.ts +42 -0
  18. package/dist/events/event.js +35 -0
  19. package/dist/events/index.d.ts +1 -0
  20. package/dist/events/index.js +1 -0
  21. package/dist/idempotency/index.d.ts +1 -0
  22. package/dist/idempotency/index.js +1 -0
  23. package/dist/{vehicle-idempotency.d.ts → idempotency/receipt.d.ts} +1 -1
  24. package/dist/index.d.ts +26 -8
  25. package/dist/index.js +26 -8
  26. package/dist/jobs/grant.d.ts +36 -0
  27. package/dist/jobs/grant.js +31 -0
  28. package/dist/jobs/identity.d.ts +11 -0
  29. package/dist/jobs/identity.js +13 -0
  30. package/dist/jobs/index.d.ts +8 -0
  31. package/dist/jobs/index.js +8 -0
  32. package/dist/jobs/replay.d.ts +8 -0
  33. package/dist/jobs/replay.js +9 -0
  34. package/dist/jobs/retention.d.ts +26 -0
  35. package/dist/jobs/retention.js +39 -0
  36. package/dist/jobs/steer.d.ts +23 -0
  37. package/dist/jobs/steer.js +41 -0
  38. package/dist/jobs/termination.d.ts +5 -0
  39. package/dist/jobs/termination.js +11 -0
  40. package/dist/jobs/wake-log.d.ts +39 -0
  41. package/dist/jobs/wake-log.js +65 -0
  42. package/dist/jobs/wire.d.ts +47 -0
  43. package/dist/jobs/wire.js +1 -0
  44. package/dist/manifest/index.d.ts +1 -0
  45. package/dist/manifest/index.js +1 -0
  46. package/dist/manifest/manifest.d.ts +49 -0
  47. package/dist/manifest/manifest.js +1 -0
  48. package/dist/operations/context.d.ts +52 -0
  49. package/dist/operations/context.js +1 -0
  50. package/dist/operations/effect.d.ts +3 -0
  51. package/dist/operations/effect.js +2 -0
  52. package/dist/operations/index.d.ts +3 -0
  53. package/dist/operations/index.js +3 -0
  54. package/dist/operations/operation.d.ts +98 -0
  55. package/dist/operations/operation.js +79 -0
  56. package/dist/{atomic-json.d.ts → persistence/atomic-json.d.ts} +1 -2
  57. package/dist/{atomic-json.js → persistence/atomic-json.js} +1 -2
  58. package/dist/persistence/index.d.ts +1 -0
  59. package/dist/persistence/index.js +1 -0
  60. package/dist/schedules/index.d.ts +1 -0
  61. package/dist/schedules/index.js +1 -0
  62. package/dist/{vehicle-scheduler.d.ts → schedules/schedule.d.ts} +6 -8
  63. package/dist/schemas/codec.d.ts +25 -0
  64. package/dist/schemas/codec.js +7 -0
  65. package/dist/schemas/index.d.ts +4 -0
  66. package/dist/schemas/index.js +4 -0
  67. package/dist/schemas/json.d.ts +7 -0
  68. package/dist/schemas/json.js +14 -0
  69. package/dist/schemas/loose-object.d.ts +20 -0
  70. package/dist/schemas/loose-object.js +73 -0
  71. package/dist/schemas/presentation.d.ts +11 -0
  72. package/dist/schemas/presentation.js +22 -0
  73. package/dist/watches/index.d.ts +1 -0
  74. package/dist/watches/index.js +1 -0
  75. package/dist/{vehicle-watchers.d.ts → watches/registry.d.ts} +2 -9
  76. package/dist/{vehicle-watchers.js → watches/registry.js} +2 -9
  77. package/package.json +5 -1
  78. package/src/{vehicle-approvals.ts → approvals/approval.ts} +27 -24
  79. package/src/approvals/index.ts +1 -0
  80. package/src/client/client.ts +31 -0
  81. package/src/client/index.ts +1 -0
  82. package/src/content/content.ts +46 -0
  83. package/src/content/index.ts +1 -0
  84. package/src/{vehicle-errors.ts → errors/error.ts} +10 -9
  85. package/src/errors/index.ts +1 -0
  86. package/src/events/event.ts +72 -0
  87. package/src/events/index.ts +1 -0
  88. package/src/idempotency/index.ts +1 -0
  89. package/src/{vehicle-idempotency.ts → idempotency/receipt.ts} +1 -1
  90. package/src/index.ts +26 -8
  91. package/src/jobs/grant.ts +53 -0
  92. package/src/jobs/identity.ts +13 -0
  93. package/src/jobs/index.ts +8 -0
  94. package/src/jobs/replay.ts +17 -0
  95. package/src/jobs/retention.ts +59 -0
  96. package/src/jobs/steer.ts +49 -0
  97. package/src/jobs/termination.ts +13 -0
  98. package/src/jobs/wake-log.ts +98 -0
  99. package/src/jobs/wire.ts +51 -0
  100. package/src/manifest/index.ts +1 -0
  101. package/src/manifest/manifest.ts +52 -0
  102. package/src/operations/context.ts +56 -0
  103. package/src/operations/effect.ts +3 -0
  104. package/src/operations/index.ts +3 -0
  105. package/src/operations/operation.ts +184 -0
  106. package/src/{atomic-json.ts → persistence/atomic-json.ts} +1 -2
  107. package/src/persistence/index.ts +1 -0
  108. package/src/schedules/index.ts +1 -0
  109. package/src/{vehicle-scheduler.ts → schedules/schedule.ts} +6 -8
  110. package/src/schemas/codec.ts +30 -0
  111. package/src/schemas/index.ts +4 -0
  112. package/src/schemas/json.ts +17 -0
  113. package/src/schemas/loose-object.ts +82 -0
  114. package/src/schemas/presentation.ts +28 -0
  115. package/src/watches/index.ts +1 -0
  116. package/src/{vehicle-watchers.ts → watches/registry.ts} +2 -9
  117. package/dist/vehicle-contract.d.ts +0 -353
  118. package/dist/vehicle-contract.js +0 -253
  119. package/dist/vehicle-jobs.d.ts +0 -159
  120. package/dist/vehicle-jobs.js +0 -182
  121. package/src/vehicle-contract.ts +0 -597
  122. package/src/vehicle-jobs.ts +0 -305
  123. /package/dist/{vehicle-errors.js → errors/error.js} +0 -0
  124. /package/dist/{vehicle-idempotency.js → idempotency/receipt.js} +0 -0
  125. /package/dist/{vehicle-scheduler.js → schedules/schedule.js} +0 -0
@@ -1,305 +0,0 @@
1
- /** Pure pieces of Vehicle Jobs: a termination-reason resolver and a bounded wake-log accumulator. Orchestration lives in vehicle-server's VehicleJobStore. */
2
-
3
- import type { VehiclePrincipal } from "./vehicle-contract.js";
4
- import type { VehicleFailure } from "./vehicle-errors.js";
5
-
6
- export type VehicleJobStatus = "running" | "succeeded" | "failed" | "canceled";
7
-
8
- /** Highest precedence first -- an explicit cancel always wins even if the handler also settled around the same time. "orphaned" is a restart-reconciliation outcome: a job that was still "running" when its process died, so nothing ever really failed or succeeded -- the record's own status just goes stale. */
9
- export const VEHICLE_JOB_TERMINATION_PRECEDENCE = ["canceled", "timeout", "orphaned", "failed", "succeeded"] as const;
10
- export type VehicleJobTerminationReason = (typeof VEHICLE_JOB_TERMINATION_PRECEDENCE)[number];
11
-
12
- export function resolveVehicleJobTerminationReason(candidates: readonly VehicleJobTerminationReason[]): VehicleJobTerminationReason {
13
- if (candidates.length === 0) throw new Error("resolveVehicleJobTerminationReason requires at least one candidate");
14
- for (const reason of VEHICLE_JOB_TERMINATION_PRECEDENCE) {
15
- if (candidates.includes(reason)) return reason;
16
- }
17
- throw new Error(`Unrecognized Vehicle job termination candidate(s): ${candidates.join(", ")}`);
18
- }
19
-
20
- /** "always" keeps every notification; "transition" drops one identical to the last (hash dedup); "first-only" keeps just the first. */
21
- export type VehicleJobNotifyMode = "always" | "transition" | "first-only";
22
-
23
- export interface VehicleJobWakeBudget {
24
- readonly maxCount: number;
25
- readonly maxBytes: number;
26
- }
27
-
28
- export type VehicleJobWakeDropReason =
29
- | "count-budget-exhausted"
30
- | "byte-budget-exhausted"
31
- | "deduplicated-transition"
32
- | "superseded-by-first-only";
33
-
34
- export interface VehicleJobWakeEntry {
35
- readonly seq: number;
36
- readonly at: number;
37
- readonly progress: unknown;
38
- }
39
-
40
- export interface VehicleJobWakeAppendResult {
41
- readonly accepted: boolean;
42
- readonly entry?: VehicleJobWakeEntry;
43
- readonly dropReason?: VehicleJobWakeDropReason;
44
- }
45
-
46
- export interface VehicleJobWakeLogOptions {
47
- readonly notifyMode: VehicleJobNotifyMode;
48
- readonly budget: VehicleJobWakeBudget;
49
- /** Defaults to Date.now. */
50
- readonly now?: () => number;
51
- }
52
-
53
- /** Bounds a job's accumulated progress notifications by count+bytes, same discipline as enforcePayloadSize but across a job's whole lifetime. */
54
- export class VehicleJobWakeLog {
55
- private readonly entries: VehicleJobWakeEntry[] = [];
56
- private usedBytes = 0;
57
- private nextSeq = 1;
58
- private lastHash: string | undefined;
59
- private acceptedFirst = false;
60
- private readonly now: () => number;
61
-
62
- constructor(private readonly options: VehicleJobWakeLogOptions) {
63
- this.now = options.now ?? Date.now;
64
- }
65
-
66
- append(progress: unknown): VehicleJobWakeAppendResult {
67
- if (this.options.notifyMode === "first-only" && this.acceptedFirst) {
68
- return { accepted: false, dropReason: "superseded-by-first-only" };
69
- }
70
- const serialized = safeJsonStringify(progress);
71
- if (this.options.notifyMode === "transition") {
72
- const hash = fnv1aHash(serialized);
73
- if (hash === this.lastHash) return { accepted: false, dropReason: "deduplicated-transition" };
74
- this.lastHash = hash;
75
- }
76
- const bytes = new TextEncoder().encode(serialized).byteLength;
77
- if (this.entries.length >= this.options.budget.maxCount) return { accepted: false, dropReason: "count-budget-exhausted" };
78
- if (this.usedBytes + bytes > this.options.budget.maxBytes) return { accepted: false, dropReason: "byte-budget-exhausted" };
79
-
80
- const entry: VehicleJobWakeEntry = { seq: this.nextSeq++, at: this.now(), progress };
81
- this.entries.push(entry);
82
- this.usedBytes += bytes;
83
- this.acceptedFirst = true;
84
- return { accepted: true, entry };
85
- }
86
-
87
- /** Entries with seq strictly greater than `cursor`. */
88
- since(cursor: number): readonly VehicleJobWakeEntry[] {
89
- return this.entries.filter((entry) => entry.seq > cursor);
90
- }
91
-
92
- /** Highest seq issued so far (0 if none accepted yet). */
93
- get cursor(): number {
94
- return this.nextSeq - 1;
95
- }
96
- }
97
-
98
- function safeJsonStringify(value: unknown): string {
99
- let serialized: string | undefined;
100
- try {
101
- serialized = JSON.stringify(value);
102
- } catch (error) {
103
- throw new Error("Vehicle job progress value is not JSON-serializable", { cause: error });
104
- }
105
- if (serialized === undefined) throw new Error("Vehicle job progress value is not JSON-serializable");
106
- return serialized;
107
- }
108
-
109
- /** Non-cryptographic (FNV-1a) -- dedup only. */
110
- function fnv1aHash(value: string): string {
111
- let hash = 0x811c9dc5;
112
- for (let i = 0; i < value.length; i++) {
113
- hash ^= value.charCodeAt(i);
114
- hash = Math.imul(hash, 0x01000193);
115
- }
116
- return (hash >>> 0).toString(16);
117
- }
118
-
119
- /** Read-only replay side of a wake log -- both a live VehicleJobWakeLog and a restored (no-longer-appendable) job satisfy this with the same tail() semantics. */
120
- export interface VehicleJobWakeLogReader {
121
- since(cursor: number): readonly VehicleJobWakeEntry[];
122
- readonly cursor: number;
123
- }
124
-
125
- /** Wraps a fixed, already-finalized list of entries (e.g. restored from disk) in the same reader shape a live VehicleJobWakeLog exposes, so VehicleJobStore.tail() doesn't need to special-case a restored job. */
126
- export function createStaticVehicleJobWakeLog(entries: readonly VehicleJobWakeEntry[]): VehicleJobWakeLogReader {
127
- const sorted = [...entries].sort((a, b) => a.seq - b.seq);
128
- const cursor = sorted.length > 0 ? sorted[sorted.length - 1]!.seq : 0;
129
- return {
130
- since: (cursorArg) => sorted.filter((entry) => entry.seq > cursorArg),
131
- cursor,
132
- };
133
- }
134
-
135
- /**
136
- * A job's mid-flight input channel -- the "steer" primitive. Bounded FIFO:
137
- * push() while a handler isn't yet reading buffers up to maxQueueSize, then
138
- * refuses further input rather than growing unboundedly or silently
139
- * overwriting an unread entry. A handler consumes it via `for await (const
140
- * input of context.steerInputs)`, which ends cleanly once close() is
141
- * called (VehicleJobStore does this at job finalization).
142
- */
143
- export interface VehicleJobSteerPushResult {
144
- readonly accepted: boolean;
145
- readonly dropReason?: "queue-full" | "channel-closed";
146
- }
147
-
148
- export class VehicleJobSteerChannel implements AsyncIterable<unknown> {
149
- private readonly buffer: unknown[] = [];
150
- private readonly waiters: ((result: IteratorResult<unknown>) => void)[] = [];
151
- private closed = false;
152
-
153
- constructor(private readonly maxQueueSize: number = 64) {}
154
-
155
- push(value: unknown): VehicleJobSteerPushResult {
156
- if (this.closed) return { accepted: false, dropReason: "channel-closed" };
157
- const waiter = this.waiters.shift();
158
- if (waiter) {
159
- waiter({ value, done: false });
160
- return { accepted: true };
161
- }
162
- if (this.buffer.length >= this.maxQueueSize) return { accepted: false, dropReason: "queue-full" };
163
- this.buffer.push(value);
164
- return { accepted: true };
165
- }
166
-
167
- /** Ends every pending and future iteration with done:true; further push() calls report "channel-closed". Idempotent. */
168
- close(): void {
169
- if (this.closed) return;
170
- this.closed = true;
171
- for (const waiter of this.waiters.splice(0)) waiter({ value: undefined, done: true });
172
- }
173
-
174
- [Symbol.asyncIterator](): AsyncIterator<unknown> {
175
- return {
176
- next: (): Promise<IteratorResult<unknown>> => {
177
- if (this.buffer.length > 0) return Promise.resolve({ value: this.buffer.shift(), done: false });
178
- if (this.closed) return Promise.resolve({ value: undefined, done: true });
179
- return new Promise((resolve) => this.waiters.push(resolve));
180
- },
181
- };
182
- }
183
- }
184
-
185
- /**
186
- * Vehicle Jobs run as in-process promises, not child processes -- there is
187
- * no PID to reuse, but the same identity-confusion risk vstack's
188
- * {pid, startToken, comm} design guards against still applies in a
189
- * generalized form: a persisted job record written by one process
190
- * instance must never be mistaken for one this (possibly restarted)
191
- * instance can still resolve. Each VehicleJobStore construction gets a
192
- * fresh random instanceToken; a persisted record's own stamped token only
193
- * ever matches the instance that wrote it. A mismatch means "the original
194
- * run is gone", the same conclusion vstack's identityMatches() reaches by
195
- * comparing a live process's actual pid/start-time/command against a
196
- * stored snapshot -- this is that same check with no process to inspect.
197
- */
198
- export function vehicleJobIdentityMatches(recordInstanceToken: string, currentInstanceToken: string): boolean {
199
- return recordInstanceToken === currentInstanceToken;
200
- }
201
-
202
- /** Minimal shape selectVehicleJobsForEviction needs from a job record -- kept separate from VehicleJobSnapshot so vehicle-server doesn't have to construct a full snapshot just to ask "should this be swept". */
203
- export interface VehicleJobEvictionCandidate {
204
- readonly jobId: string;
205
- readonly status: VehicleJobStatus;
206
- readonly delivered: boolean;
207
- readonly updatedAt: number;
208
- }
209
-
210
- export interface VehicleJobRetentionOptions {
211
- /** Hard cap on total retained job records (of any status). A running job is never evicted regardless of this cap. */
212
- readonly maxRetainedJobs: number;
213
- /** A delivered terminal job becomes eligible for eviction once this many ms have passed since it was delivered (== updatedAt at delivery time). */
214
- readonly deliveredRetentionMs: number;
215
- readonly now: number;
216
- }
217
-
218
- /**
219
- * The client-facing wire shapes for Vehicle Jobs -- submit/poll/tail options and results, shared by
220
- * vehicle-server's VehicleJobStore (the orchestration side) and vehicle-client's job-capable clients
221
- * (the calling side), so both halves of the wire agree on one definition instead of two structurally
222
- *-identical copies drifting apart. Every field type referenced here already lives in vehicle-core
223
- * (VehiclePrincipal, VehicleFailure, VehicleJobStatus, ...), which is what makes it safe for these
224
- * shapes to live here too, alongside the rest of Vehicle Jobs' pure pieces.
225
- */
226
- export interface VehicleJobSubmitOptions {
227
- readonly permissions?: readonly string[];
228
- readonly principal?: VehiclePrincipal;
229
- readonly idempotencyKey?: string;
230
- readonly expectedRevision?: string | number;
231
- readonly approvalCapability?: string;
232
- readonly correlationId?: string;
233
- readonly callerSessionId?: string;
234
- readonly callerProjectRoot?: string;
235
- /** Defaults to "transition". */
236
- readonly notifyMode?: VehicleJobNotifyMode;
237
- /** Defaults to background.defaultWakeBudget; clamped to background.maxWakeBudget either way. */
238
- readonly wakeBudget?: VehicleJobWakeBudget;
239
- /** No default -- unset means the job runs until it settles or is canceled. */
240
- readonly maxLifetimeMs?: number;
241
- }
242
-
243
- export interface VehicleJobSubmitResult {
244
- readonly jobId: string;
245
- }
246
-
247
- export interface VehicleJobSnapshot {
248
- readonly jobId: string;
249
- readonly operationName: string;
250
- readonly operationVersion: number;
251
- readonly status: VehicleJobStatus;
252
- readonly createdAt: number;
253
- readonly updatedAt: number;
254
- readonly delivered: boolean;
255
- readonly terminationReason?: VehicleJobTerminationReason;
256
- readonly output?: unknown;
257
- readonly error?: VehicleFailure;
258
- }
259
-
260
- export interface VehicleJobTailResult {
261
- readonly entries: readonly VehicleJobWakeEntry[];
262
- readonly cursor: number;
263
- }
264
-
265
- /**
266
- * Pure eviction-selection policy, kept separate from VehicleJobStore's own
267
- * bookkeeping so the bounded-retention rule is independently testable.
268
- * Preference order: (1) delivered and past deliveredRetentionMs, oldest
269
- * first; (2) once still over maxRetainedJobs, any delivered terminal job,
270
- * oldest first; (3) only as a last resort, an undelivered terminal job,
271
- * oldest first -- a real loss (a caller may still want that result), but
272
- * an unbounded store is a worse failure mode. A running job is never a
273
- * candidate.
274
- */
275
- export function selectVehicleJobsForEviction(
276
- candidates: readonly VehicleJobEvictionCandidate[],
277
- options: VehicleJobRetentionOptions,
278
- ): readonly string[] {
279
- const terminal = candidates.filter((candidate) => candidate.status !== "running");
280
- const byAgeAscending = (a: VehicleJobEvictionCandidate, b: VehicleJobEvictionCandidate) => a.updatedAt - b.updatedAt;
281
-
282
- const evicted = new Set<string>();
283
- for (const candidate of terminal) {
284
- if (candidate.delivered && options.now - candidate.updatedAt >= options.deliveredRetentionMs) evicted.add(candidate.jobId);
285
- }
286
-
287
- const remainingCount = () => candidates.length - evicted.size;
288
- if (remainingCount() > options.maxRetainedJobs) {
289
- const deliveredOldestFirst = terminal.filter((candidate) => candidate.delivered && !evicted.has(candidate.jobId)).sort(byAgeAscending);
290
- for (const candidate of deliveredOldestFirst) {
291
- if (remainingCount() <= options.maxRetainedJobs) break;
292
- evicted.add(candidate.jobId);
293
- }
294
- }
295
- if (remainingCount() > options.maxRetainedJobs) {
296
- const undeliveredOldestFirst = terminal
297
- .filter((candidate) => !candidate.delivered && !evicted.has(candidate.jobId))
298
- .sort(byAgeAscending);
299
- for (const candidate of undeliveredOldestFirst) {
300
- if (remainingCount() <= options.maxRetainedJobs) break;
301
- evicted.add(candidate.jobId);
302
- }
303
- }
304
- return [...evicted];
305
- }
File without changes