@volter/twin 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 (82) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +68 -0
  3. package/dist/src/actions.d.ts +138 -0
  4. package/dist/src/actions.js +201 -0
  5. package/dist/src/args.d.ts +3 -0
  6. package/dist/src/args.js +12 -0
  7. package/dist/src/cli.d.ts +2 -0
  8. package/dist/src/cli.js +425 -0
  9. package/dist/src/connector.d.ts +106 -0
  10. package/dist/src/connector.js +129 -0
  11. package/dist/src/control-plane.d.ts +21 -0
  12. package/dist/src/control-plane.js +40 -0
  13. package/dist/src/egress.d.ts +93 -0
  14. package/dist/src/egress.js +264 -0
  15. package/dist/src/fork.d.ts +126 -0
  16. package/dist/src/fork.js +206 -0
  17. package/dist/src/index.d.ts +42 -0
  18. package/dist/src/index.js +52 -0
  19. package/dist/src/lease.d.ts +50 -0
  20. package/dist/src/lease.js +80 -0
  21. package/dist/src/packRegistry.d.ts +34 -0
  22. package/dist/src/packRegistry.js +22 -0
  23. package/dist/src/plan.d.ts +97 -0
  24. package/dist/src/plan.js +151 -0
  25. package/dist/src/proxy.d.ts +25 -0
  26. package/dist/src/proxy.js +152 -0
  27. package/dist/src/pushLedger.d.ts +81 -0
  28. package/dist/src/pushLedger.js +130 -0
  29. package/dist/src/queueLifecycle.d.ts +62 -0
  30. package/dist/src/queueLifecycle.js +95 -0
  31. package/dist/src/reconcile.d.ts +58 -0
  32. package/dist/src/reconcile.js +137 -0
  33. package/dist/src/refs.d.ts +29 -0
  34. package/dist/src/refs.js +68 -0
  35. package/dist/src/schemas.d.ts +78 -0
  36. package/dist/src/schemas.js +50 -0
  37. package/dist/src/serve.d.ts +44 -0
  38. package/dist/src/serve.js +93 -0
  39. package/dist/src/shadow.d.ts +77 -0
  40. package/dist/src/shadow.js +138 -0
  41. package/dist/src/status.d.ts +31 -0
  42. package/dist/src/status.js +42 -0
  43. package/dist/src/storage.d.ts +119 -0
  44. package/dist/src/storage.js +535 -0
  45. package/dist/src/sync.d.ts +91 -0
  46. package/dist/src/sync.js +121 -0
  47. package/dist/src/types.d.ts +40 -0
  48. package/dist/src/types.js +1 -0
  49. package/dist/src/validate.d.ts +27 -0
  50. package/dist/src/validate.js +68 -0
  51. package/dist/src/visualizer.d.ts +13 -0
  52. package/dist/src/visualizer.js +133 -0
  53. package/dist/src/worldConfig.d.ts +9 -0
  54. package/dist/src/worldConfig.js +16 -0
  55. package/inject.cjs +429 -0
  56. package/package.json +81 -0
  57. package/src/actions.ts +285 -0
  58. package/src/args.ts +14 -0
  59. package/src/cli.ts +443 -0
  60. package/src/connector.ts +220 -0
  61. package/src/control-plane.ts +66 -0
  62. package/src/egress.ts +355 -0
  63. package/src/fork.ts +256 -0
  64. package/src/index.ts +222 -0
  65. package/src/lease.ts +97 -0
  66. package/src/packRegistry.ts +60 -0
  67. package/src/plan.ts +190 -0
  68. package/src/proxy.ts +180 -0
  69. package/src/pushLedger.ts +189 -0
  70. package/src/queueLifecycle.ts +130 -0
  71. package/src/reconcile.ts +192 -0
  72. package/src/refs.ts +91 -0
  73. package/src/schemas.ts +56 -0
  74. package/src/serve.ts +120 -0
  75. package/src/shadow.ts +192 -0
  76. package/src/status.ts +58 -0
  77. package/src/storage.ts +632 -0
  78. package/src/sync.ts +160 -0
  79. package/src/types.ts +50 -0
  80. package/src/validate.ts +95 -0
  81. package/src/visualizer.ts +142 -0
  82. package/src/worldConfig.ts +26 -0
package/src/actions.ts ADDED
@@ -0,0 +1,285 @@
1
+ // Transaction/action log (scorecard R18) — the semantic correction that separates
2
+ // OBSERVED facts from LOCAL transaction commits.
3
+ //
4
+ // The observed-event log (`events.jsonl`) holds only what was observed upstream
5
+ // (connector pulls) or confirmed after a push. Local simulator/fork writes do NOT
6
+ // go there — they are transaction commits in `actions.jsonl`, projected OVER the
7
+ // observed mirror to produce the twin's current state. Undo is a `revert` commit;
8
+ // a push that succeeds appends a `confirm` commit mapping the local transaction
9
+ // to the observed event it produced, which SUPPRESSES the local projection (the
10
+ // fact is now carried by the observed log, so it must not be double-counted).
11
+ //
12
+ // Projection = observed mirror, then apply each `set` transaction in order,
13
+ // skipping any transaction that was reverted or confirmed.
14
+ import { randomUUID } from 'node:crypto';
15
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
16
+ import { dirname, join } from 'node:path';
17
+ import { buildShadowState } from './shadow.ts';
18
+ import type { SubjectFields } from './shadow.ts';
19
+ import { appendDurable, appendEvent, twinLog, withFileLock, worldPaths } from './storage.ts';
20
+ import type { WorldServiceEvent } from './types.ts';
21
+ import type { TwinResource } from './serve.ts';
22
+
23
+ export type TwinActionOp = 'set' | 'revert' | 'confirm';
24
+ export type TwinActionPreconditionOp = 'exists' | 'not_exists' | 'eq' | 'neq' | 'version_eq';
25
+ export type TwinActionPrecondition = {
26
+ subject: { type: string; id: string };
27
+ field: string;
28
+ op: TwinActionPreconditionOp;
29
+ value?: unknown;
30
+ };
31
+ export type TwinActionRevertSpec = {
32
+ strategy: 'inverse' | 'suppress' | 'compensating-action';
33
+ operation?: string;
34
+ fields?: SubjectFields;
35
+ };
36
+
37
+ // Multi-resource transaction projection (the twins architecture notes → "Local
38
+ // Transaction Commit Packet"). The flat single-subject `fields` overlay is the
39
+ // common shorthand; `projection` is the richer form for a transaction that
40
+ // atomically touches MORE THAN ONE resource (e.g. create a PR + a review), deletes
41
+ // a resource, or emits a delivery (webhook/notification) the twin should fire.
42
+ export type ProjectedResource = { type: string; id: string; fields: SubjectFields };
43
+ export type ProjectedResourcePatch = { type: string; id: string; fields: SubjectFields };
44
+ export type ProjectedResourceRef = { type: string; id: string };
45
+ export type ProjectedDelivery = { kind: 'webhook' | 'event' | 'notification'; target: string; payload: Record<string, unknown> };
46
+ export type ActionProjection = {
47
+ creates?: ProjectedResource[];
48
+ updates?: ProjectedResourcePatch[];
49
+ deletes?: ProjectedResourceRef[];
50
+ emits?: ProjectedDelivery[];
51
+ };
52
+
53
+ export type TwinAction = {
54
+ id: string;
55
+ service: string;
56
+ op: TwinActionOp;
57
+ subject: { type: string; id: string };
58
+ occurredAt: string;
59
+ actor?: { kind: 'agent' | 'human' | 'bot' | 'system'; id?: string };
60
+ /** Optional vendor operation name, e.g. `issue.update` or `message.send`. */
61
+ operation?: string;
62
+ /** Raw operation input (provenance); not projected — `fields`/`projection` carry the state change. */
63
+ input?: Record<string, unknown>;
64
+ /** Preconditions are evaluated against the current projected twin state before append. */
65
+ preconditions?: TwinActionPrecondition[];
66
+ // op 'set': the local field changes to overlay on `subject` (single-resource shorthand).
67
+ fields?: SubjectFields;
68
+ // op 'set': the richer multi-resource transaction projection (optional; composes with `fields`).
69
+ projection?: ActionProjection;
70
+ // op 'revert': the prior action id being undone.
71
+ revertsActionId?: string;
72
+ // op 'confirm': the prior action id now reflected as an observed event.
73
+ confirmsActionId?: string;
74
+ observedEventId?: string;
75
+ /** Optional machine-readable hint for how a UI/pack should construct a revert. */
76
+ revert?: TwinActionRevertSpec;
77
+ /**
78
+ * Request-scoped correlation id (D3 — the purpose-3 audit trail: "who reviewed the
79
+ * change that caused this real write"). Always present on an appended action —
80
+ * appendAction/appendActionIfAbsent generate one when the caller doesn't supply it —
81
+ * and threaded through to the push-ledger row(s) a push against this action produces
82
+ * (see pushLedger.ts), so an action row and its push-ledger row(s) join on this id
83
+ * alone, with no dependence on actionId/pushId naming conventions.
84
+ */
85
+ correlationId?: string;
86
+ };
87
+ export type TwinTransactionCommit = TwinAction;
88
+ export type TwinTransactionCommitOp = TwinActionOp;
89
+ export type TwinTransactionPrecondition = TwinActionPrecondition;
90
+ export type TwinTransactionRevertSpec = TwinActionRevertSpec;
91
+ export class TwinActionPreconditionError extends Error {
92
+ constructor(readonly actionId: string, readonly failed: TwinActionPrecondition) {
93
+ super(`Twin transaction precondition failed for ${actionId}: ${failed.subject.type}:${failed.subject.id}.${failed.field} ${failed.op}`);
94
+ this.name = 'TwinActionPreconditionError';
95
+ }
96
+ }
97
+
98
+ function actionsPath(service: string, root?: string): string {
99
+ return join(dirname(worldPaths(service, root).events), 'actions.jsonl');
100
+ }
101
+ const actionsLock = (service: string, root?: string): string => `${actionsPath(service, root)}.lock`;
102
+
103
+ /** Every appended action carries a correlationId — generate one when the caller
104
+ * hasn't supplied it, so downstream joins (push ledger, logs) always have an id
105
+ * to key on (D3). Preserves a caller-supplied id (e.g. propagated from an HTTP
106
+ * request id) so a whole call chain can share one. */
107
+ function withCorrelationId(action: TwinAction): TwinAction {
108
+ return action.correlationId ? action : { ...action, correlationId: randomUUID() };
109
+ }
110
+
111
+ function appendActionRaw(action: TwinAction, root?: string): void {
112
+ const path = actionsPath(action.service, root);
113
+ mkdirSync(dirname(path), { recursive: true });
114
+ appendDurable(path, `${JSON.stringify(action)}\n`);
115
+ twinLog('action.append', { service: action.service, id: action.id, op: action.op, correlationId: action.correlationId });
116
+ }
117
+
118
+ export function appendAction(action: TwinAction, root?: string): TwinAction {
119
+ const stamped = withCorrelationId(action);
120
+ assertPreconditions(stamped, root);
121
+ // Cross-process line-atomic append (same lock the dedup path uses, so writes from a
122
+ // backend + a browser proxy sharing one twin can't interleave or race a check-then-append).
123
+ withFileLock(actionsLock(stamped.service, root), () => appendActionRaw(stamped, root));
124
+ return stamped;
125
+ }
126
+
127
+ /** Append `action` only if no action with the same id already exists — the whole
128
+ * check-then-append runs under the actions lock, so it's atomic across processes (two
129
+ * concurrent identical writes converge to ONE action; distinct writes both land). */
130
+ export function appendActionIfAbsent(action: TwinAction, root?: string): { action: TwinAction; appended: boolean } {
131
+ const stamped = withCorrelationId(action);
132
+ assertPreconditions(stamped, root);
133
+ return withFileLock(actionsLock(stamped.service, root), () => {
134
+ const exists = listActions(stamped.service, root).some((a) => a.id === stamped.id);
135
+ if (!exists) appendActionRaw(stamped, root);
136
+ return { action: stamped, appended: !exists };
137
+ });
138
+ }
139
+
140
+ export function appendTransactionCommit(commit: TwinTransactionCommit, root?: string): TwinTransactionCommit {
141
+ return appendAction(commit, root);
142
+ }
143
+
144
+ export function listActions(service: string, root?: string): TwinAction[] {
145
+ const path = actionsPath(service, root);
146
+ if (!existsSync(path)) return [];
147
+ return readFileSync(path, 'utf8')
148
+ .split('\n')
149
+ .filter((line) => line.trim())
150
+ .map((line) => JSON.parse(line) as TwinAction);
151
+ }
152
+
153
+ const META = new Set(['id', 'type', 'updatedAt']);
154
+
155
+ function projectedField(resource: TwinResource | undefined, field: string): unknown {
156
+ if (!resource) return undefined;
157
+ if (field === 'id' || field === 'type' || field === 'updatedAt') return resource[field];
158
+ return resource[field];
159
+ }
160
+
161
+ function assertPreconditions(action: TwinAction, root?: string): void {
162
+ if (!action.preconditions?.length) return;
163
+ const resources = projectResources(action.service, root);
164
+ for (const precondition of action.preconditions) {
165
+ const resource = resources.find((r) => r.type === precondition.subject.type && r.id === precondition.subject.id);
166
+ const actual = projectedField(resource, precondition.field);
167
+ const passes =
168
+ precondition.op === 'exists' ? actual !== undefined
169
+ : precondition.op === 'not_exists' ? actual === undefined
170
+ : precondition.op === 'eq' || precondition.op === 'version_eq' ? Object.is(actual, precondition.value)
171
+ : precondition.op === 'neq' ? !Object.is(actual, precondition.value)
172
+ : false;
173
+ if (!passes) throw new TwinActionPreconditionError(action.id, precondition);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Project the action log over the observed mirror → current twin resources.
179
+ * `set` actions overlay fields (creating subjects that don't exist in the mirror);
180
+ * reverted and confirmed actions are skipped (confirmed facts come from the
181
+ * observed log instead, so they are not projected twice).
182
+ */
183
+ export function projectResources(service: string, root?: string): TwinResource[] {
184
+ // base: observed mirror (events.jsonl only)
185
+ const mirror = buildShadowState(service, () => null, root);
186
+ const subjects = new Map<string, { type: string; id: string; updatedAt: string; fields: SubjectFields }>();
187
+ for (const s of Object.values(mirror.subjects)) {
188
+ subjects.set(`${s.subject.type}:${s.subject.id}`, { type: s.subject.type, id: s.subject.id, updatedAt: s.updatedAt, fields: { ...s.fields } });
189
+ }
190
+
191
+ const actions = listActions(service, root);
192
+ const reverted = new Set<string>();
193
+ const confirmed = new Set<string>();
194
+ for (const a of actions) {
195
+ if (a.op === 'revert' && a.revertsActionId) reverted.add(a.revertsActionId);
196
+ if (a.op === 'confirm' && a.confirmsActionId) confirmed.add(a.confirmsActionId);
197
+ }
198
+
199
+ const overlay = (type: string, id: string, fields: SubjectFields, at: string): void => {
200
+ const key = `${type}:${id}`;
201
+ const existing = subjects.get(key) ?? { type, id, updatedAt: at, fields: {} };
202
+ subjects.set(key, { ...existing, updatedAt: at, fields: { ...existing.fields, ...fields } });
203
+ };
204
+
205
+ for (const a of actions) {
206
+ if (a.op !== 'set') continue;
207
+ if (reverted.has(a.id) || confirmed.has(a.id)) continue; // suppressed
208
+ // single-resource shorthand: overlay `fields` on the action's own subject.
209
+ if (a.fields) overlay(a.subject.type, a.subject.id, a.fields, a.occurredAt);
210
+ // richer multi-resource transaction projection (applied in order; deletes remove).
211
+ if (a.projection) {
212
+ for (const c of a.projection.creates ?? []) overlay(c.type, c.id, c.fields, a.occurredAt);
213
+ for (const u of a.projection.updates ?? []) overlay(u.type, u.id, u.fields, a.occurredAt);
214
+ for (const d of a.projection.deletes ?? []) subjects.delete(`${d.type}:${d.id}`);
215
+ }
216
+ }
217
+
218
+ return [...subjects.values()].map((s) => {
219
+ const out: Record<string, unknown> = { id: s.id, type: s.type, updatedAt: s.updatedAt };
220
+ for (const [k, v] of Object.entries(s.fields)) if (!META.has(k)) out[k] = v;
221
+ return out as TwinResource;
222
+ });
223
+ }
224
+
225
+ /**
226
+ * Confirm a local action after it was pushed to the real vendor (R18): record the
227
+ * confirmed fields as an OBSERVED event (origin 'external' — it's now real) and
228
+ * append a `confirm` action mapping the local action → that observed event id.
229
+ * Projection then drops the local action (the fact lives in the observed log), so
230
+ * the change is counted exactly once. Returns the observed event id.
231
+ */
232
+ export function confirmAction(opts: {
233
+ service: string;
234
+ actionId: string;
235
+ subject: { type: string; id: string };
236
+ fields: SubjectFields;
237
+ occurredAt: string;
238
+ root?: string;
239
+ }): { observedEventId: string } {
240
+ const observedEventId = `confirmed:${opts.service}:${opts.subject.type}:${opts.subject.id}:${opts.actionId}`;
241
+ appendEvent(
242
+ {
243
+ id: observedEventId,
244
+ service: opts.service,
245
+ type: `${opts.service}.${opts.subject.type}.delta`,
246
+ schemaVersion: 1,
247
+ idempotencyKey: observedEventId,
248
+ occurredAt: opts.occurredAt,
249
+ observedAt: opts.occurredAt,
250
+ origin: 'external', // confirmed by the real vendor → an observed fact
251
+ subject: opts.subject,
252
+ data: { changed: Object.fromEntries(Object.entries(opts.fields).map(([k, v]) => [k, { after: v }])) },
253
+ } as unknown as WorldServiceEvent,
254
+ opts.root,
255
+ );
256
+ appendAction(
257
+ { id: `confirm:${opts.actionId}`, service: opts.service, op: 'confirm', subject: opts.subject, occurredAt: opts.occurredAt, confirmsActionId: opts.actionId, observedEventId },
258
+ opts.root,
259
+ );
260
+ return { observedEventId };
261
+ }
262
+
263
+ /** Local pending actions (set, not reverted, not yet confirmed) — the divergence from the mirror. */
264
+ export function pendingActions(service: string, root?: string): TwinAction[] {
265
+ const actions = listActions(service, root);
266
+ const reverted = new Set(actions.filter((a) => a.op === 'revert').map((a) => a.revertsActionId));
267
+ const confirmed = new Set(actions.filter((a) => a.op === 'confirm').map((a) => a.confirmsActionId));
268
+ return actions.filter((a) => a.op === 'set' && !reverted.has(a.id) && !confirmed.has(a.id));
269
+ }
270
+
271
+ /**
272
+ * Deliveries (webhooks/events/notifications) the active transactions want fired —
273
+ * the `projection.emits` of pending `set` actions, in order. A twin's event layer
274
+ * reads these to know what to deliver; projecting state ignores emits (side effects).
275
+ */
276
+ export function pendingEmits(service: string, root?: string): Array<{ actionId: string; delivery: ProjectedDelivery }> {
277
+ const out: Array<{ actionId: string; delivery: ProjectedDelivery }> = [];
278
+ for (const a of pendingActions(service, root)) {
279
+ for (const d of a.projection?.emits ?? []) out.push({ actionId: a.id, delivery: d });
280
+ }
281
+ return out;
282
+ }
283
+
284
+ export const listTransactionCommits = listActions;
285
+ export const pendingTransactionCommits = pendingActions;
package/src/args.ts ADDED
@@ -0,0 +1,14 @@
1
+ // Shared CLI argument helpers for world scripts and tools. Scripts kept
2
+ // growing private copies of these (5 in the sync subsystem alone before this
3
+ // file); a parsing fix that lands in one copy and not the others corrupts
4
+ // flag handling silently.
5
+
6
+ /** Value of `--name <value>`; fallback when the flag is absent or has no value. */
7
+ export function optionValue(args: string[], name: string, fallback = ''): string {
8
+ const index = args.indexOf(name);
9
+ return index >= 0 && index + 1 < args.length ? args[index + 1]! : fallback;
10
+ }
11
+
12
+ export function hasFlag(args: string[], name: string): boolean {
13
+ return args.includes(name);
14
+ }