@loomwork/compliance 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Loom
2
+ Copyright 2026 Sushil Chhetri
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this project except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @loomwork/compliance — data-subject export and erasure
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tooling for GDPR and CCPA style requests, built on the fact that the event log already holds everything
4
+ about a person. A **subject index** maps a subject id to the executions that concern them, `exportSubject`
5
+ assembles an access and portability package (Art. 15 and 20), and `EraseCoordinator` handles erasure
6
+ (Art. 17) by destroying the subject's encryption key so their sensitive fields cannot be read, and by
7
+ deleting copies the key does not cover (archived segments, claim-checked blobs, inbox streams). It is
8
+ compliance-enabling tooling, not legal advice, and the kernel itself has no notion of a "data subject":
9
+ you supply a `subjectOf` resolver. In an app you use it through `defineConfig` (`security.compliance`),
10
+ which exposes `app.subjectIndex`, `app.exportSubject` and `app.eraseSubject`. The full erasure behaviour is
11
+ in [docs/compliance.md](../../docs/compliance.md).
12
+
13
+ ```ts
14
+ import { defineConfig } from "@loomwork/app";
15
+ import { helloFlow } from "./config"; // a flow whose input is { name }
16
+
17
+ const app = defineConfig({
18
+ storage: { kind: "memory" },
19
+ flows: [helloFlow],
20
+ security: {
21
+ compliance: {
22
+ // Name the subject an event concerns, or return undefined.
23
+ subjectOf: (e) =>
24
+ e.eventType === "EXECUTION_STARTED"
25
+ ? (e.payload as { input?: { name?: string } }).input?.name
26
+ : undefined,
27
+ },
28
+ // Compliance refuses to compose unless the log is kept free of a principal's identity:
29
+ // pass `security.crypto`, or a codec that records an opaque ref. This one records nothing.
30
+ principalCodec: { toRef: () => undefined, fromRef: () => undefined },
31
+ },
32
+ });
33
+
34
+ const handle = await app.runtime.start(helloFlow, { name: "ada" });
35
+ await handle.waitForCompletion();
36
+
37
+ app.subjectIndex?.executionsOf("ada"); // ["<execution id>"]
38
+ const pkg = await app.exportSubject("ada"); // Art. 15 / 20: folded state and raw events per execution
39
+ console.log(pkg.executions.length); // 1
40
+ // app.eraseSubject("ada") also needs security.compliance.erase.shred; see docs/compliance.md
41
+ await app.close();
42
+ ```
43
+
44
+ ## Surface
45
+
46
+ - **Index.** `SubjectIndex` (`SubjectIndex.fromEvents(events, subjectOf)` rebuilds it from a cold log),
47
+ `SubjectResolver`, `TenantResolver`, `DEFAULT_TENANT`.
48
+ - **Export.** `exportSubject(subjectId, options)` returning a `SubjectExport` of per-execution
49
+ `SubjectExecutionExport` (`state`, `events`, and when relevant `claimChecked`, `reservedStreams`,
50
+ `legacyCheckpoints`, `unarchived`).
51
+ - **Erasure.** `EraseCoordinator`, `ERASURE_STREAM` (the reserved control stream its facts live on),
52
+ `EraseSubjectResult` (`outcome` of `erased`, `parked` or `unknown`) and the `Shredder` type.
53
+ `shredSubject` itself is in `@loomwork/plugin-crypto`.
54
+ - **Errors.** `ArchivedCopiesRemainError`, `ContentCopiesRemainError`, `SenderRedactionUnsupportedError`.
55
+
56
+ ## Behaviour that surprises people
57
+
58
+ - **Compliance needs a plan for principal identity.** `defineConfig` refuses to compose with
59
+ `security.compliance` unless `security.crypto` is composed or a `security.principalCodec` keeps the
60
+ identity out of the log (`PrincipalRecordingRefusedError`).
61
+ - **Erasure is liveness-gated.** If every execution of the subject is terminal it shreds now (`erased`).
62
+ If any is live it records the request durably and completes it when the last one terminates (`parked`),
63
+ naming the blockers. A parked execution counts as live, so a chat agent waiting on `receive` blocks it
64
+ until you cancel it or call `eraseSubject(..., { parked: "shred" })`, which cancels suspended owners
65
+ first. A running owner still defers.
66
+ - **It fails closed before the key is destroyed.** A plaintext archive with no `deleteExecution`, or one
67
+ holding the subject as a sender without `replaceSegments`, makes erasure throw with nothing shredded.
68
+ - **Tenants share subject ids unless you partition.** Two tenants can both have an `"alice"`; without
69
+ `tenantOf` the index merges them. With it, every query, export and erasure is tenant-scoped.
70
+ - **Work started for the subject during an erasure is not covered.** After the key is destroyed its sealed
71
+ writes fail, so quiesce new work first.
72
+ - **A destroyed key is evidence only if the store can prove it.** `destroyed` is a proof function; never
73
+ stub it, because a wrong `true` produces a false erasure record.
74
+ - **Plaintext written before crypto was enabled survives a shred**, since destroying a key cannot touch
75
+ it; only deleting its stream erases it.
76
+ - **Align `subjectOf` with the crypto plugin's.** When claim-checked blobs are sealed per subject, a
77
+ mismatch makes erasure slower and may retain ciphertext.
78
+
79
+ ## Install
80
+
81
+ Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
82
+
83
+ ## See also
84
+
85
+ - API reference: section "`@loomwork/compliance` — subject export & erasure (T3)" in [docs/api-reference.org](../../docs/api-reference.org).
86
+ - Guides: [data-subject rights](../../docs/compliance.md) (full erasure behaviour, archives, inbox streams, claim-checked outputs), [data protection patterns](../../docs/data-protection-patterns.md), [encryption at rest](../../docs/loom-2.0/11-encryption-at-rest.md).
87
+ - ADRs: [0022 log lifecycle, retention, redaction and encryption](../../docs/adr/0022-k10-log-lifecycle-retention-redaction-encryption.md), [0138 compaction archives](../../docs/adr/0138-compaction-archives-what-it-removes.md), [0140 agent claim check](../../docs/adr/0140-agent-claim-check-opt-in.md).
88
+ - Source: `packages/compliance/src`.
@@ -0,0 +1,48 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ /** Given an event, the data subject it concerns — or `undefined` if it names none. */
3
+ export type SubjectResolver = (event: EventEnvelope) => string | undefined;
4
+ /** Given an event, the tenant it belongs to — or `undefined` for the default partition. */
5
+ export type TenantResolver = (event: EventEnvelope) => string | undefined;
6
+ /** The partition subjects fall into when no tenant is resolved (single-tenant apps). */
7
+ export declare const DEFAULT_TENANT = "";
8
+ export interface SubjectIndexOptions {
9
+ /** Partition the index by tenant (T3-R2.4). Omit for a single-tenant app. */
10
+ tenantOf?: TenantResolver;
11
+ }
12
+ /**
13
+ * A live, rebuildable index of `(tenant, subjectId) → executionIds`. Feed it the event stream
14
+ * (`handleEvent`, e.g. from `defineConfig`'s `onEvent`) or rebuild from a log
15
+ * ({@link SubjectIndex.fromEvents}) — both yield the same state (P2). Backed by a nested
16
+ * `Map<tenant, Map<subject, Set<execution>>>` for O(1) scoped membership + a reverse
17
+ * `Map<execution, {tenant, subject}>` for O(1) dedupe and lookup, so a burst of events for
18
+ * one execution is not re-resolved and tenants never share a subject bucket.
19
+ */
20
+ export declare class SubjectIndex {
21
+ private readonly subjectOf;
22
+ private readonly byTenant;
23
+ private readonly byExecution;
24
+ private readonly tenantOf;
25
+ constructor(subjectOf: SubjectResolver, options?: SubjectIndexOptions);
26
+ /** Fold a full event array into a fresh index (deterministic rebuild from the log). */
27
+ static fromEvents(events: readonly EventEnvelope[], subjectOf: SubjectResolver, options?: SubjectIndexOptions): SubjectIndex;
28
+ /** Record the subject (and tenant) an event concerns. Idempotent per execution (O(1) once mapped). */
29
+ handleEvent(event: EventEnvelope): void;
30
+ /**
31
+ * The executions concerning a subject WITHIN a tenant (empty if unknown). Sorted for
32
+ * deterministic output. `tenant` defaults to the single partition (single-tenant apps).
33
+ */
34
+ executionsOf(subjectId: string, tenant?: string): string[];
35
+ /** The subject an execution concerns, or `undefined` if none was resolved. */
36
+ subjectOfExecution(executionId: string): string | undefined;
37
+ /** The tenant an execution belongs to, or `undefined` if the execution is unknown. */
38
+ tenantOfExecution(executionId: string): string | undefined;
39
+ /** Whether the index has any records for a subject within a tenant. */
40
+ has(subjectId: string, tenant?: string): boolean;
41
+ /** The subjects within a tenant (sorted). The inventory backbone for a compliance report. */
42
+ subjects(tenant?: string): string[];
43
+ /** All tenant ids with any records (sorted). A single-tenant app reports one, `""`. */
44
+ tenants(): string[];
45
+ /** Number of distinct (tenant, subject) pairs indexed. */
46
+ get size(): number;
47
+ }
48
+ //# sourceMappingURL=SubjectIndex.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubjectIndex.d.ts","sourceRoot":"","sources":["../src/SubjectIndex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAwBpD,sFAAsF;AACtF,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,aAAa,KAAK,MAAM,GAAG,SAAS,CAAC;AAE3E,2FAA2F;AAC3F,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,aAAa,KAAK,MAAM,GAAG,SAAS,CAAC;AAE1E,wFAAwF;AACxF,eAAO,MAAM,cAAc,KAAK,CAAC;AAEjC,MAAM,WAAW,mBAAmB;IAClC,6EAA6E;IAC7E,QAAQ,CAAC,EAAE,cAAc,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,qBAAa,YAAY;IAMrB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAL5B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA+C;IACxE,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA0D;IACtF,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiB;gBAGvB,SAAS,EAAE,eAAe,EAC3C,OAAO,GAAE,mBAAwB;IAKnC,uFAAuF;IACvF,MAAM,CAAC,UAAU,CACf,MAAM,EAAE,SAAS,aAAa,EAAE,EAChC,SAAS,EAAE,eAAe,EAC1B,OAAO,GAAE,mBAAwB,GAChC,YAAY;IAMf,sGAAsG;IACtG,WAAW,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAoBvC;;;OAGG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,GAAE,MAAuB,GAAG,MAAM,EAAE;IAK1E,8EAA8E;IAC9E,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAI3D,sFAAsF;IACtF,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAI1D,uEAAuE;IACvE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,GAAE,MAAuB,GAAG,OAAO;IAIhE,6FAA6F;IAC7F,QAAQ,CAAC,MAAM,GAAE,MAAuB,GAAG,MAAM,EAAE;IAKnD,uFAAuF;IACvF,OAAO,IAAI,MAAM,EAAE;IAInB,0DAA0D;IAC1D,IAAI,IAAI,IAAI,MAAM,CAIjB;CACF"}
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SubjectIndex = exports.DEFAULT_TENANT = void 0;
4
+ /** The partition subjects fall into when no tenant is resolved (single-tenant apps). */
5
+ exports.DEFAULT_TENANT = "";
6
+ /**
7
+ * A live, rebuildable index of `(tenant, subjectId) → executionIds`. Feed it the event stream
8
+ * (`handleEvent`, e.g. from `defineConfig`'s `onEvent`) or rebuild from a log
9
+ * ({@link SubjectIndex.fromEvents}) — both yield the same state (P2). Backed by a nested
10
+ * `Map<tenant, Map<subject, Set<execution>>>` for O(1) scoped membership + a reverse
11
+ * `Map<execution, {tenant, subject}>` for O(1) dedupe and lookup, so a burst of events for
12
+ * one execution is not re-resolved and tenants never share a subject bucket.
13
+ */
14
+ class SubjectIndex {
15
+ subjectOf;
16
+ byTenant = new Map();
17
+ byExecution = new Map();
18
+ tenantOf;
19
+ constructor(subjectOf, options = {}) {
20
+ this.subjectOf = subjectOf;
21
+ this.tenantOf = options.tenantOf ?? (() => exports.DEFAULT_TENANT);
22
+ }
23
+ /** Fold a full event array into a fresh index (deterministic rebuild from the log). */
24
+ static fromEvents(events, subjectOf, options = {}) {
25
+ const index = new SubjectIndex(subjectOf, options);
26
+ for (const event of events)
27
+ index.handleEvent(event);
28
+ return index;
29
+ }
30
+ /** Record the subject (and tenant) an event concerns. Idempotent per execution (O(1) once mapped). */
31
+ handleEvent(event) {
32
+ // Already mapped this execution — the (tenant, subject) is stable, nothing to do.
33
+ if (this.byExecution.has(event.executionId))
34
+ return;
35
+ const subject = this.subjectOf(event);
36
+ if (subject === undefined)
37
+ return;
38
+ const tenant = this.tenantOf(event) ?? exports.DEFAULT_TENANT;
39
+ this.byExecution.set(event.executionId, { tenant, subject });
40
+ let subjects = this.byTenant.get(tenant);
41
+ if (subjects === undefined) {
42
+ subjects = new Map();
43
+ this.byTenant.set(tenant, subjects);
44
+ }
45
+ let set = subjects.get(subject);
46
+ if (set === undefined) {
47
+ set = new Set();
48
+ subjects.set(subject, set);
49
+ }
50
+ set.add(event.executionId);
51
+ }
52
+ /**
53
+ * The executions concerning a subject WITHIN a tenant (empty if unknown). Sorted for
54
+ * deterministic output. `tenant` defaults to the single partition (single-tenant apps).
55
+ */
56
+ executionsOf(subjectId, tenant = exports.DEFAULT_TENANT) {
57
+ const set = this.byTenant.get(tenant)?.get(subjectId);
58
+ return set === undefined ? [] : [...set].sort();
59
+ }
60
+ /** The subject an execution concerns, or `undefined` if none was resolved. */
61
+ subjectOfExecution(executionId) {
62
+ return this.byExecution.get(executionId)?.subject;
63
+ }
64
+ /** The tenant an execution belongs to, or `undefined` if the execution is unknown. */
65
+ tenantOfExecution(executionId) {
66
+ return this.byExecution.get(executionId)?.tenant;
67
+ }
68
+ /** Whether the index has any records for a subject within a tenant. */
69
+ has(subjectId, tenant = exports.DEFAULT_TENANT) {
70
+ return this.byTenant.get(tenant)?.has(subjectId) ?? false;
71
+ }
72
+ /** The subjects within a tenant (sorted). The inventory backbone for a compliance report. */
73
+ subjects(tenant = exports.DEFAULT_TENANT) {
74
+ const subjects = this.byTenant.get(tenant);
75
+ return subjects === undefined ? [] : [...subjects.keys()].sort();
76
+ }
77
+ /** All tenant ids with any records (sorted). A single-tenant app reports one, `""`. */
78
+ tenants() {
79
+ return [...this.byTenant.keys()].sort();
80
+ }
81
+ /** Number of distinct (tenant, subject) pairs indexed. */
82
+ get size() {
83
+ let total = 0;
84
+ for (const subjects of this.byTenant.values())
85
+ total += subjects.size;
86
+ return total;
87
+ }
88
+ }
89
+ exports.SubjectIndex = SubjectIndex;
90
+ //# sourceMappingURL=SubjectIndex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubjectIndex.js","sourceRoot":"","sources":["../src/SubjectIndex.ts"],"names":[],"mappings":";;;AA8BA,wFAAwF;AAC3E,QAAA,cAAc,GAAG,EAAE,CAAC;AAOjC;;;;;;;GAOG;AACH,MAAa,YAAY;IAMJ;IALF,QAAQ,GAAG,IAAI,GAAG,EAAoC,CAAC;IACvD,WAAW,GAAG,IAAI,GAAG,EAA+C,CAAC;IACrE,QAAQ,CAAiB;IAE1C,YACmB,SAA0B,EAC3C,UAA+B,EAAE;QADhB,cAAS,GAAT,SAAS,CAAiB;QAG3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE,CAAC,sBAAc,CAAC,CAAC;IAC7D,CAAC;IAED,uFAAuF;IACvF,MAAM,CAAC,UAAU,CACf,MAAgC,EAChC,SAA0B,EAC1B,UAA+B,EAAE;QAEjC,MAAM,KAAK,GAAG,IAAI,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACnD,KAAK,MAAM,KAAK,IAAI,MAAM;YAAE,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QACrD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,sGAAsG;IACtG,WAAW,CAAC,KAAoB;QAC9B,kFAAkF;QAClF,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC;YAAE,OAAO;QACpD,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACtC,IAAI,OAAO,KAAK,SAAS;YAAE,OAAO;QACl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