@sackville-mcp/artifacts 0.0.1-alpha.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 +201 -0
- package/dist/index.d.mts +125 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +262 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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 Derivative
|
|
95
|
+
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 2026 Curtis Autery
|
|
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.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
//#region src/store.d.ts
|
|
2
|
+
interface Artifact {
|
|
3
|
+
/** Absolute path of the artifact on disk. */
|
|
4
|
+
path: string;
|
|
5
|
+
contentType: string;
|
|
6
|
+
byteSize: number;
|
|
7
|
+
/** Hex SHA-256 of the bytes — lets a consumer verify/cache by content. */
|
|
8
|
+
sha256: string;
|
|
9
|
+
/**
|
|
10
|
+
* True when `contentType` could not be recovered (a legacy artifact rehydrated
|
|
11
|
+
* with no `<kind>.meta.json` sidecar) and was defaulted to
|
|
12
|
+
* `application/octet-stream` — never a silent failure (ADR 0013 §4).
|
|
13
|
+
*/
|
|
14
|
+
contentTypeInferred?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Bounds on a store's own `<baseDir>/<prefix>` subtree (ADR 0017). All optional; an
|
|
18
|
+
* unset dimension is not enforced, and a policy with no dimension set is a no-op (so
|
|
19
|
+
* a store with no retention NEVER deletes — fully backward-compatible).
|
|
20
|
+
*/
|
|
21
|
+
interface RetentionPolicy {
|
|
22
|
+
/** Evict `<id>` dirs whose mtime is older than `now - maxAgeMs`. */
|
|
23
|
+
maxAgeMs?: number;
|
|
24
|
+
/** Keep at most this many `<id>` dirs (newest by mtime). */
|
|
25
|
+
maxEntries?: number;
|
|
26
|
+
/** Keep the subtree's total bytes at or under this cap (evict oldest-first). */
|
|
27
|
+
maxBytes?: number;
|
|
28
|
+
}
|
|
29
|
+
/** A sane default throttle for the server bins' opportunistic `put()` sweep — a hot
|
|
30
|
+
* write loop re-scans the subtree at most once a minute, GC stays responsive enough. */
|
|
31
|
+
declare const DEFAULT_SWEEP_INTERVAL_MS = 60000;
|
|
32
|
+
interface ArtifactStoreOptions {
|
|
33
|
+
/** Retention bounds; absent ⇒ the store is append-only (no GC). */
|
|
34
|
+
retention?: RetentionPolicy;
|
|
35
|
+
/** Clock injection (testing / determinism). Default `Date.now`. */
|
|
36
|
+
now?: () => number;
|
|
37
|
+
/** Minimum ms between opportunistic `put()`-triggered sweeps. Default 0 (every put). */
|
|
38
|
+
sweepIntervalMs?: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Parse a `RetentionPolicy` from raw env strings (each bin's per-pillar
|
|
42
|
+
* `SACKVILLE_<PILLAR>_ARTIFACT_MAX_AGE_MS` / `_MAX_ENTRIES` / `_MAX_BYTES`). Returns
|
|
43
|
+
* `undefined` when NONE is set (⇒ no GC — opt-in). A non-numeric or negative value is
|
|
44
|
+
* ignored (treated as unset) so a typo never silently deletes everything.
|
|
45
|
+
*/
|
|
46
|
+
declare function retentionFromEnv(raw: {
|
|
47
|
+
maxAgeMs?: string;
|
|
48
|
+
maxEntries?: string;
|
|
49
|
+
maxBytes?: string;
|
|
50
|
+
}): RetentionPolicy | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* On-disk-backed store for verification artifacts (traces, screenshots, video,
|
|
53
|
+
* HAR, audit reports, changelog diffs, coverage reports…), addressed by a
|
|
54
|
+
* `sackville://<prefix>/<id>/<kind>` handle. Artifacts are large/binary, so they
|
|
55
|
+
* are written to disk and returned by handle — never inlined into a tool result.
|
|
56
|
+
*
|
|
57
|
+
* The handle `prefix` is **parameterized** so each pillar emits its own handle
|
|
58
|
+
* space over one shared store (`browser/run` → `sackville://browser/run/<id>/<kind>`;
|
|
59
|
+
* `deps` → `sackville://deps/<id>/<kind>`). Extracted from the browser pillar per
|
|
60
|
+
* ADR 0010; a persistent/remote backend can replace this later — the handle
|
|
61
|
+
* contract stays the same.
|
|
62
|
+
*
|
|
63
|
+
* The on-disk layout is `<baseDir>/<prefix>/<id>/<kind>` — the prefix lives IN the
|
|
64
|
+
* path (ADR 0013 slice 1), so one shared `baseDir` is collision-free across pillars
|
|
65
|
+
* and a store can **rehydrate a foreign-prefix handle** it never `put()` itself
|
|
66
|
+
* (the cross-pillar verify read). Because a rehydrate is a filesystem read
|
|
67
|
+
* addressed by an agent-supplied string, every segment is allowlist-validated and
|
|
68
|
+
* the resolved path is realpath-confined under `baseDir`.
|
|
69
|
+
*/
|
|
70
|
+
declare class ArtifactStore {
|
|
71
|
+
private readonly baseDir;
|
|
72
|
+
private readonly prefix;
|
|
73
|
+
private artifacts;
|
|
74
|
+
/**
|
|
75
|
+
* @param baseDir on-disk root for stored artifact bytes (created if absent).
|
|
76
|
+
* @param prefix the handle namespace between `sackville://` and `/<id>/<kind>`
|
|
77
|
+
* (may contain `/`, e.g. `browser/run`); each segment must be a safe segment.
|
|
78
|
+
*/
|
|
79
|
+
private readonly retention?;
|
|
80
|
+
private readonly now;
|
|
81
|
+
private readonly sweepIntervalMs;
|
|
82
|
+
private lastSweepAt;
|
|
83
|
+
constructor(baseDir: string, prefix: string, opts?: ArtifactStoreOptions);
|
|
84
|
+
/** The handle a (`runId`, `kind`) pair maps to — reconstruct without re-storing. */
|
|
85
|
+
handleFor(runId: string, kind: string): string;
|
|
86
|
+
/** Persist `body` under run `runId` as artifact `kind`; returns its handle. */
|
|
87
|
+
put(runId: string, kind: string, body: string | Buffer, contentType: string): string;
|
|
88
|
+
private hasPolicy;
|
|
89
|
+
/** Opportunistic, THROTTLED sweep after a write (ADR 0017): at most once per
|
|
90
|
+
* `sweepIntervalMs` so a hot write loop doesn't re-scan the subtree every put. */
|
|
91
|
+
private maybeSweep;
|
|
92
|
+
/**
|
|
93
|
+
* Evict `<id>` dirs under THIS store's own `<baseDir>/<prefix>` subtree per the
|
|
94
|
+
* `RetentionPolicy` — age (`maxAgeMs`) then count (`maxEntries`) then size
|
|
95
|
+
* (`maxBytes`), oldest-first by dir mtime (so a just-written run is evicted last).
|
|
96
|
+
* Disk-based (a cold process's in-process map is empty), confinement-checked before
|
|
97
|
+
* every delete (never deletes THROUGH a symlink escaping `baseDir`), and a no-op when
|
|
98
|
+
* no policy is set. Returns the evicted ids. Public so a bin can sweep on startup.
|
|
99
|
+
*/
|
|
100
|
+
sweep(nowMs?: number): string[];
|
|
101
|
+
/** Forget the in-process handles of an evicted id, so a later `get()` misses → disk
|
|
102
|
+
* (also gone) → `undefined`, never a read of a deleted path. */
|
|
103
|
+
private dropHandles;
|
|
104
|
+
/**
|
|
105
|
+
* Resolve a handle to its metadata + bytes, or `undefined` if no such artifact
|
|
106
|
+
* exists. A handle this store `put()` resolves from the in-process map; any other
|
|
107
|
+
* well-formed handle is **rehydrated from disk** by its own prefix/id/kind.
|
|
108
|
+
* Throws on a malformed/unsafe handle (a traversal or separator in a segment).
|
|
109
|
+
*/
|
|
110
|
+
get(handle: string): (Artifact & {
|
|
111
|
+
body: Buffer;
|
|
112
|
+
}) | undefined;
|
|
113
|
+
/** Parse `sackville://<prefix>/<id>/<kind>`; validate every segment. */
|
|
114
|
+
private parseHandle;
|
|
115
|
+
private readSidecar;
|
|
116
|
+
/**
|
|
117
|
+
* Realpath-confine `path` under `baseDir` — defends against a symlinked
|
|
118
|
+
* prefix/id dir escaping the store root even though every segment is allowlisted
|
|
119
|
+
* (the same realpath posture the LSP write-mode confinement uses).
|
|
120
|
+
*/
|
|
121
|
+
private assertConfined;
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
export { type Artifact, ArtifactStore, type ArtifactStoreOptions, DEFAULT_SWEEP_INTERVAL_MS, type RetentionPolicy, retentionFromEnv };
|
|
125
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/store.ts"],"mappings":";UAaiB,QAAA;EAAA;EAEf,IAAA;EACA,WAAA;EACA,QAAA;EAFA;EAIA,MAAA;EAFA;;;;AAQmB;EAAnB,mBAAA;AAAA;;;;;;UAQe,eAAA;EAMP;EAJR,QAAA;EASoC;EAPpC,UAAA;EAOoC;EALpC,QAAA;AAAA;;;cAKW,yBAAA;AAAA,UAEI,oBAAA;EAEH;EAAZ,SAAA,GAAY,eAAe;EAI3B;EAFA,GAAA;EAEe;EAAf,eAAA;AAAA;;;;;;;iBASc,gBAAA,CAAiB,GAAA;EAC/B,QAAA;EACA,UAAA;EACA,QAAA;AAAA,IACE,eAAe;;;;;;;;;;;;;;;;;;;;cA2DN,aAAA;EAAA,iBAcQ,OAAA;EAAA,iBACA,MAAA;EAAA,QAdX,SAAA;EA8BJ;;;;;EAAA,iBAvBa,SAAA;EAAA,iBACA,GAAA;EAAA,iBACA,eAAA;EAAA,QACT,WAAA;cAGW,OAAA,UACA,MAAA,UACjB,IAAA,GAAM,oBAAA;EA0IR;EAhIA,SAAA,CAAU,KAAA,UAAe,IAAA;EAgIH;EA3HtB,GAAA,CAAI,KAAA,UAAe,IAAA,UAAc,IAAA,WAAe,MAAA,EAAQ,WAAA;EAAA,QAuBhD,SAAA;EAyHA;;EAAA,QAhHA,UAAA;EAiJc;AAAA;;;;;;;EAjItB,KAAA,CAAM,KAAA;;;UAgEE,WAAA;;;;;;;EAWR,GAAA,CAAI,MAAA,YAAkB,QAAA;IAAa,IAAA,EAAM,MAAA;EAAA;;UAqBjC,WAAA;EAAA,QAaA,WAAA;;;;;;UAoBA,cAAA;AAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
//#region src/store.ts
|
|
5
|
+
/** A sane default throttle for the server bins' opportunistic `put()` sweep — a hot
|
|
6
|
+
* write loop re-scans the subtree at most once a minute, GC stays responsive enough. */
|
|
7
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 6e4;
|
|
8
|
+
/**
|
|
9
|
+
* Parse a `RetentionPolicy` from raw env strings (each bin's per-pillar
|
|
10
|
+
* `SACKVILLE_<PILLAR>_ARTIFACT_MAX_AGE_MS` / `_MAX_ENTRIES` / `_MAX_BYTES`). Returns
|
|
11
|
+
* `undefined` when NONE is set (⇒ no GC — opt-in). A non-numeric or negative value is
|
|
12
|
+
* ignored (treated as unset) so a typo never silently deletes everything.
|
|
13
|
+
*/
|
|
14
|
+
function retentionFromEnv(raw) {
|
|
15
|
+
const n = (v) => {
|
|
16
|
+
if (!v) return void 0;
|
|
17
|
+
const x = Number(v);
|
|
18
|
+
return Number.isFinite(x) && x >= 0 ? x : void 0;
|
|
19
|
+
};
|
|
20
|
+
const policy = {};
|
|
21
|
+
const age = n(raw.maxAgeMs);
|
|
22
|
+
const entries = n(raw.maxEntries);
|
|
23
|
+
const bytes = n(raw.maxBytes);
|
|
24
|
+
if (age !== void 0) policy.maxAgeMs = age;
|
|
25
|
+
if (entries !== void 0) policy.maxEntries = entries;
|
|
26
|
+
if (bytes !== void 0) policy.maxBytes = bytes;
|
|
27
|
+
return Object.keys(policy).length > 0 ? policy : void 0;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A single safe path segment: an agent-supplied `id`/`kind` (or a prefix segment
|
|
31
|
+
* parsed out of a foreign handle) may only contain these characters and is never
|
|
32
|
+
* `.`/`..` — so it cannot traverse, separate, or escape. Mirrors the `safeId`
|
|
33
|
+
* allowlist the deps surface uses (`packages/mcp/src/deps.ts`).
|
|
34
|
+
*/
|
|
35
|
+
function isSafeSegment(value) {
|
|
36
|
+
return value.length > 0 && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value);
|
|
37
|
+
}
|
|
38
|
+
function assertSafeSegment(value, what) {
|
|
39
|
+
if (!isSafeSegment(value)) throw new Error(`ArtifactStore: unsafe ${what} segment ${JSON.stringify(value)}`);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* On-disk-backed store for verification artifacts (traces, screenshots, video,
|
|
43
|
+
* HAR, audit reports, changelog diffs, coverage reports…), addressed by a
|
|
44
|
+
* `sackville://<prefix>/<id>/<kind>` handle. Artifacts are large/binary, so they
|
|
45
|
+
* are written to disk and returned by handle — never inlined into a tool result.
|
|
46
|
+
*
|
|
47
|
+
* The handle `prefix` is **parameterized** so each pillar emits its own handle
|
|
48
|
+
* space over one shared store (`browser/run` → `sackville://browser/run/<id>/<kind>`;
|
|
49
|
+
* `deps` → `sackville://deps/<id>/<kind>`). Extracted from the browser pillar per
|
|
50
|
+
* ADR 0010; a persistent/remote backend can replace this later — the handle
|
|
51
|
+
* contract stays the same.
|
|
52
|
+
*
|
|
53
|
+
* The on-disk layout is `<baseDir>/<prefix>/<id>/<kind>` — the prefix lives IN the
|
|
54
|
+
* path (ADR 0013 slice 1), so one shared `baseDir` is collision-free across pillars
|
|
55
|
+
* and a store can **rehydrate a foreign-prefix handle** it never `put()` itself
|
|
56
|
+
* (the cross-pillar verify read). Because a rehydrate is a filesystem read
|
|
57
|
+
* addressed by an agent-supplied string, every segment is allowlist-validated and
|
|
58
|
+
* the resolved path is realpath-confined under `baseDir`.
|
|
59
|
+
*/
|
|
60
|
+
var ArtifactStore = class {
|
|
61
|
+
baseDir;
|
|
62
|
+
prefix;
|
|
63
|
+
artifacts = /* @__PURE__ */ new Map();
|
|
64
|
+
/**
|
|
65
|
+
* @param baseDir on-disk root for stored artifact bytes (created if absent).
|
|
66
|
+
* @param prefix the handle namespace between `sackville://` and `/<id>/<kind>`
|
|
67
|
+
* (may contain `/`, e.g. `browser/run`); each segment must be a safe segment.
|
|
68
|
+
*/
|
|
69
|
+
retention;
|
|
70
|
+
now;
|
|
71
|
+
sweepIntervalMs;
|
|
72
|
+
lastSweepAt = Number.NEGATIVE_INFINITY;
|
|
73
|
+
constructor(baseDir, prefix, opts = {}) {
|
|
74
|
+
this.baseDir = baseDir;
|
|
75
|
+
this.prefix = prefix;
|
|
76
|
+
for (const seg of prefix.split("/")) assertSafeSegment(seg, "prefix");
|
|
77
|
+
mkdirSync(baseDir, { recursive: true });
|
|
78
|
+
this.retention = opts.retention;
|
|
79
|
+
this.now = opts.now ?? Date.now;
|
|
80
|
+
this.sweepIntervalMs = opts.sweepIntervalMs ?? 0;
|
|
81
|
+
}
|
|
82
|
+
/** The handle a (`runId`, `kind`) pair maps to — reconstruct without re-storing. */
|
|
83
|
+
handleFor(runId, kind) {
|
|
84
|
+
return `sackville://${this.prefix}/${runId}/${kind}`;
|
|
85
|
+
}
|
|
86
|
+
/** Persist `body` under run `runId` as artifact `kind`; returns its handle. */
|
|
87
|
+
put(runId, kind, body, contentType) {
|
|
88
|
+
assertSafeSegment(runId, "id");
|
|
89
|
+
assertSafeSegment(kind, "kind");
|
|
90
|
+
const handle = this.handleFor(runId, kind);
|
|
91
|
+
const buf = typeof body === "string" ? Buffer.from(body, "utf8") : body;
|
|
92
|
+
const dir = join(this.baseDir, this.prefix, runId);
|
|
93
|
+
mkdirSync(dir, { recursive: true });
|
|
94
|
+
this.assertConfined(dir);
|
|
95
|
+
const path = join(dir, kind);
|
|
96
|
+
writeFileSync(path, buf);
|
|
97
|
+
writeFileSync(`${path}.meta.json`, JSON.stringify({ contentType }));
|
|
98
|
+
this.artifacts.set(handle, {
|
|
99
|
+
path,
|
|
100
|
+
contentType,
|
|
101
|
+
byteSize: buf.byteLength,
|
|
102
|
+
sha256: createHash("sha256").update(buf).digest("hex")
|
|
103
|
+
});
|
|
104
|
+
this.maybeSweep();
|
|
105
|
+
return handle;
|
|
106
|
+
}
|
|
107
|
+
hasPolicy() {
|
|
108
|
+
const r = this.retention;
|
|
109
|
+
return !!r && (r.maxAgeMs !== void 0 || r.maxEntries !== void 0 || r.maxBytes !== void 0);
|
|
110
|
+
}
|
|
111
|
+
/** Opportunistic, THROTTLED sweep after a write (ADR 0017): at most once per
|
|
112
|
+
* `sweepIntervalMs` so a hot write loop doesn't re-scan the subtree every put. */
|
|
113
|
+
maybeSweep() {
|
|
114
|
+
if (!this.hasPolicy()) return;
|
|
115
|
+
const t = this.now();
|
|
116
|
+
if (t - this.lastSweepAt < this.sweepIntervalMs) return;
|
|
117
|
+
this.lastSweepAt = t;
|
|
118
|
+
this.sweep(t);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Evict `<id>` dirs under THIS store's own `<baseDir>/<prefix>` subtree per the
|
|
122
|
+
* `RetentionPolicy` — age (`maxAgeMs`) then count (`maxEntries`) then size
|
|
123
|
+
* (`maxBytes`), oldest-first by dir mtime (so a just-written run is evicted last).
|
|
124
|
+
* Disk-based (a cold process's in-process map is empty), confinement-checked before
|
|
125
|
+
* every delete (never deletes THROUGH a symlink escaping `baseDir`), and a no-op when
|
|
126
|
+
* no policy is set. Returns the evicted ids. Public so a bin can sweep on startup.
|
|
127
|
+
*/
|
|
128
|
+
sweep(nowMs = this.now()) {
|
|
129
|
+
if (!this.hasPolicy()) return [];
|
|
130
|
+
const root = join(this.baseDir, this.prefix);
|
|
131
|
+
if (!existsSync(root)) return [];
|
|
132
|
+
const r = this.retention;
|
|
133
|
+
const entries = [];
|
|
134
|
+
for (const d of readdirSync(root, { withFileTypes: true })) {
|
|
135
|
+
if (!d.isDirectory()) continue;
|
|
136
|
+
const dir = join(root, d.name);
|
|
137
|
+
try {
|
|
138
|
+
const st = statSync(dir);
|
|
139
|
+
let bytes = 0;
|
|
140
|
+
for (const f of readdirSync(dir, { withFileTypes: true })) if (f.isFile()) bytes += statSync(join(dir, f.name)).size;
|
|
141
|
+
entries.push({
|
|
142
|
+
id: d.name,
|
|
143
|
+
dir,
|
|
144
|
+
mtimeMs: st.mtimeMs,
|
|
145
|
+
bytes
|
|
146
|
+
});
|
|
147
|
+
} catch {}
|
|
148
|
+
}
|
|
149
|
+
const evict = /* @__PURE__ */ new Set();
|
|
150
|
+
if (r.maxAgeMs !== void 0) {
|
|
151
|
+
const cut = nowMs - r.maxAgeMs;
|
|
152
|
+
for (const e of entries) if (e.mtimeMs < cut) evict.add(e.id);
|
|
153
|
+
}
|
|
154
|
+
let kept = entries.filter((e) => !evict.has(e.id)).sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
155
|
+
if (r.maxEntries !== void 0 && kept.length > r.maxEntries) {
|
|
156
|
+
for (const e of kept.slice(r.maxEntries)) evict.add(e.id);
|
|
157
|
+
kept = kept.slice(0, r.maxEntries);
|
|
158
|
+
}
|
|
159
|
+
if (r.maxBytes !== void 0) {
|
|
160
|
+
let total = 0;
|
|
161
|
+
for (const e of kept) {
|
|
162
|
+
total += e.bytes;
|
|
163
|
+
if (total > r.maxBytes) evict.add(e.id);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const evicted = [];
|
|
167
|
+
for (const e of entries) {
|
|
168
|
+
if (!evict.has(e.id)) continue;
|
|
169
|
+
try {
|
|
170
|
+
this.assertConfined(e.dir);
|
|
171
|
+
} catch {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
rmSync(e.dir, {
|
|
175
|
+
recursive: true,
|
|
176
|
+
force: true
|
|
177
|
+
});
|
|
178
|
+
this.dropHandles(e.id);
|
|
179
|
+
evicted.push(e.id);
|
|
180
|
+
}
|
|
181
|
+
return evicted;
|
|
182
|
+
}
|
|
183
|
+
/** Forget the in-process handles of an evicted id, so a later `get()` misses → disk
|
|
184
|
+
* (also gone) → `undefined`, never a read of a deleted path. */
|
|
185
|
+
dropHandles(id) {
|
|
186
|
+
const p = `sackville://${this.prefix}/${id}/`;
|
|
187
|
+
for (const key of this.artifacts.keys()) if (key.startsWith(p)) this.artifacts.delete(key);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Resolve a handle to its metadata + bytes, or `undefined` if no such artifact
|
|
191
|
+
* exists. A handle this store `put()` resolves from the in-process map; any other
|
|
192
|
+
* well-formed handle is **rehydrated from disk** by its own prefix/id/kind.
|
|
193
|
+
* Throws on a malformed/unsafe handle (a traversal or separator in a segment).
|
|
194
|
+
*/
|
|
195
|
+
get(handle) {
|
|
196
|
+
const meta = this.artifacts.get(handle);
|
|
197
|
+
if (meta) return {
|
|
198
|
+
...meta,
|
|
199
|
+
body: readFileSync(meta.path)
|
|
200
|
+
};
|
|
201
|
+
const { prefix, id, kind } = this.parseHandle(handle);
|
|
202
|
+
const path = join(this.baseDir, prefix, id, kind);
|
|
203
|
+
if (!existsSync(path)) return void 0;
|
|
204
|
+
this.assertConfined(path);
|
|
205
|
+
const buf = readFileSync(path);
|
|
206
|
+
const { contentType, contentTypeInferred } = this.readSidecar(path);
|
|
207
|
+
return {
|
|
208
|
+
path,
|
|
209
|
+
contentType,
|
|
210
|
+
contentTypeInferred,
|
|
211
|
+
byteSize: buf.byteLength,
|
|
212
|
+
sha256: createHash("sha256").update(buf).digest("hex"),
|
|
213
|
+
body: buf
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/** Parse `sackville://<prefix>/<id>/<kind>`; validate every segment. */
|
|
217
|
+
parseHandle(handle) {
|
|
218
|
+
const rest = handle.startsWith("sackville://") ? handle.slice(12) : void 0;
|
|
219
|
+
if (rest === void 0) throw new Error(`ArtifactStore: not a sackville:// handle: ${handle}`);
|
|
220
|
+
const parts = rest.split("/");
|
|
221
|
+
if (parts.length < 3) throw new Error(`ArtifactStore: malformed handle: ${handle}`);
|
|
222
|
+
const kind = parts.pop();
|
|
223
|
+
const id = parts.pop();
|
|
224
|
+
assertSafeSegment(id, "id");
|
|
225
|
+
assertSafeSegment(kind, "kind");
|
|
226
|
+
for (const seg of parts) assertSafeSegment(seg, "prefix");
|
|
227
|
+
return {
|
|
228
|
+
prefix: parts.join("/"),
|
|
229
|
+
id,
|
|
230
|
+
kind
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
readSidecar(path) {
|
|
234
|
+
const sidecar = `${path}.meta.json`;
|
|
235
|
+
if (!existsSync(sidecar)) return {
|
|
236
|
+
contentType: "application/octet-stream",
|
|
237
|
+
contentTypeInferred: true
|
|
238
|
+
};
|
|
239
|
+
try {
|
|
240
|
+
const parsed = JSON.parse(readFileSync(sidecar, "utf8"));
|
|
241
|
+
if (typeof parsed.contentType === "string" && parsed.contentType.length > 0) return { contentType: parsed.contentType };
|
|
242
|
+
} catch {}
|
|
243
|
+
return {
|
|
244
|
+
contentType: "application/octet-stream",
|
|
245
|
+
contentTypeInferred: true
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Realpath-confine `path` under `baseDir` — defends against a symlinked
|
|
250
|
+
* prefix/id dir escaping the store root even though every segment is allowlisted
|
|
251
|
+
* (the same realpath posture the LSP write-mode confinement uses).
|
|
252
|
+
*/
|
|
253
|
+
assertConfined(path) {
|
|
254
|
+
const root = realpathSync(this.baseDir);
|
|
255
|
+
const resolved = realpathSync(path);
|
|
256
|
+
if (resolved !== root && !resolved.startsWith(root + sep)) throw new Error(`ArtifactStore: path escapes baseDir: ${path}`);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
//#endregion
|
|
260
|
+
export { ArtifactStore, DEFAULT_SWEEP_INTERVAL_MS, retentionFromEnv };
|
|
261
|
+
|
|
262
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { join, sep } from 'node:path'\n\nexport interface Artifact {\n /** Absolute path of the artifact on disk. */\n path: string\n contentType: string\n byteSize: number\n /** Hex SHA-256 of the bytes — lets a consumer verify/cache by content. */\n sha256: string\n /**\n * True when `contentType` could not be recovered (a legacy artifact rehydrated\n * with no `<kind>.meta.json` sidecar) and was defaulted to\n * `application/octet-stream` — never a silent failure (ADR 0013 §4).\n */\n contentTypeInferred?: boolean\n}\n\n/**\n * Bounds on a store's own `<baseDir>/<prefix>` subtree (ADR 0017). All optional; an\n * unset dimension is not enforced, and a policy with no dimension set is a no-op (so\n * a store with no retention NEVER deletes — fully backward-compatible).\n */\nexport interface RetentionPolicy {\n /** Evict `<id>` dirs whose mtime is older than `now - maxAgeMs`. */\n maxAgeMs?: number\n /** Keep at most this many `<id>` dirs (newest by mtime). */\n maxEntries?: number\n /** Keep the subtree's total bytes at or under this cap (evict oldest-first). */\n maxBytes?: number\n}\n\n/** A sane default throttle for the server bins' opportunistic `put()` sweep — a hot\n * write loop re-scans the subtree at most once a minute, GC stays responsive enough. */\nexport const DEFAULT_SWEEP_INTERVAL_MS = 60_000\n\nexport interface ArtifactStoreOptions {\n /** Retention bounds; absent ⇒ the store is append-only (no GC). */\n retention?: RetentionPolicy\n /** Clock injection (testing / determinism). Default `Date.now`. */\n now?: () => number\n /** Minimum ms between opportunistic `put()`-triggered sweeps. Default 0 (every put). */\n sweepIntervalMs?: number\n}\n\n/**\n * Parse a `RetentionPolicy` from raw env strings (each bin's per-pillar\n * `SACKVILLE_<PILLAR>_ARTIFACT_MAX_AGE_MS` / `_MAX_ENTRIES` / `_MAX_BYTES`). Returns\n * `undefined` when NONE is set (⇒ no GC — opt-in). A non-numeric or negative value is\n * ignored (treated as unset) so a typo never silently deletes everything.\n */\nexport function retentionFromEnv(raw: {\n maxAgeMs?: string\n maxEntries?: string\n maxBytes?: string\n}): RetentionPolicy | undefined {\n const n = (v: string | undefined): number | undefined => {\n if (!v) return undefined\n const x = Number(v)\n return Number.isFinite(x) && x >= 0 ? x : undefined\n }\n const policy: RetentionPolicy = {}\n const age = n(raw.maxAgeMs)\n const entries = n(raw.maxEntries)\n const bytes = n(raw.maxBytes)\n if (age !== undefined) policy.maxAgeMs = age\n if (entries !== undefined) policy.maxEntries = entries\n if (bytes !== undefined) policy.maxBytes = bytes\n return Object.keys(policy).length > 0 ? policy : undefined\n}\n\n/** A handle parsed into its on-disk-addressing parts. */\ninterface ParsedHandle {\n /** The handle namespace (may contain `/`, e.g. `browser/run`). */\n prefix: string\n id: string\n kind: string\n}\n\n/**\n * A single safe path segment: an agent-supplied `id`/`kind` (or a prefix segment\n * parsed out of a foreign handle) may only contain these characters and is never\n * `.`/`..` — so it cannot traverse, separate, or escape. Mirrors the `safeId`\n * allowlist the deps surface uses (`packages/mcp/src/deps.ts`).\n */\nfunction isSafeSegment(value: string): boolean {\n return value.length > 0 && value !== '.' && value !== '..' && /^[A-Za-z0-9._-]+$/.test(value)\n}\n\nfunction assertSafeSegment(value: string, what: string): void {\n if (!isSafeSegment(value)) {\n throw new Error(`ArtifactStore: unsafe ${what} segment ${JSON.stringify(value)}`)\n }\n}\n\n/**\n * On-disk-backed store for verification artifacts (traces, screenshots, video,\n * HAR, audit reports, changelog diffs, coverage reports…), addressed by a\n * `sackville://<prefix>/<id>/<kind>` handle. Artifacts are large/binary, so they\n * are written to disk and returned by handle — never inlined into a tool result.\n *\n * The handle `prefix` is **parameterized** so each pillar emits its own handle\n * space over one shared store (`browser/run` → `sackville://browser/run/<id>/<kind>`;\n * `deps` → `sackville://deps/<id>/<kind>`). Extracted from the browser pillar per\n * ADR 0010; a persistent/remote backend can replace this later — the handle\n * contract stays the same.\n *\n * The on-disk layout is `<baseDir>/<prefix>/<id>/<kind>` — the prefix lives IN the\n * path (ADR 0013 slice 1), so one shared `baseDir` is collision-free across pillars\n * and a store can **rehydrate a foreign-prefix handle** it never `put()` itself\n * (the cross-pillar verify read). Because a rehydrate is a filesystem read\n * addressed by an agent-supplied string, every segment is allowlist-validated and\n * the resolved path is realpath-confined under `baseDir`.\n */\nexport class ArtifactStore {\n private artifacts = new Map<string, Artifact>()\n\n /**\n * @param baseDir on-disk root for stored artifact bytes (created if absent).\n * @param prefix the handle namespace between `sackville://` and `/<id>/<kind>`\n * (may contain `/`, e.g. `browser/run`); each segment must be a safe segment.\n */\n private readonly retention?: RetentionPolicy\n private readonly now: () => number\n private readonly sweepIntervalMs: number\n private lastSweepAt = Number.NEGATIVE_INFINITY\n\n constructor(\n private readonly baseDir: string,\n private readonly prefix: string,\n opts: ArtifactStoreOptions = {},\n ) {\n for (const seg of prefix.split('/')) assertSafeSegment(seg, 'prefix')\n mkdirSync(baseDir, { recursive: true })\n this.retention = opts.retention\n this.now = opts.now ?? Date.now\n this.sweepIntervalMs = opts.sweepIntervalMs ?? 0\n }\n\n /** The handle a (`runId`, `kind`) pair maps to — reconstruct without re-storing. */\n handleFor(runId: string, kind: string): string {\n return `sackville://${this.prefix}/${runId}/${kind}`\n }\n\n /** Persist `body` under run `runId` as artifact `kind`; returns its handle. */\n put(runId: string, kind: string, body: string | Buffer, contentType: string): string {\n assertSafeSegment(runId, 'id')\n assertSafeSegment(kind, 'kind')\n const handle = this.handleFor(runId, kind)\n const buf = typeof body === 'string' ? Buffer.from(body, 'utf8') : body\n const dir = join(this.baseDir, this.prefix, runId)\n mkdirSync(dir, { recursive: true })\n this.assertConfined(dir)\n const path = join(dir, kind)\n writeFileSync(path, buf)\n // Sidecar so a cold-process rehydrate recovers contentType (not inferable\n // from raw bytes). One per artifact: `<kind>.meta.json`.\n writeFileSync(`${path}.meta.json`, JSON.stringify({ contentType }))\n this.artifacts.set(handle, {\n path,\n contentType,\n byteSize: buf.byteLength,\n sha256: createHash('sha256').update(buf).digest('hex'),\n })\n this.maybeSweep()\n return handle\n }\n\n private hasPolicy(): boolean {\n const r = this.retention\n return (\n !!r && (r.maxAgeMs !== undefined || r.maxEntries !== undefined || r.maxBytes !== undefined)\n )\n }\n\n /** Opportunistic, THROTTLED sweep after a write (ADR 0017): at most once per\n * `sweepIntervalMs` so a hot write loop doesn't re-scan the subtree every put. */\n private maybeSweep(): void {\n if (!this.hasPolicy()) return\n const t = this.now()\n if (t - this.lastSweepAt < this.sweepIntervalMs) return\n this.lastSweepAt = t\n this.sweep(t)\n }\n\n /**\n * Evict `<id>` dirs under THIS store's own `<baseDir>/<prefix>` subtree per the\n * `RetentionPolicy` — age (`maxAgeMs`) then count (`maxEntries`) then size\n * (`maxBytes`), oldest-first by dir mtime (so a just-written run is evicted last).\n * Disk-based (a cold process's in-process map is empty), confinement-checked before\n * every delete (never deletes THROUGH a symlink escaping `baseDir`), and a no-op when\n * no policy is set. Returns the evicted ids. Public so a bin can sweep on startup.\n */\n sweep(nowMs: number = this.now()): string[] {\n if (!this.hasPolicy()) return []\n const root = join(this.baseDir, this.prefix)\n if (!existsSync(root)) return []\n const r = this.retention as RetentionPolicy\n\n interface Entry {\n id: string\n dir: string\n mtimeMs: number\n bytes: number\n }\n const entries: Entry[] = []\n for (const d of readdirSync(root, { withFileTypes: true })) {\n if (!d.isDirectory()) continue\n const dir = join(root, d.name)\n try {\n const st = statSync(dir)\n let bytes = 0\n for (const f of readdirSync(dir, { withFileTypes: true })) {\n if (f.isFile()) bytes += statSync(join(dir, f.name)).size\n }\n entries.push({ id: d.name, dir, mtimeMs: st.mtimeMs, bytes })\n } catch {\n // a racing delete / unreadable entry — skip it this pass\n }\n }\n\n const evict = new Set<string>()\n if (r.maxAgeMs !== undefined) {\n const cut = nowMs - r.maxAgeMs\n for (const e of entries) if (e.mtimeMs < cut) evict.add(e.id)\n }\n // Newest-first survivors drive the count + size caps (oldest evicted first).\n let kept = entries.filter((e) => !evict.has(e.id)).sort((a, b) => b.mtimeMs - a.mtimeMs)\n if (r.maxEntries !== undefined && kept.length > r.maxEntries) {\n for (const e of kept.slice(r.maxEntries)) evict.add(e.id)\n kept = kept.slice(0, r.maxEntries)\n }\n if (r.maxBytes !== undefined) {\n let total = 0\n for (const e of kept) {\n total += e.bytes\n if (total > r.maxBytes) evict.add(e.id)\n }\n }\n\n const evicted: string[] = []\n for (const e of entries) {\n if (!evict.has(e.id)) continue\n try {\n this.assertConfined(e.dir) // never delete THROUGH a symlink escaping baseDir\n } catch {\n continue\n }\n rmSync(e.dir, { recursive: true, force: true })\n this.dropHandles(e.id)\n evicted.push(e.id)\n }\n return evicted\n }\n\n /** Forget the in-process handles of an evicted id, so a later `get()` misses → disk\n * (also gone) → `undefined`, never a read of a deleted path. */\n private dropHandles(id: string): void {\n const p = `sackville://${this.prefix}/${id}/`\n for (const key of this.artifacts.keys()) if (key.startsWith(p)) this.artifacts.delete(key)\n }\n\n /**\n * Resolve a handle to its metadata + bytes, or `undefined` if no such artifact\n * exists. A handle this store `put()` resolves from the in-process map; any other\n * well-formed handle is **rehydrated from disk** by its own prefix/id/kind.\n * Throws on a malformed/unsafe handle (a traversal or separator in a segment).\n */\n get(handle: string): (Artifact & { body: Buffer }) | undefined {\n const meta = this.artifacts.get(handle)\n if (meta) return { ...meta, body: readFileSync(meta.path) }\n\n const { prefix, id, kind } = this.parseHandle(handle)\n const path = join(this.baseDir, prefix, id, kind)\n if (!existsSync(path)) return undefined\n this.assertConfined(path)\n const buf = readFileSync(path)\n const { contentType, contentTypeInferred } = this.readSidecar(path)\n return {\n path,\n contentType,\n contentTypeInferred,\n byteSize: buf.byteLength,\n sha256: createHash('sha256').update(buf).digest('hex'),\n body: buf,\n }\n }\n\n /** Parse `sackville://<prefix>/<id>/<kind>`; validate every segment. */\n private parseHandle(handle: string): ParsedHandle {\n const rest = handle.startsWith('sackville://') ? handle.slice('sackville://'.length) : undefined\n if (rest === undefined) throw new Error(`ArtifactStore: not a sackville:// handle: ${handle}`)\n const parts = rest.split('/')\n if (parts.length < 3) throw new Error(`ArtifactStore: malformed handle: ${handle}`)\n const kind = parts.pop() as string\n const id = parts.pop() as string\n assertSafeSegment(id, 'id')\n assertSafeSegment(kind, 'kind')\n for (const seg of parts) assertSafeSegment(seg, 'prefix')\n return { prefix: parts.join('/'), id, kind }\n }\n\n private readSidecar(path: string): { contentType: string; contentTypeInferred?: boolean } {\n const sidecar = `${path}.meta.json`\n if (!existsSync(sidecar))\n return { contentType: 'application/octet-stream', contentTypeInferred: true }\n try {\n const parsed = JSON.parse(readFileSync(sidecar, 'utf8')) as { contentType?: unknown }\n if (typeof parsed.contentType === 'string' && parsed.contentType.length > 0) {\n return { contentType: parsed.contentType }\n }\n } catch {\n // fall through to the inferred default below\n }\n return { contentType: 'application/octet-stream', contentTypeInferred: true }\n }\n\n /**\n * Realpath-confine `path` under `baseDir` — defends against a symlinked\n * prefix/id dir escaping the store root even though every segment is allowlisted\n * (the same realpath posture the LSP write-mode confinement uses).\n */\n private assertConfined(path: string): void {\n const root = realpathSync(this.baseDir)\n const resolved = realpathSync(path)\n if (resolved !== root && !resolved.startsWith(root + sep)) {\n throw new Error(`ArtifactStore: path escapes baseDir: ${path}`)\n }\n }\n}\n"],"mappings":";;;;;;AA4CA,MAAa,4BAA4B;;;;;;;AAiBzC,SAAgB,iBAAiB,KAID;CAC9B,MAAM,KAAK,MAA8C;EACvD,IAAI,CAAC,GAAG,OAAO,KAAA;EACf,MAAM,IAAI,OAAO,CAAC;EAClB,OAAO,OAAO,SAAS,CAAC,KAAK,KAAK,IAAI,IAAI,KAAA;CAC5C;CACA,MAAM,SAA0B,CAAC;CACjC,MAAM,MAAM,EAAE,IAAI,QAAQ;CAC1B,MAAM,UAAU,EAAE,IAAI,UAAU;CAChC,MAAM,QAAQ,EAAE,IAAI,QAAQ;CAC5B,IAAI,QAAQ,KAAA,GAAW,OAAO,WAAW;CACzC,IAAI,YAAY,KAAA,GAAW,OAAO,aAAa;CAC/C,IAAI,UAAU,KAAA,GAAW,OAAO,WAAW;CAC3C,OAAO,OAAO,KAAK,MAAM,EAAE,SAAS,IAAI,SAAS,KAAA;AACnD;;;;;;;AAgBA,SAAS,cAAc,OAAwB;CAC7C,OAAO,MAAM,S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OAAO,aAAa,KAAK,OAAO;EACtC,MAAM,WAAW,aAAa,IAAI;EAClC,IAAI,aAAa,QAAQ,CAAC,SAAS,WAAW,OAAO,GAAG,GACtD,MAAM,IAAI,MAAM,wCAAwC,MAAM;CAElE;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sackville-mcp/artifacts",
|
|
3
|
+
"version": "0.0.1-alpha.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"import": {
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"default": "./dist/index.mjs"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"main": "./dist/index.mjs",
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/ceautery/sackville.git",
|
|
24
|
+
"directory": "packages/artifacts"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsdown src/index.ts --dts",
|
|
28
|
+
"typecheck": "tsc --noEmit"
|
|
29
|
+
}
|
|
30
|
+
}
|