@andares/pi-toolkits 1.0.1 → 1.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.
@@ -16,17 +16,13 @@
16
16
  * never called `record_change` still gets a correct (if less informative)
17
17
  * acceptance queue.
18
18
  */
19
+ import { join } from "node:path";
19
20
  import {
20
- appendFileSync,
21
- closeSync,
22
- existsSync,
23
- mkdirSync,
24
- openSync,
25
- readFileSync,
26
- readSync,
27
- statSync,
28
- } from "node:fs";
29
- import { dirname, join } from "node:path";
21
+ appendLedgerLine,
22
+ newLedgerEventId,
23
+ parseLedgerLines,
24
+ readLedgerLines,
25
+ } from "../../lib/event-ledger.js";
30
26
  import type { RecordEntry } from "./records.js";
31
27
 
32
28
  export const LEDGER_VERSION = 1;
@@ -179,61 +175,21 @@ export function ledgerPath(root: string): string {
179
175
 
180
176
  /** Monotonic-enough id: time plus 6 random base36 chars. */
181
177
  export function newEventId(now: Date = new Date()): string {
182
- const random = Math.random().toString(36).slice(2, 8).padEnd(6, "0");
183
- return `e-${now.getTime().toString(36)}-${random}`;
178
+ return newLedgerEventId(now);
184
179
  }
185
180
 
186
181
  /**
187
- * Append one event. The file always ends with a newline: if a previous write
188
- * was interrupted mid-line, this repairs the boundary instead of gluing two
189
- * JSON objects together (a gluing would silently drop both on read).
182
+ * Append one event. The line boundary is repaired by the shared ledger helper:
183
+ * an interrupted write must not glue two JSON objects into one line, which
184
+ * would silently drop both on read.
190
185
  */
191
186
  export function appendEvent(file: string, event: UatEvent): void {
192
- mkdirSync(dirname(file), { recursive: true });
193
- const line = JSON.stringify(event);
194
- if (existsSync(file) && statSync(file).size > 0 && !endsWithNewline(file)) {
195
- appendFileSync(file, `\n${line}\n`, "utf8");
196
- return;
197
- }
198
- appendFileSync(file, `${line}\n`, "utf8");
199
- }
200
-
201
- function endsWithNewline(file: string): boolean {
202
- const fd = openSync(file, "r");
203
- try {
204
- const size = statSync(file).size;
205
- const buffer = Buffer.alloc(1);
206
- readSync(fd, buffer, 0, 1, size - 1);
207
- return buffer[0] === 0x0a;
208
- } finally {
209
- closeSync(fd);
210
- }
187
+ appendLedgerLine(file, event);
211
188
  }
212
189
 
213
190
  /** Parse the stream, skipping malformed lines and duplicate ids. */
214
191
  export function parseEvents(raw: string): { events: UatEvent[]; skipped: number } {
215
- const events: UatEvent[] = [];
216
- const seen = new Set<string>();
217
- let skipped = 0;
218
- for (const line of raw.split("\n")) {
219
- const trimmed = line.trim();
220
- if (trimmed === "") continue;
221
- let parsed: unknown;
222
- try {
223
- parsed = JSON.parse(trimmed);
224
- } catch {
225
- skipped += 1;
226
- continue;
227
- }
228
- if (!isEvent(parsed)) {
229
- skipped += 1;
230
- continue;
231
- }
232
- if (seen.has(parsed.id)) continue;
233
- seen.add(parsed.id);
234
- events.push(parsed);
235
- }
236
- return { events, skipped };
192
+ return parseLedgerLines(raw, isEvent);
237
193
  }
238
194
 
239
195
  function isEvent(value: unknown): value is UatEvent {
@@ -298,12 +254,7 @@ function isEvent(value: unknown): value is UatEvent {
298
254
  }
299
255
 
300
256
  export function readEvents(file: string): { events: UatEvent[]; skipped: number } {
301
- if (!existsSync(file)) return { events: [], skipped: 0 };
302
- try {
303
- return parseEvents(readFileSync(file, "utf8"));
304
- } catch {
305
- return { events: [], skipped: 1 };
306
- }
257
+ return readLedgerLines(file, isEvent);
307
258
  }
308
259
 
309
260
  /** Latest candidate metadata per report id (last write wins). */
package/src/index.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  * - init — agent memory framework install / adoption (/ask-init)
16
16
  * - uat — acceptance ledger and browser page (/ask-uat, record_change)
17
17
  * - quit-guard — quit watchdog: force-exit when pi's shutdown hangs (/quit-guard)
18
+ * - keep — session backlog: keep-quit / keep-load / keep-drop
18
19
  * - whats-new — automatic release notes on the first start after an upgrade
19
20
  *
20
21
  * `ask` and `permission` are independent gates on one bus: each answers its own
@@ -29,6 +30,7 @@ import { registerAutostart } from "./features/autostart/index.js";
29
30
  import { registerCompact } from "./features/compact/index.js";
30
31
  import { registerFavorites } from "./features/favorites/index.js";
31
32
  import { registerInit } from "./features/init/index.js";
33
+ import { registerKeep } from "./features/keep/index.js";
32
34
  import { registerPermission } from "./features/permission/index.js";
33
35
  import { registerSpec } from "./features/spec/index.js";
34
36
  import { registerQuitGuard } from "./features/quit-guard/index.js";
@@ -54,6 +56,7 @@ export default function piToolkits(pi: ExtensionAPI): void {
54
56
  registerCompact(pi);
55
57
  registerFavorites(pi);
56
58
  registerInit(pi);
59
+ registerKeep(pi);
57
60
  registerQuitGuard(pi);
58
61
  registerReview(pi);
59
62
  registerStash(pi);
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Append-only event ledger — the mechanics two features share.
3
+ *
4
+ * Both the acceptance ledger (`.agents/uat/ledger.jsonl`) and the keep ledger
5
+ * (`<agent-dir>/pi-toolkits-keep/keep.jsonl`) are the same shape: one JSON
6
+ * object per line, deduplicated by `id`, read whole and folded into state by a
7
+ * pure function. Three properties are load-bearing in both places:
8
+ *
9
+ * - appends never rewrite the file, so two processes can add lines at the
10
+ * same time without a lock;
11
+ * - a reader tolerates a malformed or half-written line instead of failing
12
+ * the whole stream;
13
+ * - the line boundary is repaired on append — an interrupted write must not
14
+ * glue two JSON objects into one unparseable line, which would silently
15
+ * drop both records.
16
+ *
17
+ * Only the mechanics live here. Each feature owns its event vocabulary and its
18
+ * validator.
19
+ */
20
+ import {
21
+ appendFileSync,
22
+ closeSync,
23
+ existsSync,
24
+ mkdirSync,
25
+ openSync,
26
+ readFileSync,
27
+ readSync,
28
+ statSync,
29
+ } from "node:fs";
30
+ import { dirname } from "node:path";
31
+
32
+ /** Fields every ledger event carries. */
33
+ export interface LedgerEventBase {
34
+ readonly v: number;
35
+ readonly id: string;
36
+ readonly ts: string;
37
+ }
38
+
39
+ /** Monotonic-enough id: time plus 6 random base36 chars. */
40
+ export function newLedgerEventId(now: Date = new Date()): string {
41
+ const random = Math.random().toString(36).slice(2, 8).padEnd(6, "0");
42
+ return `e-${now.getTime().toString(36)}-${random}`;
43
+ }
44
+
45
+ /**
46
+ * Append one event. The file always ends with a newline: if a previous write
47
+ * was interrupted mid-line, this repairs the boundary instead of gluing two
48
+ * JSON objects together.
49
+ */
50
+ export function appendLedgerLine(file: string, event: unknown): void {
51
+ mkdirSync(dirname(file), { recursive: true });
52
+ const line = JSON.stringify(event);
53
+ if (existsSync(file) && statSync(file).size > 0 && !endsWithNewline(file)) {
54
+ appendFileSync(file, `\n${line}\n`, "utf8");
55
+ return;
56
+ }
57
+ appendFileSync(file, `${line}\n`, "utf8");
58
+ }
59
+
60
+ function endsWithNewline(file: string): boolean {
61
+ const fd = openSync(file, "r");
62
+ try {
63
+ const size = statSync(file).size;
64
+ const buffer = Buffer.alloc(1);
65
+ readSync(fd, buffer, 0, 1, size - 1);
66
+ return buffer[0] === 0x0a;
67
+ } finally {
68
+ closeSync(fd);
69
+ }
70
+ }
71
+
72
+ /** Parse the stream, skipping malformed lines and duplicate ids. */
73
+ export function parseLedgerLines<T extends LedgerEventBase>(
74
+ raw: string,
75
+ isEvent: (value: unknown) => value is T,
76
+ ): { events: T[]; skipped: number } {
77
+ const events: T[] = [];
78
+ const seen = new Set<string>();
79
+ let skipped = 0;
80
+ for (const line of raw.split("\n")) {
81
+ const trimmed = line.trim();
82
+ if (trimmed === "") continue;
83
+ let parsed: unknown;
84
+ try {
85
+ parsed = JSON.parse(trimmed);
86
+ } catch {
87
+ skipped += 1;
88
+ continue;
89
+ }
90
+ if (!isEvent(parsed)) {
91
+ skipped += 1;
92
+ continue;
93
+ }
94
+ if (seen.has(parsed.id)) continue;
95
+ seen.add(parsed.id);
96
+ events.push(parsed);
97
+ }
98
+ return { events, skipped };
99
+ }
100
+
101
+ /** Read and parse a ledger file. A missing or unreadable file is empty. */
102
+ export function readLedgerLines<T extends LedgerEventBase>(
103
+ file: string,
104
+ isEvent: (value: unknown) => value is T,
105
+ ): { events: T[]; skipped: number } {
106
+ if (!existsSync(file)) return { events: [], skipped: 0 };
107
+ try {
108
+ return parseLedgerLines(readFileSync(file, "utf8"), isEvent);
109
+ } catch {
110
+ return { events: [], skipped: 1 };
111
+ }
112
+ }