@inhuman.tools/plexus-expectations 0.0.0-stage → 0.1.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 (160) hide show
  1. package/LICENSE.md +7 -0
  2. package/README.md +144 -2
  3. package/dist/driver/ExpectationActor.d.ts +56 -0
  4. package/dist/driver/ExpectationActor.d.ts.map +1 -0
  5. package/dist/driver/ExpectationActor.js +210 -0
  6. package/dist/driver/ExpectationActor.js.map +1 -0
  7. package/dist/driver/PEWDriver.d.ts +144 -0
  8. package/dist/driver/PEWDriver.d.ts.map +1 -0
  9. package/dist/driver/PEWDriver.js +303 -0
  10. package/dist/driver/PEWDriver.js.map +1 -0
  11. package/dist/driver/PEWDriverConnection.d.ts +139 -0
  12. package/dist/driver/PEWDriverConnection.d.ts.map +1 -0
  13. package/dist/driver/PEWDriverConnection.js +298 -0
  14. package/dist/driver/PEWDriverConnection.js.map +1 -0
  15. package/dist/driver/actor-machine.d.ts +28 -0
  16. package/dist/driver/actor-machine.d.ts.map +1 -0
  17. package/dist/driver/actor-machine.js +50 -0
  18. package/dist/driver/actor-machine.js.map +1 -0
  19. package/dist/driver/connection-miss.d.ts +9 -0
  20. package/dist/driver/connection-miss.d.ts.map +1 -0
  21. package/dist/driver/connection-miss.js +13 -0
  22. package/dist/driver/connection-miss.js.map +1 -0
  23. package/dist/driver/index.d.ts +6 -0
  24. package/dist/driver/index.d.ts.map +1 -0
  25. package/dist/driver/index.js +5 -0
  26. package/dist/driver/index.js.map +1 -0
  27. package/dist/error-with-invariant.d.ts +9 -0
  28. package/dist/error-with-invariant.d.ts.map +1 -0
  29. package/dist/error-with-invariant.js +12 -0
  30. package/dist/error-with-invariant.js.map +1 -0
  31. package/dist/executor/index.d.ts +4 -0
  32. package/dist/executor/index.d.ts.map +1 -0
  33. package/dist/executor/index.js +4 -0
  34. package/dist/executor/index.js.map +1 -0
  35. package/dist/executor/kernel-intern.d.ts +16 -0
  36. package/dist/executor/kernel-intern.d.ts.map +1 -0
  37. package/dist/executor/kernel-intern.js +98 -0
  38. package/dist/executor/kernel-intern.js.map +1 -0
  39. package/dist/executor/orchestrator.d.ts +97 -0
  40. package/dist/executor/orchestrator.d.ts.map +1 -0
  41. package/dist/executor/orchestrator.js +465 -0
  42. package/dist/executor/orchestrator.js.map +1 -0
  43. package/dist/executor/types.d.ts +8 -0
  44. package/dist/executor/types.d.ts.map +1 -0
  45. package/dist/executor/types.js +2 -0
  46. package/dist/executor/types.js.map +1 -0
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +2 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/schemas/connection.d.ts +4 -0
  52. package/dist/schemas/connection.d.ts.map +1 -0
  53. package/dist/schemas/connection.js +4 -0
  54. package/dist/schemas/connection.js.map +1 -0
  55. package/dist/schemas/index.d.ts +2 -0
  56. package/dist/schemas/index.d.ts.map +1 -0
  57. package/dist/schemas/index.js +2 -0
  58. package/dist/schemas/index.js.map +1 -0
  59. package/dist/shared/attention.d.ts +27 -0
  60. package/dist/shared/attention.d.ts.map +1 -0
  61. package/dist/shared/attention.js +116 -0
  62. package/dist/shared/attention.js.map +1 -0
  63. package/dist/shared/control.d.ts +4 -0
  64. package/dist/shared/control.d.ts.map +1 -0
  65. package/dist/shared/control.js +2 -0
  66. package/dist/shared/control.js.map +1 -0
  67. package/dist/shared/index.d.ts +7 -0
  68. package/dist/shared/index.d.ts.map +1 -0
  69. package/dist/shared/index.js +7 -0
  70. package/dist/shared/index.js.map +1 -0
  71. package/dist/shared/map-field-awareness.d.ts +19 -0
  72. package/dist/shared/map-field-awareness.d.ts.map +1 -0
  73. package/dist/shared/map-field-awareness.js +58 -0
  74. package/dist/shared/map-field-awareness.js.map +1 -0
  75. package/dist/shared/models/ApprovableExpectation.d.ts +15 -0
  76. package/dist/shared/models/ApprovableExpectation.d.ts.map +1 -0
  77. package/dist/shared/models/ApprovableExpectation.js +138 -0
  78. package/dist/shared/models/ApprovableExpectation.js.map +1 -0
  79. package/dist/shared/models/ConnectionSpec.d.ts +44 -0
  80. package/dist/shared/models/ConnectionSpec.d.ts.map +1 -0
  81. package/dist/shared/models/ConnectionSpec.js +180 -0
  82. package/dist/shared/models/ConnectionSpec.js.map +1 -0
  83. package/dist/shared/models/DriverSpec.d.ts +45 -0
  84. package/dist/shared/models/DriverSpec.d.ts.map +1 -0
  85. package/dist/shared/models/DriverSpec.js +221 -0
  86. package/dist/shared/models/DriverSpec.js.map +1 -0
  87. package/dist/shared/models/IntrospectingPlexusModel.d.ts +8 -0
  88. package/dist/shared/models/IntrospectingPlexusModel.d.ts.map +1 -0
  89. package/dist/shared/models/IntrospectingPlexusModel.js +48 -0
  90. package/dist/shared/models/IntrospectingPlexusModel.js.map +1 -0
  91. package/dist/shared/models/Job.d.ts +85 -0
  92. package/dist/shared/models/Job.d.ts.map +1 -0
  93. package/dist/shared/models/Job.js +261 -0
  94. package/dist/shared/models/Job.js.map +1 -0
  95. package/dist/shared/models/ProgrammaticJob.d.ts +6 -0
  96. package/dist/shared/models/ProgrammaticJob.d.ts.map +1 -0
  97. package/dist/shared/models/ProgrammaticJob.js +80 -0
  98. package/dist/shared/models/ProgrammaticJob.js.map +1 -0
  99. package/dist/shared/models/WorkContainer.d.ts +36 -0
  100. package/dist/shared/models/WorkContainer.d.ts.map +1 -0
  101. package/dist/shared/models/WorkContainer.js +140 -0
  102. package/dist/shared/models/WorkContainer.js.map +1 -0
  103. package/dist/shared/models/WorkExpectation.d.ts +63 -0
  104. package/dist/shared/models/WorkExpectation.d.ts.map +1 -0
  105. package/dist/shared/models/WorkExpectation.js +290 -0
  106. package/dist/shared/models/WorkExpectation.js.map +1 -0
  107. package/dist/shared/models/WorkExpectationWithIntrospection.d.ts +4 -0
  108. package/dist/shared/models/WorkExpectationWithIntrospection.d.ts.map +1 -0
  109. package/dist/shared/models/WorkExpectationWithIntrospection.js +28 -0
  110. package/dist/shared/models/WorkExpectationWithIntrospection.js.map +1 -0
  111. package/dist/shared/models/index.d.ts +7 -0
  112. package/dist/shared/models/index.d.ts.map +1 -0
  113. package/dist/shared/models/index.js +6 -0
  114. package/dist/shared/models/index.js.map +1 -0
  115. package/dist/shared/models/jsonRecord.d.ts +14 -0
  116. package/dist/shared/models/jsonRecord.d.ts.map +1 -0
  117. package/dist/shared/models/jsonRecord.js +46 -0
  118. package/dist/shared/models/jsonRecord.js.map +1 -0
  119. package/dist/shared/resolution.d.ts +39 -0
  120. package/dist/shared/resolution.d.ts.map +1 -0
  121. package/dist/shared/resolution.js +124 -0
  122. package/dist/shared/resolution.js.map +1 -0
  123. package/dist/shared/revalidation-demand.d.ts +27 -0
  124. package/dist/shared/revalidation-demand.d.ts.map +1 -0
  125. package/dist/shared/revalidation-demand.js +116 -0
  126. package/dist/shared/revalidation-demand.js.map +1 -0
  127. package/dist/shared/role.d.ts +12 -0
  128. package/dist/shared/role.d.ts.map +1 -0
  129. package/dist/shared/role.js +21 -0
  130. package/dist/shared/role.js.map +1 -0
  131. package/dist/shared/types.d.ts +43 -0
  132. package/dist/shared/types.d.ts.map +1 -0
  133. package/dist/shared/types.js +12 -0
  134. package/dist/shared/types.js.map +1 -0
  135. package/package.json +79 -3
  136. package/src/driver/ExpectationActor.ts +244 -0
  137. package/src/driver/PEWDriver.ts +302 -0
  138. package/src/driver/actor-machine.ts +54 -0
  139. package/src/driver/connection-miss.ts +13 -0
  140. package/src/driver/index.ts +5 -0
  141. package/src/executor/index.ts +3 -0
  142. package/src/executor/kernel-intern.ts +121 -0
  143. package/src/executor/orchestrator.ts +463 -0
  144. package/src/executor/types.ts +3 -0
  145. package/src/index.ts +1 -0
  146. package/src/schemas/connection.ts +4 -0
  147. package/src/schemas/index.ts +1 -0
  148. package/src/shared/control.ts +4 -0
  149. package/src/shared/index.ts +6 -0
  150. package/src/shared/map-field-awareness.ts +65 -0
  151. package/src/shared/models/ConnectionSpec.ts +84 -0
  152. package/src/shared/models/DriverSpec.ts +102 -0
  153. package/src/shared/models/Job.ts +192 -0
  154. package/src/shared/models/WorkContainer.ts +90 -0
  155. package/src/shared/models/WorkExpectation.ts +229 -0
  156. package/src/shared/models/index.ts +6 -0
  157. package/src/shared/models/jsonRecord.ts +49 -0
  158. package/src/shared/revalidation-demand.ts +121 -0
  159. package/src/shared/role.ts +32 -0
  160. package/src/shared/types.ts +57 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Process-local connection intern table keyed by the kernel root object.
3
+ *
4
+ * Session wrap is Yjs load. Park drops an owner ref and must not dispose the
5
+ * instance — {@link disposeKernelConnections} is kernel teardown only.
6
+ * Rejected: last-ref dispose. Switching seats reminted every driver.
7
+ */
8
+ import { DefaultedWeakMap } from "@here.build/collections";
9
+ import { comparer, reaction, type IReactionDisposer } from "mobx";
10
+
11
+ import { ConnectionMiss } from "../driver/connection-miss.js";
12
+ import { extraLiveFromState, type PEWDriver } from "../driver/PEWDriver.js";
13
+ import type { ConnectionSpec } from "../shared/models/ConnectionSpec.js";
14
+ import { asReadyState } from "../shared/types.js";
15
+
16
+ type InternOwner = { forgetConnection(id: string): void };
17
+
18
+ function internOwnerOf(owner: object): InternOwner | undefined {
19
+ return typeof (owner as InternOwner).forgetConnection === "function" ? (owner as InternOwner) : undefined;
20
+ }
21
+
22
+ type KernelRoot = { readonly connections: Record<string, ConnectionSpec | undefined> };
23
+ type ConnectionHold = {
24
+ readonly refs: Set<object>;
25
+ readonly pending: Promise<PEWDriver>;
26
+ mirror: IReactionDisposer | undefined;
27
+ };
28
+ type KernelIntern = { readonly connections: Map<string, ConnectionHold> };
29
+
30
+ const internByKernel = new DefaultedWeakMap<object, KernelIntern>(() => ({ connections: new Map() }));
31
+
32
+ export function acquireConnection(
33
+ kernel: KernelRoot,
34
+ owner: object,
35
+ connectionId: string,
36
+ construct: () => PEWDriver | Promise<PEWDriver>,
37
+ ): Promise<PEWDriver> {
38
+ const bag = internByKernel.get(kernel);
39
+ const existing = bag.connections.get(connectionId);
40
+ if (existing !== undefined) {
41
+ existing.refs.add(owner);
42
+ return existing.pending;
43
+ }
44
+ const lease: ConnectionHold = {
45
+ refs: new Set([owner]),
46
+ pending: Promise.resolve().then(construct).then((instance) => {
47
+ lease.mirror = reaction(
48
+ () => {
49
+ const spec = kernel.connections[connectionId];
50
+ if (spec === undefined) return null;
51
+ const ready = asReadyState(instance.readyState);
52
+ // Bootstrapping remint must not wipe a ready catalog.
53
+ if (ready !== "ready" && ready !== "failed" && spec.readyState === "ready") return null;
54
+ return { ready, error: instance.error, live: extraLiveFromState(instance.state) };
55
+ },
56
+ (snap) => {
57
+ if (snap == null) return;
58
+ kernel.connections[connectionId]?.stampProcess({
59
+ readyState: snap.ready,
60
+ error: snap.error,
61
+ live: snap.live,
62
+ });
63
+ },
64
+ { fireImmediately: true, equals: comparer.structural },
65
+ );
66
+ return instance;
67
+ }),
68
+ mirror: undefined,
69
+ };
70
+ bag.connections.set(connectionId, lease);
71
+ void lease.pending.then(undefined, () => {
72
+ if (lease.refs.size === 0) bag.connections.delete(connectionId);
73
+ });
74
+ return lease.pending;
75
+ }
76
+
77
+ export function releaseConnection(kernel: object, owner: object, connectionId: string): void {
78
+ if (!internByKernel.has(kernel)) return;
79
+ internByKernel.get(kernel).connections.get(connectionId)?.refs.delete(owner);
80
+ }
81
+
82
+ /**
83
+ * Remint door. Logout/drop — not park, not last-ref.
84
+ * Pending lease still `asyncDispose`s when it fulfills. Next `ensure` remints.
85
+ */
86
+ export async function dropConnection(kernel: KernelRoot, connectionId: string): Promise<void> {
87
+ if (!internByKernel.has(kernel)) return;
88
+ const bag = internByKernel.get(kernel);
89
+ const lease = bag.connections.get(connectionId);
90
+ if (lease === undefined) return;
91
+ bag.connections.delete(connectionId);
92
+ lease.mirror?.();
93
+ const owners = [...lease.refs];
94
+ lease.refs.clear();
95
+ const miss = new ConnectionMiss("connection-dropped", `connection ${connectionId} dropped`);
96
+ const disposing = lease.pending.then(
97
+ (instance) => {
98
+ instance.abortOnDrop(miss);
99
+ return instance[Symbol.asyncDispose]();
100
+ },
101
+ () => {},
102
+ );
103
+ for (const owner of owners) internOwnerOf(owner)?.forgetConnection(connectionId);
104
+ await disposing;
105
+ }
106
+
107
+ /** Kernel teardown only. Session park is a document wrap, not a connection lifetime. */
108
+ export function disposeKernelConnections(kernel: object): void {
109
+ if (!internByKernel.has(kernel)) return;
110
+ const bag = internByKernel.get(kernel);
111
+ internByKernel.delete(kernel);
112
+ for (const lease of bag.connections.values()) {
113
+ lease.refs.clear();
114
+ lease.mirror?.();
115
+ void lease.pending.then(
116
+ (instance) => instance[Symbol.asyncDispose](),
117
+ () => {},
118
+ );
119
+ }
120
+ bag.connections.clear();
121
+ }
@@ -0,0 +1,463 @@
1
+ import { DefaultedMap } from "@here.build/collections";
2
+ import { action, autorun, comparer, computed, observable, type IReactionDisposer, reaction, toJS } from "mobx";
3
+ import invariant from "tiny-invariant";
4
+
5
+ import {
6
+ acquireConnection,
7
+ releaseConnection,
8
+ } from "./kernel-intern.js";
9
+ import { ExpectationActor } from "../driver/ExpectationActor.js";
10
+ import {
11
+ type ConnectionSecretsView,
12
+ type DriverConnectionClass,
13
+ extraLiveFromState,
14
+ isDriverConnectionClass,
15
+ type PEWDriver,
16
+ } from "../driver/PEWDriver.js";
17
+ import { DriverSpec } from "../shared/models/DriverSpec.js";
18
+ import { Job } from "../shared/models/Job.js";
19
+ import { WorkContainer, walkWork } from "../shared/models/WorkContainer.js";
20
+ import { type AnyWorkExpectation, WorkExpectation, isTreeOrphan } from "../shared/models/WorkExpectation.js";
21
+ import { type KernelPlexus, type SessionPlexus } from "../shared/types.js";
22
+
23
+ /** Class identity for `instanceof`. `registerExecutor` never constructs. */
24
+ export type JobConstructor<T extends Job = Job> = abstract new (...args: any[]) => T;
25
+
26
+ /**
27
+ * Seam: session work graph → honor (PEW) and claim (Job).
28
+ *
29
+ * Honor is reachable PEW → handle. Unstarted cancel writes the durable
30
+ * ending here and must not poke `ensure` — MCP: an unstarted tool must not
31
+ * spin the server. Do not call `Actor.complete` — unstarted Work has no
32
+ * Actor. `handle` is not the sealer. License is phase 1 on an Approvable
33
+ * leaf. A sealed parent is not honored (the
34
+ * child is already ending in the agentic runtime, or must not start).
35
+ *
36
+ * INTERN TABLE IS NOT AN ATOM. `#connections` is a plain Map of kernel-interned
37
+ * instances (one live driver per kernel connection id). Honor re-enters by
38
+ * reading catalog `spec.readyState` and, once minted, `instance.readyState`.
39
+ * `handle` only when `ready`.
40
+ *
41
+ * A rejected ensure/load memo IS the sticky failure (no hot loop).
42
+ *
43
+ * Honor and Job claim do not start in the constructor. PEW autorun used to
44
+ * run during `super()`, so a readiness Promise after construct was not a
45
+ * gate. Call {@link activate} after replicas are pinned and recovery ran.
46
+ *
47
+ * Import discipline: this module does not import harness or the session document.
48
+ */
49
+ export abstract class Orchestrator<
50
+ K extends KernelPlexus = KernelPlexus,
51
+ S extends SessionPlexus = SessionPlexus,
52
+ > implements Disposable {
53
+ #disposed = false;
54
+ #admissionStopped = false;
55
+ readonly #activated = observable.box(false);
56
+ readonly #disposeWork: () => void;
57
+ /** Disposed with the orchestrator — a dead session must not keep writing the live kernel catalog. */
58
+ readonly #mirrorDisposers: IReactionDisposer[] = [];
59
+ readonly #processes = new Map<JobConstructor, () => void>();
60
+ /** Execute (phase 2) — started BODY. */
61
+ readonly #jobAbort = new Map<Job, AbortController>();
62
+ /** In-flight license (phase 1). */
63
+ readonly #guardAbort = new Map<Job, AbortController>();
64
+ /**
65
+ * Process-local: execute already claimed this job. Survives seal:false
66
+ * so the starter does not re-run BODY. A new Orchestrator is empty —
67
+ * bootstrap `orchestrated && !completed` runs execute once more.
68
+ */
69
+ readonly #bodyStarted = new WeakSet<Job>();
70
+ /**
71
+ * Origin-dispatched PEW skip. Lives here, not on the session subclass:
72
+ * honor used to run during `super()`, and subclass fields are unassigned
73
+ * then (JS). A child WeakSet made `shouldHonor` throw `undefined.has`.
74
+ */
75
+ protected readonly originCompletions = new WeakSet<WorkExpectation>();
76
+ readonly #disposeAborts: () => void;
77
+
78
+ constructor(
79
+ public readonly kernel: K,
80
+ public readonly session: S,
81
+ ) {
82
+ this.#mirrorDisposers.push(
83
+ autorun(() => {
84
+ if (this.#disposed || !this.#activated.get()) return;
85
+ for (const name of Object.keys(this.drivers)) {
86
+ // Driver discovery is intentionally eager so the kernel catalog can
87
+ // expose class-side offers and live facts before a connection is
88
+ // ensured. A session may not be able to load every driver in a
89
+ // shared kernel, so consume a rejected discovery promise here; the
90
+ // driver spec already carries the failure for interested readers.
91
+ void this.#classes.get(name).catch(() => {});
92
+ }
93
+ }),
94
+ );
95
+ this.#disposeWork = autorun(() => {
96
+ if (this.#disposed || !this.#activated.get()) return;
97
+ for (const node of collectReachable(this.session.root)) {
98
+ if (node.isDone || isTreeOrphan(node)) continue;
99
+ if (!this.shouldHonor(node)) continue;
100
+ const spec = this.connections[node.connectionId];
101
+ if (spec === undefined) continue;
102
+ void spec.readyState;
103
+ const instance = this.#connections.get(node.connectionId);
104
+ if (instance !== undefined) {
105
+ if (instance.readyState === "ready") instance.handle(node);
106
+ continue;
107
+ }
108
+ invariant(Object.hasOwn(this.connections, node.connectionId), `unknown connection ${node.connectionId}`);
109
+ void this.ensure(node.connectionId);
110
+ }
111
+ });
112
+ this.#disposeAborts = autorun(() => {
113
+ if (this.#disposed || !this.#activated.get()) return;
114
+ const live = new Set(this.reachableJobs);
115
+ for (const [job, ac] of this.#jobAbort) {
116
+ if (live.has(job) || ac.signal.aborted) continue;
117
+ ac.abort();
118
+ }
119
+ for (const [job, ac] of this.#guardAbort) {
120
+ if (live.has(job) || ac.signal.aborted) continue;
121
+ ac.abort();
122
+ }
123
+ });
124
+ }
125
+
126
+ @computed
127
+ protected get reachableJobs(): Job[] {
128
+ const root = this.session.root;
129
+ const jobs = new Set<Job>();
130
+ if (root instanceof Job) jobs.add(root);
131
+ if (root instanceof WorkContainer) {
132
+ for (const job of Iterator.from(walkWork(root)).filter((node): node is Job => node instanceof Job)) {
133
+ jobs.add(job);
134
+ }
135
+ }
136
+ return [...jobs];
137
+ }
138
+
139
+ /**
140
+ * Two functions. License (phase 1) returns `true` | `false` and writes
141
+ * `orchestrationResult` (`orchestrated` follows). `true` → await execute
142
+ * (phase 2). `false` → skip execute, `completed = true`. Bootstrap
143
+ * `orchestrated && !completed` skips the license and runs execute.
144
+ * `signal` aborts when the job leaves the graph or the orchestrator disposes.
145
+ */
146
+ registerExecutor<T extends Job>(
147
+ Class: JobConstructor<T>,
148
+ license: (job: T, orchestrator: this) => boolean | Promise<boolean>,
149
+ execute: (job: T, signal: AbortSignal, orchestrator: this) => void | Promise<void>,
150
+ options?: { readonly seal?: boolean },
151
+ ): void {
152
+ invariant(!this.#processes.has(Class), `Orchestrator: executor already registered for ${Class.name}`);
153
+ const seal = options?.seal !== false;
154
+ this.#processes.set(
155
+ Class,
156
+ autorun(() => {
157
+ if (this.#disposed || !this.#activated.get()) return;
158
+ for (const node of this.reachableJobs) {
159
+ if (!(node instanceof Class)) continue;
160
+ const job = node as T;
161
+ if (job.completed || job.cancelled) continue;
162
+ if (job.orchestrationResult === false) {
163
+ job.markComplete();
164
+ continue;
165
+ }
166
+ if (job.orchestrationResult === true) {
167
+ this.#startExecute(job, execute, seal);
168
+ continue;
169
+ }
170
+ if (this.#guardAbort.has(job) || this.#jobAbort.has(job)) continue;
171
+ // Ordering is data on the job: wait here until every predecessor is released.
172
+ if (!job.afterReleased) continue;
173
+ this.#startGuard(job, license, execute, seal);
174
+ }
175
+ }),
176
+ );
177
+ }
178
+
179
+ #startGuard<T extends Job>(
180
+ job: T,
181
+ license: (job: T, orchestrator: this) => boolean | Promise<boolean>,
182
+ execute: (job: T, signal: AbortSignal, orchestrator: this) => void | Promise<void>,
183
+ seal: boolean,
184
+ ): void {
185
+ const settle = action((ok: boolean) => {
186
+ if (job.orchestrationResult !== null || job.completed || job.cancelled) return;
187
+ job.orchestrationResult = ok;
188
+ if (ok) {this.#startExecute(job, execute, seal);}
189
+ else {job.markComplete();}
190
+ });
191
+ // A guard that threw never licensed the job: deny it with a crash receipt.
192
+ const crashed = action((error: unknown) => {
193
+ if (job.orchestrationResult !== null || job.completed || job.cancelled) return;
194
+ this.#recordCrash(job, "license", error);
195
+ job.orchestrationResult = false;
196
+ job.markComplete();
197
+ });
198
+ try {
199
+ const result = license(job, this);
200
+ if (typeof result === "boolean") {
201
+ settle(result);
202
+ return;
203
+ }
204
+ const ac = new AbortController();
205
+ this.#guardAbort.set(job, ac);
206
+ void result.then(
207
+ (ok) => {
208
+ if (ac.signal.aborted) return;
209
+ settle(ok);
210
+ return ok;
211
+ },
212
+ (error: unknown) => {
213
+ if (ac.signal.aborted) return;
214
+ crashed(error);
215
+ },
216
+ ).finally(
217
+ action(() => {
218
+ this.#guardAbort.delete(job);
219
+ }),
220
+ );
221
+ } catch (error) {
222
+ crashed(error);
223
+ }
224
+ }
225
+
226
+ #startExecute<T extends Job>(
227
+ job: T,
228
+ execute: (job: T, signal: AbortSignal, orchestrator: this) => void | Promise<void>,
229
+ seal: boolean,
230
+ ): void {
231
+ if (this.#bodyStarted.has(job) || job.completed || job.cancelled) return;
232
+ if (job.orchestrationResult !== true) return;
233
+ this.#bodyStarted.add(job);
234
+ action(() => {
235
+ job.markStarted();
236
+ })();
237
+ const ac = new AbortController();
238
+ this.#jobAbort.set(job, ac);
239
+ void Promise.resolve()
240
+ .then(() => execute(job, ac.signal, this))
241
+ .then(
242
+ () => false,
243
+ (error: unknown) => {
244
+ // An abort (cancel, park, leaving the graph) is not a crash: the aborter owns the ending.
245
+ if (ac.signal.aborted || job.completed || job.cancelled) return false;
246
+ action(() => this.#recordCrash(job, "body", error))();
247
+ return true;
248
+ },
249
+ )
250
+ .then(
251
+ action((crashed: boolean) => {
252
+ if (seal || crashed) job.markComplete();
253
+ this.#jobAbort.delete(job);
254
+ }),
255
+ )
256
+ .catch(() => {});
257
+ }
258
+
259
+ #recordCrash(job: Job, phase: "license" | "body", error: unknown): void {
260
+ const detail = error instanceof Error ? error.message : String(error);
261
+ job.crash = `${phase}: ${detail === "" ? "unknown error" : detail}`;
262
+ try {
263
+ this.stampCrash(job, phase, detail);
264
+ } catch {
265
+ /* the crash fact is already on the job; the receipt is best effort */
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Host hook: a guard or body threw. `job.crash` is set; write the receipt
271
+ * the job's joiners read (a tool outcome, a call failure). The orchestrator
272
+ * completes the job right after.
273
+ */
274
+ protected stampCrash(_job: Job, _phase: "license" | "body", _detail: string): void {}
275
+
276
+ /** In-flight claimed Jobs (handler has not `finally`'d). */
277
+ protected inFlightJobs(): Iterable<Job> {
278
+ return this.#jobAbort.keys();
279
+ }
280
+
281
+ /** Abort an in-flight executor. No-op if the job is not claimed here. */
282
+ abortJob(job: Job, reason?: unknown): void {
283
+ this.#jobAbort.get(job)?.abort(reason);
284
+ }
285
+
286
+ readonly #connections = new Map<string, PEWDriver>();
287
+ readonly #classes = new DefaultedMap<string, Promise<DriverConnectionClass>>(this.#loadDriverClass.bind(this));
288
+ readonly #ensured = new DefaultedMap<string, Promise<PEWDriver>>(this.#ensureConnection.bind(this));
289
+
290
+ abstract loadDriverModule(driver: DriverSpec): Promise<DriverConnectionClass>;
291
+
292
+ /**
293
+ * Honor still `handle`s leftover attach PEW. Origin-dispatched completions
294
+ * return false (PR4). Default true unless the node is in {@link originCompletions}.
295
+ */
296
+ protected shouldHonor(node: WorkExpectation): boolean {
297
+ return !this.originCompletions.has(node);
298
+ }
299
+
300
+ /** Process-local. Secrets are never a Plexus field. */
301
+ protected connectionSecrets(_connectionId: string): ConnectionSecretsView {
302
+ return { get: () => undefined };
303
+ }
304
+
305
+ /** After bootstrap, before ensure settles. The session host binds the settings writer here. */
306
+ protected attachConnection(_connectionId: string, _instance: PEWDriver): void {}
307
+
308
+ connectionOf(expectation: WorkExpectation): PEWDriver | undefined {
309
+ return this.#connections.get(expectation.connectionId);
310
+ }
311
+
312
+ actorOf<T extends AnyWorkExpectation>(expectation: T): ExpectationActor<T> | undefined {
313
+ const connection = this.connectionOf(expectation);
314
+ if (!connection?.has(expectation)) return undefined;
315
+ return connection.resolveExpectation(expectation);
316
+ }
317
+
318
+ #loadDriverClass(driverName: string): Promise<DriverConnectionClass> {
319
+ return (async () => {
320
+ // JS: subclass fields (SessionOrchestrator.sessionDaemon) are unassigned during super().
321
+ await Promise.resolve();
322
+ const driver = this.drivers[driverName];
323
+ invariant(driver !== undefined, `unknown driver ${driverName}`);
324
+ try {
325
+ const cls = await this.loadDriverModule(driver);
326
+ invariant(isDriverConnectionClass(cls), "loadDriverModule: result is not a PEWDriver class");
327
+ // Occupancy is kernel-plane: interned connections outlive a session wrap.
328
+ cls.awareness = this.kernel.awareness;
329
+ cls.driverName = driverName;
330
+ const spec = this.drivers[driverName];
331
+ if (spec !== undefined) {
332
+ spec.stampLoad({
333
+ readyState: "ready",
334
+ error: "",
335
+ offersJson: JSON.stringify(cls.offers),
336
+ live: extraLiveFromState(cls.state),
337
+ });
338
+ // Offers are class state a driver may keep fresh (local detection). The
339
+ // reaction also holds the observation that wakes a lazy `cls.offers`.
340
+ this.#mirrorDisposers.push(
341
+ reaction(
342
+ () => toJS(cls.offers),
343
+ (offers) => {
344
+ if (!this.#disposed) spec.offers = offers;
345
+ },
346
+ { equals: comparer.structural },
347
+ ),
348
+ );
349
+ }
350
+ return cls;
351
+ } catch (error) {
352
+ const spec = this.drivers[driverName];
353
+ if (spec !== undefined) spec.stampLoad({ readyState: "failed", error: String(error) });
354
+ throw error;
355
+ }
356
+ })();
357
+ }
358
+
359
+ #ensureConnection(connectionId: string): Promise<PEWDriver> {
360
+ const pending = (async () => {
361
+ const driver = this.kernel.root.connections[connectionId]?.driver;
362
+ invariant(driver !== undefined, `unknown driver for connection ${connectionId}`);
363
+ const instance = await acquireConnection(this.kernel.root, this, connectionId, async () => {
364
+ const cls = await this.#classes.get(driver.name);
365
+ const minted = new cls(
366
+ connectionId,
367
+ // YAML: settings stamped onto the connection before ensure.
368
+ this.kernel.root.connections[connectionId]?.configuration ?? {},
369
+ this.connectionSecrets(connectionId),
370
+ );
371
+ action(() => {
372
+ minted.awareness = this.kernel.awareness; // kernel occupancy, not session
373
+ })();
374
+ return minted;
375
+ });
376
+ action(() => {
377
+ instance.awareness = this.kernel.awareness;
378
+ })();
379
+ this.#connections.set(connectionId, instance);
380
+ await instance.ensureBootstrapStarted();
381
+ this.attachConnection(connectionId, instance);
382
+ return instance;
383
+ })();
384
+ void pending.then(undefined, () => {});
385
+ return pending;
386
+ }
387
+
388
+ ensure(connectionId: string): Promise<PEWDriver> {
389
+ return this.#ensured.get(connectionId);
390
+ }
391
+
392
+ /** True once the connection memo has been poked — without poking it. */
393
+ protected isEnsured(connectionId: string): boolean {
394
+ return this.#ensured.has(connectionId);
395
+ }
396
+
397
+ /** Intern-owner remint. Deletes the sticky `#ensured` memo. */
398
+ forgetConnection(id: string): void {
399
+ this.#ensured.delete(id);
400
+ this.#connections.delete(id);
401
+ releaseConnection(this.kernel.root, this, id);
402
+ }
403
+
404
+ /** True after {@link activate}; constructor and registerExecutor do not honor. */
405
+ get activated(): boolean {
406
+ return this.#activated.get();
407
+ }
408
+
409
+ /**
410
+ * Start honor, Job claim, and driver discovery. Idempotent. No-op after
411
+ * park/dispose — those already stopped admission.
412
+ */
413
+ activate(): void {
414
+ if (this.#disposed || this.#admissionStopped) return;
415
+ action(() => {
416
+ this.#activated.set(true);
417
+ })();
418
+ }
419
+
420
+ /**
421
+ * Stop honor and new claim. In-flight BODY and live connections stay —
422
+ * park waits dispatched MCP before {@link Symbol.dispose} releases them.
423
+ */
424
+ protected stopAdmission(): void {
425
+ if (this.#admissionStopped) return;
426
+ this.#admissionStopped = true;
427
+ this.#disposeWork();
428
+ for (const dispose of this.#processes.values()) dispose();
429
+ this.#processes.clear();
430
+ for (const ac of this.#guardAbort.values()) ac.abort("park");
431
+ }
432
+
433
+ [Symbol.dispose](): void {
434
+ if (this.#disposed) return;
435
+ this.#disposed = true;
436
+ this.stopAdmission();
437
+ for (const ac of this.#jobAbort.values()) ac.abort();
438
+ for (const ac of this.#guardAbort.values()) ac.abort();
439
+ this.#disposeAborts();
440
+ this.#jobAbort.clear();
441
+ this.#guardAbort.clear();
442
+ for (const id of this.#connections.keys()) releaseConnection(this.kernel.root, this, id);
443
+ this.#connections.clear();
444
+ for (const dispose of this.#mirrorDisposers.splice(0)) dispose();
445
+ }
446
+
447
+ get drivers() {
448
+ return this.kernel.root.drivers;
449
+ }
450
+
451
+ get connections() {
452
+ return this.kernel.root.connections;
453
+ }
454
+ }
455
+
456
+ function collectReachable(root: unknown): Set<WorkExpectation> {
457
+ if (!(root instanceof WorkContainer)) return new Set();
458
+ const found = new Set<WorkExpectation>();
459
+ for (const node of walkWork(root)) {
460
+ if (node instanceof WorkExpectation) found.add(node);
461
+ }
462
+ return found;
463
+ }
@@ -0,0 +1,3 @@
1
+ export type Settlement<TResult> =
2
+ | { readonly outcome: "complete"; readonly result: TResult }
3
+ | { readonly outcome: "fail"; readonly reason: unknown };
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./shared/index.js";
@@ -0,0 +1,4 @@
1
+ import { z } from "zod";
2
+
3
+ export const pewConfigurationSchema = z.record(z.string(), z.unknown());
4
+ export const pewSecretsSchema = z.record(z.string(), z.unknown());
@@ -0,0 +1 @@
1
+ export * from "./connection.js";
@@ -0,0 +1,4 @@
1
+ /** `null` on the entity means not done. Cancel is `failed`, not a fourth state. */
2
+ export type ExpectationOutcome = "successful" | "failed";
3
+
4
+ export type EndCause = "settled" | "cancel" | "crash";
@@ -0,0 +1,6 @@
1
+ export * from "./models/index.js";
2
+ export * from "./revalidation-demand.js";
3
+ export * from "./control.js";
4
+ export * from "./map-field-awareness.js";
5
+ export * from "./role.js";
6
+ export * from "./types.js";
@@ -0,0 +1,65 @@
1
+ /**
2
+ * One awareness field as a string-keyed map.
3
+ *
4
+ * Each client owns its map. A write patches the local map. A read is the
5
+ * first present entry across bases, local then others, so a peer's key is
6
+ * visible here. `undefined` means the key is absent; `""` and `null` are
7
+ * stored values.
8
+ *
9
+ * Callers read and write through this lens. A process-local map misses
10
+ * every peer entry.
11
+ */
12
+ import {
13
+ FieldAwareness,
14
+ type AwarenessShape,
15
+ type PlexusAwareness,
16
+ type ShapeOfAwareness,
17
+ } from "@here.build/plexus";
18
+
19
+ export class MapFieldAwareness<
20
+ A extends PlexusAwareness<AwarenessShape> = PlexusAwareness,
21
+ K extends string & keyof ShapeOfAwareness<A> = string & keyof ShapeOfAwareness<A>,
22
+ > extends FieldAwareness<A, K> {
23
+ mapGet(key: string): unknown {
24
+ const own = readAt(this.get(), key);
25
+ if (own !== undefined) return own;
26
+ for (const id of this.clientIds) {
27
+ const value = readAt(this.getOther(id), key);
28
+ if (value !== undefined) return value;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ mapSet(key: string, value: unknown): void {
34
+ this.#write({ ...this.#record(), [key]: value });
35
+ }
36
+
37
+ mapDelete(key: string): void {
38
+ const current = this.#record();
39
+ if (!(key in current)) return;
40
+ delete current[key];
41
+ // An empty object is still a published value. The last delete leaves the lane null.
42
+ if (Object.keys(current).length === 0) this.clear();
43
+ else this.#write(current);
44
+ }
45
+
46
+ #record(): Record<string, unknown> {
47
+ const value = this.get();
48
+ if (!isRecord(value)) return {};
49
+ return { ...value };
50
+ }
51
+
52
+ /** `set` wants the lane's serializable value. The bag is a plain object. */
53
+ #write(bag: Record<string, unknown>): void {
54
+ this.set(bag as ShapeOfAwareness<A>[K]);
55
+ }
56
+ }
57
+
58
+ function isRecord(value: unknown): value is Record<string, unknown> {
59
+ return value !== null && typeof value === "object" && !Array.isArray(value);
60
+ }
61
+
62
+ function readAt(value: unknown, key: string): unknown {
63
+ if (!isRecord(value) || !(key in value)) return undefined;
64
+ return value[key];
65
+ }