@alma-harness/core 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 +71 -0
- package/dist/chunk-KPNXPUGR.js +125 -0
- package/dist/chunk-KPNXPUGR.js.map +1 -0
- package/dist/index.d.ts +789 -0
- package/dist/index.js +127 -0
- package/dist/index.js.map +1 -0
- package/dist/testing/index.d.ts +74 -0
- package/dist/testing/index.js +268 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/turn-store-uKJ4inz2.d.ts +1054 -0
- package/package.json +43 -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,71 @@
|
|
|
1
|
+
# @alma-harness/core
|
|
2
|
+
|
|
3
|
+
The contracts and the security core of [Alma](https://github.com/FabioFernandesCarneiro/alma)
|
|
4
|
+
— a TypeScript runtime for multi-tenant agents operating on sensitive data.
|
|
5
|
+
The engine that runs against them ships as
|
|
6
|
+
[`@alma-harness/loop`](../loop).
|
|
7
|
+
|
|
8
|
+
> **Status: pre-release.** Not yet published to npm. The API is still moving;
|
|
9
|
+
> see the [roadmap](../../docs/architecture.md#12-adoption-roadmap).
|
|
10
|
+
|
|
11
|
+
## What it owns
|
|
12
|
+
|
|
13
|
+
The vocabulary every other package speaks, and the rules the engine may not
|
|
14
|
+
bend. What a turn is allowed to do is defined here; the engine that enforces
|
|
15
|
+
it lives in [`@alma-harness/loop`](../loop).
|
|
16
|
+
|
|
17
|
+
- **Tenancy** (`Scope`, `scopePath`) — `{org, uid}` bound by closure. The model
|
|
18
|
+
never sees or chooses it; deriving it from a verified identity is the host
|
|
19
|
+
application's job.
|
|
20
|
+
- **Lifecycle events** (`LifecycleHooks`, `Interceptor`) — the closed set of
|
|
21
|
+
typed seams an extension may attach to, capability-narrowing only.
|
|
22
|
+
- **Tools** (`defineTool`) — capability by registration. What the model may
|
|
23
|
+
call is derived from the registry per step, never a list it can extend.
|
|
24
|
+
Outputs are bounded at registration (`maxOutputChars`, a default applies):
|
|
25
|
+
a result enters the transcript once and is re-sent forever, and removing
|
|
26
|
+
it later costs more than it saves.
|
|
27
|
+
- **Routing** (`ModelPolicy`, `Sensitivity`, `Tier`) — complexity × sensitivity,
|
|
28
|
+
enforced at dispatch and never escalating through a delegate.
|
|
29
|
+
- **Budget** (`BudgetCaps`, `priceUsage`, `SpendStore`) — dollar caps,
|
|
30
|
+
fail-closed pricing: an unpriced model never spends. `perTurnUsd` is a hard
|
|
31
|
+
stop (the malfunction guard); session and tenant-day caps are accounted
|
|
32
|
+
through the `SpendStore` seam with per-cap policy — `warn` by default (the
|
|
33
|
+
turn continues, the crossing is reported), `block` opt-in.
|
|
34
|
+
- **Audit** (`AuditLog`) — access, routing, cost, recall and context trails. Where they
|
|
35
|
+
are written is swappable; *that* they are written is not.
|
|
36
|
+
- **Turn coordination** (`TurnStore`) — the session lease and the idempotency
|
|
37
|
+
record (spec 030). A redelivered webhook replays the stored result instead of
|
|
38
|
+
re-executing tools and re-charging; two messages on one session serialize
|
|
39
|
+
instead of interleaving. Same idiom: where the record lives is swappable,
|
|
40
|
+
that a turn is claimed before it runs is not.
|
|
41
|
+
- **Memory contracts** (`EpisodeStore`, `ProfileStore`, `MemoryErasure`, …) —
|
|
42
|
+
the interfaces live here because memory integrates with tenancy, audit and
|
|
43
|
+
routing; the implementations live in `@alma-harness/memory`.
|
|
44
|
+
|
|
45
|
+
## What it must never do
|
|
46
|
+
|
|
47
|
+
- Reach the filesystem, spawn a subprocess, or ship a shell. Ever.
|
|
48
|
+
- Accept a scope from the model, or let a hook rewrite routing, budget or the
|
|
49
|
+
advertised tool set.
|
|
50
|
+
- Depend on a provider SDK. The neutral message format is the boundary.
|
|
51
|
+
|
|
52
|
+
## Testing helpers
|
|
53
|
+
|
|
54
|
+
`@alma-harness/core/testing` ships reference implementations of the contracts
|
|
55
|
+
this package publishes — a recording `AuditLog`, and the in-memory
|
|
56
|
+
`SessionStore`, `SpendStore` and `TurnStore`. Nothing in it imports vitest. The shared
|
|
57
|
+
storage contract suites every adapter must pass live in
|
|
58
|
+
`@alma-harness/testing`; the in-memory memory stores in
|
|
59
|
+
`@alma-harness/memory/testing`; the scripted `ModelClient` that drives the
|
|
60
|
+
engine in [`@alma-harness/loop/testing`](../loop).
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { InMemorySessionStore, RecordingAuditLog } from "@alma-harness/core/testing";
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Documentation
|
|
67
|
+
|
|
68
|
+
[Docs index](../../docs/README.md) · [Architecture](../../docs/architecture.md)
|
|
69
|
+
· [Invariants](../../docs/invariants.md) · [Quickstart](../../examples/quickstart)
|
|
70
|
+
|
|
71
|
+
Apache-2.0
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// src/scope.ts
|
|
2
|
+
var InvalidScopeError = class extends Error {
|
|
3
|
+
constructor(segment, value) {
|
|
4
|
+
super(`Invalid scope ${segment}: ${JSON.stringify(value)}`);
|
|
5
|
+
this.name = "InvalidScopeError";
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
var SCOPE_SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
|
|
9
|
+
function scopePath(scope) {
|
|
10
|
+
if (!SCOPE_SEGMENT.test(scope.org)) throw new InvalidScopeError("org", scope.org);
|
|
11
|
+
if (!SCOPE_SEGMENT.test(scope.uid)) throw new InvalidScopeError("uid", scope.uid);
|
|
12
|
+
return `tenants/${scope.org}/users/${scope.uid}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// src/text.ts
|
|
16
|
+
function cutAtCodePoint(text, end) {
|
|
17
|
+
if (end <= 0) return "";
|
|
18
|
+
const last = text.charCodeAt(end - 1);
|
|
19
|
+
return text.slice(0, last >= 55296 && last <= 56319 ? end - 1 : end);
|
|
20
|
+
}
|
|
21
|
+
function hasMalformed(root) {
|
|
22
|
+
const stack = [root];
|
|
23
|
+
while (stack.length > 0) {
|
|
24
|
+
const value = stack.pop();
|
|
25
|
+
if (typeof value === "string") {
|
|
26
|
+
if (!value.isWellFormed()) return true;
|
|
27
|
+
} else if (Array.isArray(value)) {
|
|
28
|
+
for (const item of value) stack.push(item);
|
|
29
|
+
} else if (value !== null && typeof value === "object") {
|
|
30
|
+
for (const [key, item] of Object.entries(value)) {
|
|
31
|
+
if (!key.isWellFormed()) return true;
|
|
32
|
+
stack.push(item);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
function repair(root) {
|
|
39
|
+
const leaf = (v) => typeof v === "string" ? v.toWellFormed() : v;
|
|
40
|
+
const open = (v) => {
|
|
41
|
+
if (Array.isArray(v)) return { keys: null, items: v, built: [] };
|
|
42
|
+
if (v !== null && typeof v === "object") {
|
|
43
|
+
const entries = Object.entries(v);
|
|
44
|
+
return {
|
|
45
|
+
keys: entries.map(([key]) => key.toWellFormed()),
|
|
46
|
+
items: entries.map(([, item]) => item),
|
|
47
|
+
built: []
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
};
|
|
52
|
+
const close = (f) => (
|
|
53
|
+
// `Object.fromEntries` uses CreateDataProperty, so a literal `__proto__`
|
|
54
|
+
// key becomes an OWN property. Assigning `out[key] = …` instead invoked
|
|
55
|
+
// the `Object.prototype.__proto__` SETTER: the key vanished from the
|
|
56
|
+
// persisted message and the rebuilt object took a tool-controlled
|
|
57
|
+
// prototype (spec 025 review).
|
|
58
|
+
f.keys === null ? f.built : Object.fromEntries(f.keys.map((k, i) => [k, f.built[i]]))
|
|
59
|
+
);
|
|
60
|
+
const rootFrame = open(root);
|
|
61
|
+
if (rootFrame === null) return leaf(root);
|
|
62
|
+
const frames = [rootFrame];
|
|
63
|
+
for (; ; ) {
|
|
64
|
+
const frame = frames[frames.length - 1];
|
|
65
|
+
if (frame.built.length === frame.items.length) {
|
|
66
|
+
const value = close(frame);
|
|
67
|
+
frames.pop();
|
|
68
|
+
if (frames.length === 0) return value;
|
|
69
|
+
frames[frames.length - 1].built.push(value);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const next = frame.items[frame.built.length];
|
|
73
|
+
const child = open(next);
|
|
74
|
+
if (child === null) frame.built.push(leaf(next));
|
|
75
|
+
else frames.push(child);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function toWellFormedDeep(value) {
|
|
79
|
+
return hasMalformed(value) ? repair(value) : value;
|
|
80
|
+
}
|
|
81
|
+
var MalformedTextError = class extends Error {
|
|
82
|
+
constructor(path) {
|
|
83
|
+
super(
|
|
84
|
+
`malformed UTF-16 at ${path}: a lone surrogate is not text and cannot be persisted \u2014 run toWellFormedDeep() on the value first`
|
|
85
|
+
);
|
|
86
|
+
this.path = path;
|
|
87
|
+
this.name = "MalformedTextError";
|
|
88
|
+
}
|
|
89
|
+
path;
|
|
90
|
+
};
|
|
91
|
+
function malformedPath(root, base) {
|
|
92
|
+
const stack = [{ value: root, path: base }];
|
|
93
|
+
while (stack.length > 0) {
|
|
94
|
+
const { value, path } = stack.pop();
|
|
95
|
+
if (typeof value === "string") {
|
|
96
|
+
if (!value.isWellFormed()) return path;
|
|
97
|
+
} else if (Array.isArray(value)) {
|
|
98
|
+
for (let i = value.length - 1; i >= 0; i--) {
|
|
99
|
+
stack.push({ value: value[i], path: `${path}[${i}]` });
|
|
100
|
+
}
|
|
101
|
+
} else if (value !== null && typeof value === "object") {
|
|
102
|
+
const entries = Object.entries(value);
|
|
103
|
+
for (const [key] of entries) if (!key.isWellFormed()) return `${path}.<key>`;
|
|
104
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
105
|
+
const entry = entries[i];
|
|
106
|
+
stack.push({ value: entry[1], path: `${path}.${entry[0]}` });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return base;
|
|
111
|
+
}
|
|
112
|
+
function assertWellFormed(value, where) {
|
|
113
|
+
if (!hasMalformed(value)) return;
|
|
114
|
+
throw new MalformedTextError(malformedPath(value, where));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export {
|
|
118
|
+
InvalidScopeError,
|
|
119
|
+
scopePath,
|
|
120
|
+
cutAtCodePoint,
|
|
121
|
+
toWellFormedDeep,
|
|
122
|
+
MalformedTextError,
|
|
123
|
+
assertWellFormed
|
|
124
|
+
};
|
|
125
|
+
//# sourceMappingURL=chunk-KPNXPUGR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scope.ts","../src/text.ts"],"sourcesContent":["/**\n * Tenancy scope — the isolation boundary of the whole harness.\n *\n * `{org, uid}` derives from a server-verified token, never from a client\n * payload, and is bound to tool registries by closure at construction time —\n * the model never passes org/uid as parameters.\n *\n * @see docs/architecture.md §6.1, §6.8\n */\nexport interface Scope {\n /** Organization (tenant) id. */\n readonly org: string;\n /** User id within the organization. */\n readonly uid: string;\n}\n\n/**\n * Thrown by {@link scopePath} when a scope segment could be used for path\n * traversal or key-delimiter injection.\n */\nexport class InvalidScopeError extends Error {\n constructor(segment: \"org\" | \"uid\", value: string) {\n super(`Invalid scope ${segment}: ${JSON.stringify(value)}`);\n this.name = \"InvalidScopeError\";\n }\n}\n\n/**\n * DECISION: allowed charset for scope segments. The doc (§2) records uneven\n * path-sanitization hardening as a production bug class; the harness therefore\n * validates centrally. Alphanumerics plus `_ - .` (no leading dot) covers real\n * Firebase uids and org slugs while excluding `/`, `..` and whitespace.\n */\nconst SCOPE_SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;\n\n/**\n * The single place that builds `tenants/{org}/users/{uid}` — §6.8.\n *\n * A *concept*, not a literal storage path: the Firestore adapter renders it as\n * a collection path, the Postgres adapter as row-level-security predicates\n * (§6). Every store keys its data by this concept so scoped purge and export\n * have one canonical addressing scheme.\n */\nexport function scopePath(scope: Scope): string {\n if (!SCOPE_SEGMENT.test(scope.org)) throw new InvalidScopeError(\"org\", scope.org);\n if (!SCOPE_SEGMENT.test(scope.uid)) throw new InvalidScopeError(\"uid\", scope.uid);\n return `tenants/${scope.org}/users/${scope.uid}`;\n}\n","/**\n * Text safety at the persistence boundary — spec: well-formed-text.\n *\n * A JavaScript string is UTF-16 code units, and everything outside the BMP —\n * emoji, the CJK range — is two of them. Any operation that cuts by index can\n * leave a LONE SURROGATE: half a character, which is not text. It is invalid\n * in `jsonb`, so a store that persists `JSON.stringify(msg)::jsonb` rejects\n * the write and the turn loses every message including the user's.\n */\n\n/**\n * Cuts `text` at `end` code units, moving back one when that would split a\n * surrogate pair.\n *\n * PRECONDITION: `text` is well-formed. This helper does not REPAIR — it only\n * declines to break — so a lone surrogate already present survives the cut.\n * A caller that cannot guarantee its input (spec 025 review: the memory\n * validator now REFUSES what this could hand it) runs `toWellFormedDeep`\n * first.\n *\n * Given that precondition, exactly one case can break, so the check is O(1):\n * a HIGH surrogate at the last included index, whose partner sits just past\n * the cut. A low surrogate there already has its partner included.\n *\n * Grapheme clusters are deliberately NOT preserved — an accent can still be\n * separated from its base letter. That is cosmetic in a string the reader is\n * told was truncated; a lone surrogate is a data-integrity failure.\n */\nexport function cutAtCodePoint(text: string, end: number): string {\n if (end <= 0) return \"\";\n const last = text.charCodeAt(end - 1);\n return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);\n}\n\n/**\n * True when any string in `value` — including any object KEY — is malformed.\n *\n * ITERATIVE on purpose. The first draft recursed, and a recursive walk blew\n * the stack at ~4,000 levels of nesting while `JSON.stringify` handled the\n * same value: a payload the store would have ACCEPTED made the repair throw\n * (spec 025 review). Detection runs on every turn, so it is the half that must\n * never be the thing that fails.\n */\nfunction hasMalformed(root: unknown): boolean {\n const stack: unknown[] = [root];\n while (stack.length > 0) {\n const value = stack.pop();\n if (typeof value === \"string\") {\n if (!value.isWellFormed()) return true;\n } else if (Array.isArray(value)) {\n for (const item of value) stack.push(item);\n } else if (value !== null && typeof value === \"object\") {\n for (const [key, item] of Object.entries(value)) {\n // Keys travel into the JSON too, and a malformed one is refused by\n // `jsonb` exactly like a malformed value — the first draft checked\n // values only, so `{\"bad\\ud83dkey\": \"fine\"}` sailed through.\n if (!key.isWellFormed()) return true;\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Rebuilds `value` with every string — key and leaf — made well-formed.\n *\n * Wholesale, not selectively: identity is the guarantee for a CLEAN value, and\n * a broken one is being rewritten anyway. The untouched branches keep their\n * bytes, and the cached prefix keys off content rather than object identity.\n */\nfunction repair(root: unknown): unknown {\n // ITERATIVE, like `hasMalformed` and for the same reason — spec 040 review.\n // This was the LAST recursive walk over this shape, and it was the one that\n // mattered: detection was made iterative in spec 025 while repair was left\n // recursive behind a best-effort `catch`, so a deeply nested MALFORMED value\n // was detected and then failed to be repaired. The existing depth pin could\n // not see it because its 50,000-level fixture is clean, so `hasMalformed`\n // returns false and repair never runs.\n //\n // An explicit stack of half-built containers, closed bottom-up. Children are\n // produced before their parent, so nothing is rebuilt twice.\n interface Frame {\n /** Repaired keys, in order — `null` marks an array. */\n keys: string[] | null;\n items: readonly unknown[];\n built: unknown[];\n }\n\n const leaf = (v: unknown): unknown => (typeof v === \"string\" ? v.toWellFormed() : v);\n\n const open = (v: unknown): Frame | null => {\n if (Array.isArray(v)) return { keys: null, items: v, built: [] };\n if (v !== null && typeof v === \"object\") {\n const entries = Object.entries(v);\n return {\n keys: entries.map(([key]) => key.toWellFormed()),\n items: entries.map(([, item]) => item),\n built: [],\n };\n }\n return null;\n };\n\n const close = (f: Frame): unknown =>\n // `Object.fromEntries` uses CreateDataProperty, so a literal `__proto__`\n // key becomes an OWN property. Assigning `out[key] = …` instead invoked\n // the `Object.prototype.__proto__` SETTER: the key vanished from the\n // persisted message and the rebuilt object took a tool-controlled\n // prototype (spec 025 review).\n f.keys === null ? f.built : Object.fromEntries(f.keys.map((k, i) => [k, f.built[i]]));\n\n const rootFrame = open(root);\n if (rootFrame === null) return leaf(root);\n\n const frames: Frame[] = [rootFrame];\n for (;;) {\n const frame = frames[frames.length - 1]!;\n if (frame.built.length === frame.items.length) {\n const value = close(frame);\n frames.pop();\n if (frames.length === 0) return value;\n frames[frames.length - 1]!.built.push(value);\n continue;\n }\n const next = frame.items[frame.built.length];\n const child = open(next);\n if (child === null) frame.built.push(leaf(next));\n else frames.push(child);\n }\n}\n\n/**\n * Returns `value` with every string made well-formed, each lone surrogate\n * replaced by U+FFFD — and the SAME REFERENCE when nothing was broken.\n *\n * The identity property is load-bearing rather than an optimization: an\n * under-ceiling tool output must be persisted byte-identical or the cached\n * prefix drifts (spec: tool-output-discipline), and a normalizer that rebuilt\n * every message would drift all of them. Detection allocates nothing beyond a\n * work stack; only an already-broken value is rebuilt.\n *\n * ⚠ Do NOT replace this with a one-pass check on the serialized form.\n * `JSON.stringify` has been well-formed since ES2019: it escapes a lone\n * surrogate as `\\ud83d`, so `JSON.stringify(v).isWellFormed()` is ALWAYS true\n * and detects nothing. Normalizing that output does not help either — the\n * escape survives, and the store still rejects it. Only the source string can\n * be repaired.\n *\n * BOTH halves are iterative as of spec 040. Detection was made so in spec 025;\n * repair was left recursive behind each caller's best-effort `catch`, which\n * meant a deeply nested MALFORMED value was detected and then not repaired —\n * invisible to the depth pin of the day, whose fixture is clean and therefore\n * never reaches repair at all. Callers still treat repair as best-effort, and\n * that is now belt-and-braces rather than the load-bearing mitigation it was.\n */\nexport function toWellFormedDeep<T>(value: T): T {\n return hasMalformed(value) ? (repair(value) as T) : value;\n}\n\n/**\n * A store refused a write because a string in it was not text — spec 040.\n *\n * Its own class so a bulk writer can catch this and nothing else: a migration\n * wants to skip or repair the one bad row, not swallow a connection failure\n * alongside it.\n *\n * The message names the PATH and never the content. A lone surrogate prints\n * as a replacement box and the string around it is, in the case that drove\n * this, clinical text — neither belongs in a log line.\n */\nexport class MalformedTextError extends Error {\n constructor(readonly path: string) {\n super(\n `malformed UTF-16 at ${path}: a lone surrogate is not text and cannot be ` +\n `persisted — run toWellFormedDeep() on the value first`,\n );\n this.name = \"MalformedTextError\";\n }\n}\n\n/**\n * Locates a malformed string, as a readable path. Runs ONLY after\n * {@link hasMalformed} has already said there is one, so the cost of carrying\n * paths is paid on the failing write and never on the hot one.\n *\n * ITERATIVE, for the reason {@link hasMalformed} is — spec 040's own review.\n * The first version recursed one frame per level of nesting and threw\n * `RangeError` instead of {@link MalformedTextError} on a value `JSON.stringify`\n * handles, which is the exact defect spec 025 removed from detection and this\n * function reintroduced beside it. A caller writing\n * `catch (e) { if (e instanceof MalformedTextError) … }` — the usage this class\n * exists to support — would not have caught it.\n *\n * Depth-first, left to right, with an object's KEYS all checked before any of\n * its values are descended into. So the path is the first offender in that\n * order, not an arbitrary one.\n */\nfunction malformedPath(root: unknown, base: string): string {\n const stack: { value: unknown; path: string }[] = [{ value: root, path: base }];\n while (stack.length > 0) {\n const { value, path } = stack.pop()!;\n if (typeof value === \"string\") {\n if (!value.isWellFormed()) return path;\n } else if (Array.isArray(value)) {\n // Pushed in reverse so `pop` yields them in order.\n for (let i = value.length - 1; i >= 0; i--) {\n stack.push({ value: value[i], path: `${path}[${i}]` });\n }\n } else if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value);\n // A malformed KEY is reported as `<key>` rather than by its own text —\n // the text is what cannot be printed.\n for (const [key] of entries) if (!key.isWellFormed()) return `${path}.<key>`;\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]!;\n stack.push({ value: entry[1], path: `${path}.${entry[0]}` });\n }\n }\n }\n return base;\n}\n\n/**\n * Throws {@link MalformedTextError} when any string in `value` — object keys\n * included — is not well-formed UTF-16.\n *\n * The guard every store calls at its write boundary, so that the adapters\n * AGREE (spec 040). They used to diverge: `jsonb` refuses a lone surrogate so\n * the Postgres adapters failed the write, while the in-memory references kept\n * it — and both contracts said \"do not rely on either behaviour\", which is not\n * a contract. `runTurn` repairs on the way in, but only BEST-EFFORT (its catch\n * keeps the unrepaired message), and a product writing to a store directly —\n * a migration, a backfill, a replay — has no such pass at all.\n *\n * Refusing rather than repairing here is deliberate. A store that silently\n * rewrites the bytes of a record kept for years is worse than one that\n * refuses, and since the repair is best-effort by design an `append` that\n * repaired would still not be a guarantee.\n *\n * `where` labels the value for the message — typically the parameter name and\n * index, e.g. `entries[3]`.\n */\nexport function assertWellFormed(value: unknown, where: string): void {\n // Cheap detection first: the clean path allocates nothing beyond the work\n // stack and never builds a path string.\n if (!hasMalformed(value)) return;\n throw new MalformedTextError(malformedPath(value, where));\n}\n"],"mappings":";AAoBO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YAAY,SAAwB,OAAe;AACjD,UAAM,iBAAiB,OAAO,KAAK,KAAK,UAAU,KAAK,CAAC,EAAE;AAC1D,SAAK,OAAO;AAAA,EACd;AACF;AAQA,IAAM,gBAAgB;AAUf,SAAS,UAAU,OAAsB;AAC9C,MAAI,CAAC,cAAc,KAAK,MAAM,GAAG,EAAG,OAAM,IAAI,kBAAkB,OAAO,MAAM,GAAG;AAChF,MAAI,CAAC,cAAc,KAAK,MAAM,GAAG,EAAG,OAAM,IAAI,kBAAkB,OAAO,MAAM,GAAG;AAChF,SAAO,WAAW,MAAM,GAAG,UAAU,MAAM,GAAG;AAChD;;;ACnBO,SAAS,eAAe,MAAc,KAAqB;AAChE,MAAI,OAAO,EAAG,QAAO;AACrB,QAAM,OAAO,KAAK,WAAW,MAAM,CAAC;AACpC,SAAO,KAAK,MAAM,GAAG,QAAQ,SAAU,QAAQ,QAAS,MAAM,IAAI,GAAG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