@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.
- package/LICENSE +202 -0
- package/README.md +68 -0
- package/dist/src/actions.d.ts +138 -0
- package/dist/src/actions.js +201 -0
- package/dist/src/args.d.ts +3 -0
- package/dist/src/args.js +12 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +425 -0
- package/dist/src/connector.d.ts +106 -0
- package/dist/src/connector.js +129 -0
- package/dist/src/control-plane.d.ts +21 -0
- package/dist/src/control-plane.js +40 -0
- package/dist/src/egress.d.ts +93 -0
- package/dist/src/egress.js +264 -0
- package/dist/src/fork.d.ts +126 -0
- package/dist/src/fork.js +206 -0
- package/dist/src/index.d.ts +42 -0
- package/dist/src/index.js +52 -0
- package/dist/src/lease.d.ts +50 -0
- package/dist/src/lease.js +80 -0
- package/dist/src/packRegistry.d.ts +34 -0
- package/dist/src/packRegistry.js +22 -0
- package/dist/src/plan.d.ts +97 -0
- package/dist/src/plan.js +151 -0
- package/dist/src/proxy.d.ts +25 -0
- package/dist/src/proxy.js +152 -0
- package/dist/src/pushLedger.d.ts +81 -0
- package/dist/src/pushLedger.js +130 -0
- package/dist/src/queueLifecycle.d.ts +62 -0
- package/dist/src/queueLifecycle.js +95 -0
- package/dist/src/reconcile.d.ts +58 -0
- package/dist/src/reconcile.js +137 -0
- package/dist/src/refs.d.ts +29 -0
- package/dist/src/refs.js +68 -0
- package/dist/src/schemas.d.ts +78 -0
- package/dist/src/schemas.js +50 -0
- package/dist/src/serve.d.ts +44 -0
- package/dist/src/serve.js +93 -0
- package/dist/src/shadow.d.ts +77 -0
- package/dist/src/shadow.js +138 -0
- package/dist/src/status.d.ts +31 -0
- package/dist/src/status.js +42 -0
- package/dist/src/storage.d.ts +119 -0
- package/dist/src/storage.js +535 -0
- package/dist/src/sync.d.ts +91 -0
- package/dist/src/sync.js +121 -0
- package/dist/src/types.d.ts +40 -0
- package/dist/src/types.js +1 -0
- package/dist/src/validate.d.ts +27 -0
- package/dist/src/validate.js +68 -0
- package/dist/src/visualizer.d.ts +13 -0
- package/dist/src/visualizer.js +133 -0
- package/dist/src/worldConfig.d.ts +9 -0
- package/dist/src/worldConfig.js +16 -0
- package/inject.cjs +429 -0
- package/package.json +81 -0
- package/src/actions.ts +285 -0
- package/src/args.ts +14 -0
- package/src/cli.ts +443 -0
- package/src/connector.ts +220 -0
- package/src/control-plane.ts +66 -0
- package/src/egress.ts +355 -0
- package/src/fork.ts +256 -0
- package/src/index.ts +222 -0
- package/src/lease.ts +97 -0
- package/src/packRegistry.ts +60 -0
- package/src/plan.ts +190 -0
- package/src/proxy.ts +180 -0
- package/src/pushLedger.ts +189 -0
- package/src/queueLifecycle.ts +130 -0
- package/src/reconcile.ts +192 -0
- package/src/refs.ts +91 -0
- package/src/schemas.ts +56 -0
- package/src/serve.ts +120 -0
- package/src/shadow.ts +192 -0
- package/src/status.ts +58 -0
- package/src/storage.ts +632 -0
- package/src/sync.ts +160 -0
- package/src/types.ts +50 -0
- package/src/validate.ts +95 -0
- package/src/visualizer.ts +142 -0
- package/src/worldConfig.ts +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# @volter/twin
|
|
2
|
+
|
|
3
|
+
The kernel + control plane that the vendor twins build on. It is the shared layer of
|
|
4
|
+
the **twins** project: the uniform way every twin is *driven* (the `controlPlane`
|
|
5
|
+
namespace), plus the optional data-plane libraries a twin may reuse. It does **not**
|
|
6
|
+
make twins implement their vendor alike — each `@volter/twin-<vendor>` pack presents
|
|
7
|
+
its own vendor's exact API on top of this. CLI: `volter-twin`.
|
|
8
|
+
|
|
9
|
+
## The model
|
|
10
|
+
|
|
11
|
+
- **Events** (`events.jsonl`): append-only, idempotency-keyed observations — facts
|
|
12
|
+
pulled or confirmed from the real vendor. Replays append nothing; conflicting
|
|
13
|
+
payloads under one key throw.
|
|
14
|
+
- **Actions / transaction commits** (`actions.jsonl`): append-only local writes. They
|
|
15
|
+
project into visible state but do not pollute the observed-event log; undo is a
|
|
16
|
+
later revert/cancel commit.
|
|
17
|
+
- **Projected state**: a twin's read model is `fold(events) + apply(active actions)`,
|
|
18
|
+
suppressing a local projection once a push is confirmed by an observed vendor event.
|
|
19
|
+
- **Push / egress ledger**: selected local actions are replicated to the real vendor
|
|
20
|
+
idempotently; the ledger records action → attempt/result → confirmation.
|
|
21
|
+
- **Shadow state + deltas**: pollers fold the event log into per-subject field state
|
|
22
|
+
and append only changed fields.
|
|
23
|
+
- **Connectors** (`runConnectorPoll` / `runConnectorSweep`): cursor/subject poll
|
|
24
|
+
runners owning the sync invariants.
|
|
25
|
+
- **Control plane** (the `controlPlane` namespace): `status`, `plan`, push (+ phases),
|
|
26
|
+
`lease`, refs/checkpoints, the queue lifecycle, and fork operations
|
|
27
|
+
(rebase/merge/cherry-pick/revert/reset) — the one uniform surface for driving any
|
|
28
|
+
twin.
|
|
29
|
+
- **Validation** (`volter-twin validate` / `validateWorld`): twin integrity — egress
|
|
30
|
+
reconciliation + schema conformance.
|
|
31
|
+
|
|
32
|
+
One twin, three operations (not "modes"): **pull** reality, **write** local actions
|
|
33
|
+
(unless started read-only), **fork** the local commits — like `pull`/`commit`/`branch`
|
|
34
|
+
on a repo. The on-disk state is a "world" (a synchronized set of twins).
|
|
35
|
+
|
|
36
|
+
## CLI (`volter-twin`)
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
volter-twin events append <service> --file evt.json # append an observed event
|
|
40
|
+
volter-twin events list <service> --json
|
|
41
|
+
volter-twin state rebuild <service> # rebuild projected state from events
|
|
42
|
+
volter-twin status <service> # queued/unpushed/drift/conflicts
|
|
43
|
+
volter-twin plan <service> # reviewable apply plan
|
|
44
|
+
volter-twin refs <service> # remote checkpoints
|
|
45
|
+
volter-twin validate [--services <a,b>] # twin integrity (egress reconciliation)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
State lives under `<cwd>/.volter/world/` by default (directory name overridable via
|
|
49
|
+
`VOLTER_STATE_DIR`, or pass `--root`); per-service config in `.volter/world/config.json`.
|
|
50
|
+
**Pin a `--root` / `VOLTER_STATE_DIR` in CI** so a twin doesn't write into your repo.
|
|
51
|
+
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
`listEvents`, `appendEvent`, `createEvent`, `loadState`, `rebuildGenericState`,
|
|
55
|
+
`buildShadowState`, `recordObservedDelta`, `performExternalWrite`, `recordWriteIntent`,
|
|
56
|
+
`listEgressLedger`, `validateWorld`, `runConnectorPoll`, `createTwinServer`,
|
|
57
|
+
`applyTwinWrite`, `loadWorldConfig`, plus the `controlPlane` namespace and the optional
|
|
58
|
+
`queryHelpers` / `recordedDiff` / `derive` / pack-registry libraries. See `src/index.ts`.
|
|
59
|
+
|
|
60
|
+
(Annotations + source books are a *tracker* concern, not a twin one:
|
|
61
|
+
`@volter/tracker/world-annotations`, `@volter/tracker/world-source-books`.)
|
|
62
|
+
|
|
63
|
+
## The vendor twins
|
|
64
|
+
|
|
65
|
+
Each vendor's twin is its own modular package that `peerDepends` on `@volter/twin`:
|
|
66
|
+
`@volter/twin-stripe`, `@volter/twin-linear`, `@volter/twin-jira`,
|
|
67
|
+
`@volter/twin-github`, `@volter/twin-slack` (at `packages/twin/<vendor>`), each with its
|
|
68
|
+
own `world-<vendor>` CLI (`serve` / `mirror` / `conformance`) and React UI mirror.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { SubjectFields } from './shadow.js';
|
|
2
|
+
import type { TwinResource } from './serve.js';
|
|
3
|
+
export type TwinActionOp = 'set' | 'revert' | 'confirm';
|
|
4
|
+
export type TwinActionPreconditionOp = 'exists' | 'not_exists' | 'eq' | 'neq' | 'version_eq';
|
|
5
|
+
export type TwinActionPrecondition = {
|
|
6
|
+
subject: {
|
|
7
|
+
type: string;
|
|
8
|
+
id: string;
|
|
9
|
+
};
|
|
10
|
+
field: string;
|
|
11
|
+
op: TwinActionPreconditionOp;
|
|
12
|
+
value?: unknown;
|
|
13
|
+
};
|
|
14
|
+
export type TwinActionRevertSpec = {
|
|
15
|
+
strategy: 'inverse' | 'suppress' | 'compensating-action';
|
|
16
|
+
operation?: string;
|
|
17
|
+
fields?: SubjectFields;
|
|
18
|
+
};
|
|
19
|
+
export type ProjectedResource = {
|
|
20
|
+
type: string;
|
|
21
|
+
id: string;
|
|
22
|
+
fields: SubjectFields;
|
|
23
|
+
};
|
|
24
|
+
export type ProjectedResourcePatch = {
|
|
25
|
+
type: string;
|
|
26
|
+
id: string;
|
|
27
|
+
fields: SubjectFields;
|
|
28
|
+
};
|
|
29
|
+
export type ProjectedResourceRef = {
|
|
30
|
+
type: string;
|
|
31
|
+
id: string;
|
|
32
|
+
};
|
|
33
|
+
export type ProjectedDelivery = {
|
|
34
|
+
kind: 'webhook' | 'event' | 'notification';
|
|
35
|
+
target: string;
|
|
36
|
+
payload: Record<string, unknown>;
|
|
37
|
+
};
|
|
38
|
+
export type ActionProjection = {
|
|
39
|
+
creates?: ProjectedResource[];
|
|
40
|
+
updates?: ProjectedResourcePatch[];
|
|
41
|
+
deletes?: ProjectedResourceRef[];
|
|
42
|
+
emits?: ProjectedDelivery[];
|
|
43
|
+
};
|
|
44
|
+
export type TwinAction = {
|
|
45
|
+
id: string;
|
|
46
|
+
service: string;
|
|
47
|
+
op: TwinActionOp;
|
|
48
|
+
subject: {
|
|
49
|
+
type: string;
|
|
50
|
+
id: string;
|
|
51
|
+
};
|
|
52
|
+
occurredAt: string;
|
|
53
|
+
actor?: {
|
|
54
|
+
kind: 'agent' | 'human' | 'bot' | 'system';
|
|
55
|
+
id?: string;
|
|
56
|
+
};
|
|
57
|
+
/** Optional vendor operation name, e.g. `issue.update` or `message.send`. */
|
|
58
|
+
operation?: string;
|
|
59
|
+
/** Raw operation input (provenance); not projected — `fields`/`projection` carry the state change. */
|
|
60
|
+
input?: Record<string, unknown>;
|
|
61
|
+
/** Preconditions are evaluated against the current projected twin state before append. */
|
|
62
|
+
preconditions?: TwinActionPrecondition[];
|
|
63
|
+
fields?: SubjectFields;
|
|
64
|
+
projection?: ActionProjection;
|
|
65
|
+
revertsActionId?: string;
|
|
66
|
+
confirmsActionId?: string;
|
|
67
|
+
observedEventId?: string;
|
|
68
|
+
/** Optional machine-readable hint for how a UI/pack should construct a revert. */
|
|
69
|
+
revert?: TwinActionRevertSpec;
|
|
70
|
+
/**
|
|
71
|
+
* Request-scoped correlation id (D3 — the purpose-3 audit trail: "who reviewed the
|
|
72
|
+
* change that caused this real write"). Always present on an appended action —
|
|
73
|
+
* appendAction/appendActionIfAbsent generate one when the caller doesn't supply it —
|
|
74
|
+
* and threaded through to the push-ledger row(s) a push against this action produces
|
|
75
|
+
* (see pushLedger.ts), so an action row and its push-ledger row(s) join on this id
|
|
76
|
+
* alone, with no dependence on actionId/pushId naming conventions.
|
|
77
|
+
*/
|
|
78
|
+
correlationId?: string;
|
|
79
|
+
};
|
|
80
|
+
export type TwinTransactionCommit = TwinAction;
|
|
81
|
+
export type TwinTransactionCommitOp = TwinActionOp;
|
|
82
|
+
export type TwinTransactionPrecondition = TwinActionPrecondition;
|
|
83
|
+
export type TwinTransactionRevertSpec = TwinActionRevertSpec;
|
|
84
|
+
export declare class TwinActionPreconditionError extends Error {
|
|
85
|
+
readonly actionId: string;
|
|
86
|
+
readonly failed: TwinActionPrecondition;
|
|
87
|
+
constructor(actionId: string, failed: TwinActionPrecondition);
|
|
88
|
+
}
|
|
89
|
+
export declare function appendAction(action: TwinAction, root?: string): TwinAction;
|
|
90
|
+
/** Append `action` only if no action with the same id already exists — the whole
|
|
91
|
+
* check-then-append runs under the actions lock, so it's atomic across processes (two
|
|
92
|
+
* concurrent identical writes converge to ONE action; distinct writes both land). */
|
|
93
|
+
export declare function appendActionIfAbsent(action: TwinAction, root?: string): {
|
|
94
|
+
action: TwinAction;
|
|
95
|
+
appended: boolean;
|
|
96
|
+
};
|
|
97
|
+
export declare function appendTransactionCommit(commit: TwinTransactionCommit, root?: string): TwinTransactionCommit;
|
|
98
|
+
export declare function listActions(service: string, root?: string): TwinAction[];
|
|
99
|
+
/**
|
|
100
|
+
* Project the action log over the observed mirror → current twin resources.
|
|
101
|
+
* `set` actions overlay fields (creating subjects that don't exist in the mirror);
|
|
102
|
+
* reverted and confirmed actions are skipped (confirmed facts come from the
|
|
103
|
+
* observed log instead, so they are not projected twice).
|
|
104
|
+
*/
|
|
105
|
+
export declare function projectResources(service: string, root?: string): TwinResource[];
|
|
106
|
+
/**
|
|
107
|
+
* Confirm a local action after it was pushed to the real vendor (R18): record the
|
|
108
|
+
* confirmed fields as an OBSERVED event (origin 'external' — it's now real) and
|
|
109
|
+
* append a `confirm` action mapping the local action → that observed event id.
|
|
110
|
+
* Projection then drops the local action (the fact lives in the observed log), so
|
|
111
|
+
* the change is counted exactly once. Returns the observed event id.
|
|
112
|
+
*/
|
|
113
|
+
export declare function confirmAction(opts: {
|
|
114
|
+
service: string;
|
|
115
|
+
actionId: string;
|
|
116
|
+
subject: {
|
|
117
|
+
type: string;
|
|
118
|
+
id: string;
|
|
119
|
+
};
|
|
120
|
+
fields: SubjectFields;
|
|
121
|
+
occurredAt: string;
|
|
122
|
+
root?: string;
|
|
123
|
+
}): {
|
|
124
|
+
observedEventId: string;
|
|
125
|
+
};
|
|
126
|
+
/** Local pending actions (set, not reverted, not yet confirmed) — the divergence from the mirror. */
|
|
127
|
+
export declare function pendingActions(service: string, root?: string): TwinAction[];
|
|
128
|
+
/**
|
|
129
|
+
* Deliveries (webhooks/events/notifications) the active transactions want fired —
|
|
130
|
+
* the `projection.emits` of pending `set` actions, in order. A twin's event layer
|
|
131
|
+
* reads these to know what to deliver; projecting state ignores emits (side effects).
|
|
132
|
+
*/
|
|
133
|
+
export declare function pendingEmits(service: string, root?: string): Array<{
|
|
134
|
+
actionId: string;
|
|
135
|
+
delivery: ProjectedDelivery;
|
|
136
|
+
}>;
|
|
137
|
+
export declare const listTransactionCommits: typeof listActions;
|
|
138
|
+
export declare const pendingTransactionCommits: typeof pendingActions;
|
|
@@ -0,0 +1,201 @@
|
|
|
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.js";
|
|
18
|
+
import { appendDurable, appendEvent, twinLog, withFileLock, worldPaths } from "./storage.js";
|
|
19
|
+
export class TwinActionPreconditionError extends Error {
|
|
20
|
+
actionId;
|
|
21
|
+
failed;
|
|
22
|
+
constructor(actionId, failed) {
|
|
23
|
+
super(`Twin transaction precondition failed for ${actionId}: ${failed.subject.type}:${failed.subject.id}.${failed.field} ${failed.op}`);
|
|
24
|
+
this.actionId = actionId;
|
|
25
|
+
this.failed = failed;
|
|
26
|
+
this.name = 'TwinActionPreconditionError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function actionsPath(service, root) {
|
|
30
|
+
return join(dirname(worldPaths(service, root).events), 'actions.jsonl');
|
|
31
|
+
}
|
|
32
|
+
const actionsLock = (service, root) => `${actionsPath(service, root)}.lock`;
|
|
33
|
+
/** Every appended action carries a correlationId — generate one when the caller
|
|
34
|
+
* hasn't supplied it, so downstream joins (push ledger, logs) always have an id
|
|
35
|
+
* to key on (D3). Preserves a caller-supplied id (e.g. propagated from an HTTP
|
|
36
|
+
* request id) so a whole call chain can share one. */
|
|
37
|
+
function withCorrelationId(action) {
|
|
38
|
+
return action.correlationId ? action : { ...action, correlationId: randomUUID() };
|
|
39
|
+
}
|
|
40
|
+
function appendActionRaw(action, root) {
|
|
41
|
+
const path = actionsPath(action.service, root);
|
|
42
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
43
|
+
appendDurable(path, `${JSON.stringify(action)}\n`);
|
|
44
|
+
twinLog('action.append', { service: action.service, id: action.id, op: action.op, correlationId: action.correlationId });
|
|
45
|
+
}
|
|
46
|
+
export function appendAction(action, root) {
|
|
47
|
+
const stamped = withCorrelationId(action);
|
|
48
|
+
assertPreconditions(stamped, root);
|
|
49
|
+
// Cross-process line-atomic append (same lock the dedup path uses, so writes from a
|
|
50
|
+
// backend + a browser proxy sharing one twin can't interleave or race a check-then-append).
|
|
51
|
+
withFileLock(actionsLock(stamped.service, root), () => appendActionRaw(stamped, root));
|
|
52
|
+
return stamped;
|
|
53
|
+
}
|
|
54
|
+
/** Append `action` only if no action with the same id already exists — the whole
|
|
55
|
+
* check-then-append runs under the actions lock, so it's atomic across processes (two
|
|
56
|
+
* concurrent identical writes converge to ONE action; distinct writes both land). */
|
|
57
|
+
export function appendActionIfAbsent(action, root) {
|
|
58
|
+
const stamped = withCorrelationId(action);
|
|
59
|
+
assertPreconditions(stamped, root);
|
|
60
|
+
return withFileLock(actionsLock(stamped.service, root), () => {
|
|
61
|
+
const exists = listActions(stamped.service, root).some((a) => a.id === stamped.id);
|
|
62
|
+
if (!exists)
|
|
63
|
+
appendActionRaw(stamped, root);
|
|
64
|
+
return { action: stamped, appended: !exists };
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export function appendTransactionCommit(commit, root) {
|
|
68
|
+
return appendAction(commit, root);
|
|
69
|
+
}
|
|
70
|
+
export function listActions(service, root) {
|
|
71
|
+
const path = actionsPath(service, root);
|
|
72
|
+
if (!existsSync(path))
|
|
73
|
+
return [];
|
|
74
|
+
return readFileSync(path, 'utf8')
|
|
75
|
+
.split('\n')
|
|
76
|
+
.filter((line) => line.trim())
|
|
77
|
+
.map((line) => JSON.parse(line));
|
|
78
|
+
}
|
|
79
|
+
const META = new Set(['id', 'type', 'updatedAt']);
|
|
80
|
+
function projectedField(resource, field) {
|
|
81
|
+
if (!resource)
|
|
82
|
+
return undefined;
|
|
83
|
+
if (field === 'id' || field === 'type' || field === 'updatedAt')
|
|
84
|
+
return resource[field];
|
|
85
|
+
return resource[field];
|
|
86
|
+
}
|
|
87
|
+
function assertPreconditions(action, root) {
|
|
88
|
+
if (!action.preconditions?.length)
|
|
89
|
+
return;
|
|
90
|
+
const resources = projectResources(action.service, root);
|
|
91
|
+
for (const precondition of action.preconditions) {
|
|
92
|
+
const resource = resources.find((r) => r.type === precondition.subject.type && r.id === precondition.subject.id);
|
|
93
|
+
const actual = projectedField(resource, precondition.field);
|
|
94
|
+
const passes = precondition.op === 'exists' ? actual !== undefined
|
|
95
|
+
: precondition.op === 'not_exists' ? actual === undefined
|
|
96
|
+
: precondition.op === 'eq' || precondition.op === 'version_eq' ? Object.is(actual, precondition.value)
|
|
97
|
+
: precondition.op === 'neq' ? !Object.is(actual, precondition.value)
|
|
98
|
+
: false;
|
|
99
|
+
if (!passes)
|
|
100
|
+
throw new TwinActionPreconditionError(action.id, precondition);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Project the action log over the observed mirror → current twin resources.
|
|
105
|
+
* `set` actions overlay fields (creating subjects that don't exist in the mirror);
|
|
106
|
+
* reverted and confirmed actions are skipped (confirmed facts come from the
|
|
107
|
+
* observed log instead, so they are not projected twice).
|
|
108
|
+
*/
|
|
109
|
+
export function projectResources(service, root) {
|
|
110
|
+
// base: observed mirror (events.jsonl only)
|
|
111
|
+
const mirror = buildShadowState(service, () => null, root);
|
|
112
|
+
const subjects = new Map();
|
|
113
|
+
for (const s of Object.values(mirror.subjects)) {
|
|
114
|
+
subjects.set(`${s.subject.type}:${s.subject.id}`, { type: s.subject.type, id: s.subject.id, updatedAt: s.updatedAt, fields: { ...s.fields } });
|
|
115
|
+
}
|
|
116
|
+
const actions = listActions(service, root);
|
|
117
|
+
const reverted = new Set();
|
|
118
|
+
const confirmed = new Set();
|
|
119
|
+
for (const a of actions) {
|
|
120
|
+
if (a.op === 'revert' && a.revertsActionId)
|
|
121
|
+
reverted.add(a.revertsActionId);
|
|
122
|
+
if (a.op === 'confirm' && a.confirmsActionId)
|
|
123
|
+
confirmed.add(a.confirmsActionId);
|
|
124
|
+
}
|
|
125
|
+
const overlay = (type, id, fields, at) => {
|
|
126
|
+
const key = `${type}:${id}`;
|
|
127
|
+
const existing = subjects.get(key) ?? { type, id, updatedAt: at, fields: {} };
|
|
128
|
+
subjects.set(key, { ...existing, updatedAt: at, fields: { ...existing.fields, ...fields } });
|
|
129
|
+
};
|
|
130
|
+
for (const a of actions) {
|
|
131
|
+
if (a.op !== 'set')
|
|
132
|
+
continue;
|
|
133
|
+
if (reverted.has(a.id) || confirmed.has(a.id))
|
|
134
|
+
continue; // suppressed
|
|
135
|
+
// single-resource shorthand: overlay `fields` on the action's own subject.
|
|
136
|
+
if (a.fields)
|
|
137
|
+
overlay(a.subject.type, a.subject.id, a.fields, a.occurredAt);
|
|
138
|
+
// richer multi-resource transaction projection (applied in order; deletes remove).
|
|
139
|
+
if (a.projection) {
|
|
140
|
+
for (const c of a.projection.creates ?? [])
|
|
141
|
+
overlay(c.type, c.id, c.fields, a.occurredAt);
|
|
142
|
+
for (const u of a.projection.updates ?? [])
|
|
143
|
+
overlay(u.type, u.id, u.fields, a.occurredAt);
|
|
144
|
+
for (const d of a.projection.deletes ?? [])
|
|
145
|
+
subjects.delete(`${d.type}:${d.id}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return [...subjects.values()].map((s) => {
|
|
149
|
+
const out = { id: s.id, type: s.type, updatedAt: s.updatedAt };
|
|
150
|
+
for (const [k, v] of Object.entries(s.fields))
|
|
151
|
+
if (!META.has(k))
|
|
152
|
+
out[k] = v;
|
|
153
|
+
return out;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Confirm a local action after it was pushed to the real vendor (R18): record the
|
|
158
|
+
* confirmed fields as an OBSERVED event (origin 'external' — it's now real) and
|
|
159
|
+
* append a `confirm` action mapping the local action → that observed event id.
|
|
160
|
+
* Projection then drops the local action (the fact lives in the observed log), so
|
|
161
|
+
* the change is counted exactly once. Returns the observed event id.
|
|
162
|
+
*/
|
|
163
|
+
export function confirmAction(opts) {
|
|
164
|
+
const observedEventId = `confirmed:${opts.service}:${opts.subject.type}:${opts.subject.id}:${opts.actionId}`;
|
|
165
|
+
appendEvent({
|
|
166
|
+
id: observedEventId,
|
|
167
|
+
service: opts.service,
|
|
168
|
+
type: `${opts.service}.${opts.subject.type}.delta`,
|
|
169
|
+
schemaVersion: 1,
|
|
170
|
+
idempotencyKey: observedEventId,
|
|
171
|
+
occurredAt: opts.occurredAt,
|
|
172
|
+
observedAt: opts.occurredAt,
|
|
173
|
+
origin: 'external', // confirmed by the real vendor → an observed fact
|
|
174
|
+
subject: opts.subject,
|
|
175
|
+
data: { changed: Object.fromEntries(Object.entries(opts.fields).map(([k, v]) => [k, { after: v }])) },
|
|
176
|
+
}, opts.root);
|
|
177
|
+
appendAction({ id: `confirm:${opts.actionId}`, service: opts.service, op: 'confirm', subject: opts.subject, occurredAt: opts.occurredAt, confirmsActionId: opts.actionId, observedEventId }, opts.root);
|
|
178
|
+
return { observedEventId };
|
|
179
|
+
}
|
|
180
|
+
/** Local pending actions (set, not reverted, not yet confirmed) — the divergence from the mirror. */
|
|
181
|
+
export function pendingActions(service, root) {
|
|
182
|
+
const actions = listActions(service, root);
|
|
183
|
+
const reverted = new Set(actions.filter((a) => a.op === 'revert').map((a) => a.revertsActionId));
|
|
184
|
+
const confirmed = new Set(actions.filter((a) => a.op === 'confirm').map((a) => a.confirmsActionId));
|
|
185
|
+
return actions.filter((a) => a.op === 'set' && !reverted.has(a.id) && !confirmed.has(a.id));
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Deliveries (webhooks/events/notifications) the active transactions want fired —
|
|
189
|
+
* the `projection.emits` of pending `set` actions, in order. A twin's event layer
|
|
190
|
+
* reads these to know what to deliver; projecting state ignores emits (side effects).
|
|
191
|
+
*/
|
|
192
|
+
export function pendingEmits(service, root) {
|
|
193
|
+
const out = [];
|
|
194
|
+
for (const a of pendingActions(service, root)) {
|
|
195
|
+
for (const d of a.projection?.emits ?? [])
|
|
196
|
+
out.push({ actionId: a.id, delivery: d });
|
|
197
|
+
}
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
export const listTransactionCommits = listActions;
|
|
201
|
+
export const pendingTransactionCommits = pendingActions;
|
package/dist/src/args.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
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
|
+
/** Value of `--name <value>`; fallback when the flag is absent or has no value. */
|
|
6
|
+
export function optionValue(args, name, fallback = '') {
|
|
7
|
+
const index = args.indexOf(name);
|
|
8
|
+
return index >= 0 && index + 1 < args.length ? args[index + 1] : fallback;
|
|
9
|
+
}
|
|
10
|
+
export function hasFlag(args, name) {
|
|
11
|
+
return args.includes(name);
|
|
12
|
+
}
|