@remembrance-ai/pi-plugin 0.0.0-stage → 0.2.25

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,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
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 2026 Dreamark, Inc.
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/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # Remembrance for Pi
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
+ Native Pi extension for reusable skill discovery, organization preferences,
4
+ feedback, protected local learning, recovery, and connection diagnostics.
5
+ Requires Node.js 22.19 or newer and Pi 1.5.2 or newer.
6
+
7
+ ```sh
8
+ pi install npm:@remembrance-ai/pi-plugin@0.2.25
9
+ ```
10
+
11
+ Restart Pi after installation. The extension registers its bundled `remembrance`
12
+ MCP server through Pi's native MCP support. It uses the existing Remembrance
13
+ environment variables or `~/.config/remembrance/config.json` (under
14
+ `XDG_CONFIG_HOME` when set); installation does not copy credentials into Pi
15
+ configuration. Never put organization keys in a prompt or commit them.
16
+
17
+ Use Remembrance tools directly when automatic context is insufficient. Discovery
18
+ and preference context use the same bounded hooks as the other native plugins.
19
+ Private capture uses the existing encrypted local outbox and exact private
20
+ actions; a retained draft is not a submitted contribution. Missing source
21
+ authority leaves a recoverable hold. A host denial never switches transport.
22
+
23
+ The first private write in each consent lane offers **Allow this time**,
24
+ **Always allow**, or **Deny** in Pi. Always allow saves a protected receipt for
25
+ that organization, registry, and lane. Headless runs require a matching saved
26
+ receipt. Administrator operations require approval for every exact operation;
27
+ a saved private-learning receipt never approves an administrator write.
28
+
29
+ Update with:
30
+
31
+ ```sh
32
+ pi install npm:@remembrance-ai/pi-plugin@latest
33
+ ```
34
+
35
+ Set `REMEMBRANCE_AUTO_QUERY=0` to disable automatic queries. Use the MCP
36
+ `get_connection_status` and `run_connection_doctor` tools for diagnostics.
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@remembrance-ai/pi-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.25",
4
+ "license": "Apache-2.0",
5
+ "description": "Native Pi extension for Remembrance discovery, preferences, feedback, and protected learning.",
6
+ "type": "module",
7
+ "main": "src/index.mjs",
8
+ "exports": {
9
+ ".": "./src/index.mjs"
10
+ },
11
+ "keywords": [
12
+ "pi-package",
13
+ "pi-extension",
14
+ "remembrance"
15
+ ],
16
+ "pi": {
17
+ "extensions": [
18
+ "./src/index.mjs"
19
+ ],
20
+ "skills": [
21
+ "./skills"
22
+ ]
23
+ },
24
+ "files": [
25
+ "src",
26
+ "scripts",
27
+ "servers",
28
+ "skills",
29
+ "LICENSE",
30
+ "README.md"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "provenance": false
35
+ },
36
+ "engines": {
37
+ "node": ">=22.19.0"
38
+ },
39
+ "scripts": {
40
+ "build": "node --check src/index.mjs && node --check scripts/hook-core.mjs",
41
+ "prepack": "npm run build",
42
+ "test": "vitest run",
43
+ "test:private-lesson": "vitest run test/security.test.mjs test/lifecycle.test.mjs test/tools.test.mjs",
44
+ "typecheck": "node --check src/index.mjs && node --check scripts/hook-core.mjs"
45
+ },
46
+ "devDependencies": {
47
+ "vitest": "^3.1.2"
48
+ }
49
+ }
@@ -0,0 +1,376 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ constants,
6
+ fstatSync,
7
+ fsyncSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ openSync,
11
+ opendirSync,
12
+ readSync,
13
+ renameSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { homedir, tmpdir, userInfo } from "node:os";
18
+ import { dirname, join } from "node:path";
19
+
20
+ const FEEDBACK_DENIAL_VERSION = "feedback-denial-acknowledgement-v1";
21
+ const FEEDBACK_DENIAL_SUBDIRECTORY = "feedback-denials";
22
+ const FEEDBACK_DENIAL_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
23
+ const MAX_FEEDBACK_IDENTIFIER_LENGTH = 512;
24
+ const MAX_FEEDBACK_DENIAL_MARKER_BYTES = 1024;
25
+ const MAX_FEEDBACK_DENIAL_MARKERS = 512;
26
+ const MARKER_NAME_PATTERN = /^[a-f0-9]{64}\.json$/u;
27
+
28
+ class FeedbackDenialStorageError extends Error {
29
+ constructor() {
30
+ super("The host-policy denial acknowledgement could not be persisted.");
31
+ this.name = "FeedbackDenialStorageError";
32
+ this.code = "feedback_denial_acknowledgement_failed";
33
+ this.status = "acknowledgement_failed";
34
+ this.acknowledged = false;
35
+ this.submitted = false;
36
+ this.local_only = true;
37
+ }
38
+ }
39
+
40
+ function normalizeInput(input) {
41
+ if (!input || typeof input !== "object" || Array.isArray(input)) return null;
42
+ const keys = Object.keys(input).sort();
43
+ const expectedKeys =
44
+ input.tool === "submit_feedback"
45
+ ? ["query_id", "reason", "result_id", "tool"]
46
+ : ["query_id", "reason", "tool"];
47
+ if (
48
+ keys.length !== expectedKeys.length ||
49
+ keys.some((key, index) => key !== expectedKeys[index]) ||
50
+ !["submit_query_feedback", "submit_feedback"].includes(input.tool) ||
51
+ input.reason !== "host_policy_denied" ||
52
+ !validIdentifier(input.query_id)
53
+ ) {
54
+ return null;
55
+ }
56
+ if (input.tool === "submit_feedback") {
57
+ if (!validIdentifier(input.result_id)) return null;
58
+ return {
59
+ tool: input.tool,
60
+ query_id: input.query_id,
61
+ result_id: input.result_id,
62
+ reason: input.reason,
63
+ };
64
+ }
65
+ if ("result_id" in input) return null;
66
+ return {
67
+ tool: input.tool,
68
+ query_id: input.query_id,
69
+ reason: input.reason,
70
+ };
71
+ }
72
+
73
+ function validIdentifier(value) {
74
+ return (
75
+ typeof value === "string" &&
76
+ value.length > 0 &&
77
+ value.length <= MAX_FEEDBACK_IDENTIFIER_LENGTH
78
+ );
79
+ }
80
+
81
+ function exactEventDigest(input) {
82
+ const fields = [input.tool, input.query_id, input.result_id ?? ""];
83
+ const hash = createHash("sha256");
84
+ for (const field of fields) {
85
+ const bytes = Buffer.from(field, "utf8");
86
+ hash.update(String(bytes.length), "utf8");
87
+ hash.update(":", "utf8");
88
+ hash.update(bytes);
89
+ hash.update(";", "utf8");
90
+ }
91
+ return hash.digest("hex");
92
+ }
93
+
94
+ function localUsageOwnerId() {
95
+ const uid = currentUserId();
96
+ if (uid !== null) return `uid-${uid}`;
97
+ return `home-${createHash("sha256")
98
+ .update(homedir())
99
+ .digest("hex")
100
+ .slice(0, 16)}`;
101
+ }
102
+
103
+ function currentUserId() {
104
+ try {
105
+ const uid = userInfo().uid;
106
+ if (Number.isSafeInteger(uid) && uid >= 0) return uid;
107
+ } catch {
108
+ // Non-POSIX runtimes fall back to the same home hash as hook-core.
109
+ }
110
+ return null;
111
+ }
112
+
113
+ function usageDirectory(env) {
114
+ return env?.REMEMBRANCE_USAGE_DIR
115
+ ? String(env.REMEMBRANCE_USAGE_DIR)
116
+ : join(tmpdir(), `remembrance-usage-${localUsageOwnerId()}`);
117
+ }
118
+
119
+ function markerDirectory(env) {
120
+ return join(usageDirectory(env), FEEDBACK_DENIAL_SUBDIRECTORY);
121
+ }
122
+
123
+ function markerPath(input, env) {
124
+ return join(markerDirectory(env), `${exactEventDigest(input)}.json`);
125
+ }
126
+
127
+ function isPosix() {
128
+ return currentUserId() !== null;
129
+ }
130
+
131
+ function assertCurrentOwner(uid) {
132
+ const currentUid = currentUserId();
133
+ if (currentUid !== null && uid !== currentUid) {
134
+ throw new Error("Local state is not owned by the current user.");
135
+ }
136
+ }
137
+
138
+ function ensurePrivateDirectory(path) {
139
+ mkdirSync(path, { recursive: true, mode: 0o700 });
140
+ const metadata = lstatSync(path);
141
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
142
+ throw new Error("Local state is not a regular directory.");
143
+ }
144
+ assertCurrentOwner(metadata.uid);
145
+ if (isPosix() && (metadata.mode & 0o077) !== 0) {
146
+ chmodSync(path, 0o700);
147
+ const repaired = lstatSync(path);
148
+ assertCurrentOwner(repaired.uid);
149
+ if ((repaired.mode & 0o077) !== 0) {
150
+ throw new Error("Local state directory permissions are not private.");
151
+ }
152
+ }
153
+ }
154
+
155
+ function assertPrivateDirectory(path) {
156
+ const metadata = lstatSync(path);
157
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
158
+ throw new Error("Local state is not a regular directory.");
159
+ }
160
+ assertCurrentOwner(metadata.uid);
161
+ if (isPosix() && (metadata.mode & 0o022) !== 0) {
162
+ throw new Error("Local state directory is writable by another user.");
163
+ }
164
+ }
165
+
166
+ function assertPrivateMarker(metadata) {
167
+ if (
168
+ metadata.isSymbolicLink() ||
169
+ !metadata.isFile() ||
170
+ metadata.size > MAX_FEEDBACK_DENIAL_MARKER_BYTES
171
+ ) {
172
+ throw new Error("Local state marker is unsafe.");
173
+ }
174
+ assertCurrentOwner(metadata.uid);
175
+ if (isPosix() && (metadata.mode & 0o077) !== 0) {
176
+ throw new Error("Local state marker permissions are not private.");
177
+ }
178
+ }
179
+
180
+ function readBoundedDescriptor(descriptor) {
181
+ const chunks = [];
182
+ let total = 0;
183
+ while (total <= MAX_FEEDBACK_DENIAL_MARKER_BYTES) {
184
+ const chunk = Buffer.allocUnsafe(
185
+ Math.min(1024, MAX_FEEDBACK_DENIAL_MARKER_BYTES + 1 - total),
186
+ );
187
+ const bytesRead = readSync(descriptor, chunk, 0, chunk.length, null);
188
+ if (bytesRead === 0) break;
189
+ chunks.push(chunk.subarray(0, bytesRead));
190
+ total += bytesRead;
191
+ }
192
+ if (total > MAX_FEEDBACK_DENIAL_MARKER_BYTES) {
193
+ throw new Error("Local state marker exceeds its size limit.");
194
+ }
195
+ return Buffer.concat(chunks, total).toString("utf8");
196
+ }
197
+
198
+ function readMarker(path, expectedDigest) {
199
+ assertPrivateDirectory(dirname(dirname(path)));
200
+ assertPrivateDirectory(dirname(path));
201
+ const before = lstatSync(path);
202
+ assertPrivateMarker(before);
203
+ const descriptor = openSync(
204
+ path,
205
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
206
+ );
207
+ try {
208
+ const opened = fstatSync(descriptor);
209
+ assertPrivateMarker(opened);
210
+ if (before.dev !== opened.dev || before.ino !== opened.ino) {
211
+ throw new Error("Local state marker changed while opening.");
212
+ }
213
+ const parsed = JSON.parse(readBoundedDescriptor(descriptor));
214
+ if (
215
+ !parsed ||
216
+ typeof parsed !== "object" ||
217
+ Array.isArray(parsed) ||
218
+ parsed.version !== FEEDBACK_DENIAL_VERSION ||
219
+ parsed.event_digest !== `sha256:${expectedDigest}` ||
220
+ typeof parsed.acknowledged_at !== "string" ||
221
+ typeof parsed.expires_at !== "string" ||
222
+ !Number.isFinite(Date.parse(parsed.acknowledged_at)) ||
223
+ !Number.isFinite(Date.parse(parsed.expires_at))
224
+ ) {
225
+ throw new Error("Local state marker is malformed.");
226
+ }
227
+ return parsed;
228
+ } finally {
229
+ closeSync(descriptor);
230
+ }
231
+ }
232
+
233
+ function removeExpiredMarker(path, marker, now) {
234
+ if (Date.parse(marker.expires_at) > now) return false;
235
+ rmSync(path, { force: true });
236
+ return true;
237
+ }
238
+
239
+ function cleanupExpiredMarkers(directory, now) {
240
+ const handle = opendirSync(directory);
241
+ let markerCount = 0;
242
+ let visited = 0;
243
+ try {
244
+ while (visited <= MAX_FEEDBACK_DENIAL_MARKERS) {
245
+ const entry = handle.readSync();
246
+ if (!entry) break;
247
+ visited += 1;
248
+ if (!entry.isFile() || !MARKER_NAME_PATTERN.test(entry.name)) continue;
249
+ markerCount += 1;
250
+ const digest = entry.name.slice(0, -".json".length);
251
+ const path = join(directory, entry.name);
252
+ try {
253
+ if (removeExpiredMarker(path, readMarker(path, digest), now)) {
254
+ markerCount -= 1;
255
+ }
256
+ } catch {
257
+ // One corrupt marker cannot acknowledge or remove another event.
258
+ }
259
+ }
260
+ if (visited > MAX_FEEDBACK_DENIAL_MARKERS) {
261
+ throw new Error("Local acknowledgement storage exceeds its entry limit.");
262
+ }
263
+ } finally {
264
+ handle.closeSync();
265
+ }
266
+ if (markerCount >= MAX_FEEDBACK_DENIAL_MARKERS) {
267
+ throw new Error("Local acknowledgement storage is full.");
268
+ }
269
+ }
270
+
271
+ function writeMarkerAtomically(path, marker) {
272
+ const temporaryPath = `${path}.${randomBytes(8).toString("hex")}.tmp`;
273
+ let descriptor;
274
+ try {
275
+ descriptor = openSync(
276
+ temporaryPath,
277
+ constants.O_WRONLY |
278
+ constants.O_CREAT |
279
+ constants.O_EXCL |
280
+ (constants.O_NOFOLLOW ?? 0),
281
+ 0o600,
282
+ );
283
+ writeFileSync(descriptor, `${JSON.stringify(marker)}\n`, {
284
+ encoding: "utf8",
285
+ });
286
+ fsyncSync(descriptor);
287
+ closeSync(descriptor);
288
+ descriptor = undefined;
289
+ renameSync(temporaryPath, path);
290
+ } catch (error) {
291
+ if (descriptor !== undefined) {
292
+ try {
293
+ closeSync(descriptor);
294
+ } catch {
295
+ // Preserve the original persistence failure.
296
+ }
297
+ }
298
+ try {
299
+ rmSync(temporaryPath, { force: true });
300
+ } catch {
301
+ // Preserve the original persistence failure.
302
+ }
303
+ throw error;
304
+ }
305
+ }
306
+
307
+ export function acknowledgeFeedbackDenial(input, env = process.env) {
308
+ const normalized = normalizeInput(input);
309
+ if (!normalized) {
310
+ throw new TypeError("Invalid feedback denial acknowledgement input.");
311
+ }
312
+ const digest = exactEventDigest(normalized);
313
+ const directory = markerDirectory(env);
314
+ const path = markerPath(normalized, env);
315
+ const now = Date.now();
316
+ try {
317
+ ensurePrivateDirectory(usageDirectory(env));
318
+ ensurePrivateDirectory(directory);
319
+ cleanupExpiredMarkers(directory, now);
320
+ try {
321
+ const existing = readMarker(path, digest);
322
+ if (Date.parse(existing.expires_at) > now) {
323
+ return {
324
+ status: "acknowledged_host_denial",
325
+ acknowledged: true,
326
+ submitted: false,
327
+ local_only: true,
328
+ already_acknowledged: true,
329
+ expires_at: existing.expires_at,
330
+ };
331
+ }
332
+ rmSync(path, { force: true });
333
+ } catch (error) {
334
+ if (error?.code !== "ENOENT") throw error;
335
+ }
336
+ const acknowledgedAt = new Date(now).toISOString();
337
+ const expiresAt = new Date(
338
+ now + FEEDBACK_DENIAL_RETENTION_MS,
339
+ ).toISOString();
340
+ writeMarkerAtomically(path, {
341
+ version: FEEDBACK_DENIAL_VERSION,
342
+ event_digest: `sha256:${digest}`,
343
+ acknowledged_at: acknowledgedAt,
344
+ expires_at: expiresAt,
345
+ });
346
+ const persisted = readMarker(path, digest);
347
+ if (Date.parse(persisted.expires_at) <= now) {
348
+ throw new Error("Local acknowledgement expired before persistence.");
349
+ }
350
+ return {
351
+ status: "acknowledged_host_denial",
352
+ acknowledged: true,
353
+ submitted: false,
354
+ local_only: true,
355
+ already_acknowledged: false,
356
+ expires_at: persisted.expires_at,
357
+ };
358
+ } catch (error) {
359
+ throw new FeedbackDenialStorageError();
360
+ }
361
+ }
362
+
363
+ export function feedbackDenialAcknowledged(input, env = process.env) {
364
+ const normalized = normalizeInput(input);
365
+ if (!normalized) return false;
366
+ const digest = exactEventDigest(normalized);
367
+ const path = markerPath(normalized, env);
368
+ try {
369
+ const marker = readMarker(path, digest);
370
+ const now = Date.now();
371
+ if (removeExpiredMarker(path, marker, now)) return false;
372
+ return true;
373
+ } catch {
374
+ return false;
375
+ }
376
+ }