@d86e/hive-panel 1.0.28 → 1.0.30

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/src/cache.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { execFile } from "node:child_process";
4
- import { isInitialised } from "./data.js";
4
+ import { encodeTaskCursor, decodeTaskCursor, isTaskAfterCursor, isInitialised } from "./data.js";
5
+ import { eventLineKey, parseEventLineKey } from "./event-store.js";
5
6
 
6
7
  export const SNAPSHOT_TTL_MS = 2_000;
7
8
  export const EVENT_TAIL_MAX = 5_000;
@@ -39,24 +40,22 @@ function compareTasks(left, right) {
39
40
  return String(right?.id || "").localeCompare(String(left?.id || ""));
40
41
  }
41
42
 
42
- function lanePage(rows, stats, state, cursor, limit, search) {
43
- const query = String(search || "").trim().toLowerCase();
44
- let lane = rows.filter((task) => (task.state || "pending") === state);
45
- if (query) {
46
- lane = lane.filter((task) => String(task.id || "").toLowerCase().includes(query)
47
- || String(task.title || "").toLowerCase().includes(query));
48
- }
43
+ function lanePage(rows, stats, state, cursor, limit) {
44
+ const lane = rows.filter((task) => (task.state || "pending") === state);
49
45
  lane.sort(compareTasks);
50
46
  const total = Number(stats?.byState?.[state]);
51
- const offset = Math.max(0, Math.floor(Number(cursor) || 0));
47
+ const totalRows = Number.isFinite(total) && total >= 0 ? total : lane.length;
48
+ const parsed = decodeTaskCursor(cursor);
49
+ const remaining = parsed && parsed.legacyOffset !== undefined
50
+ ? lane.slice(parsed.legacyOffset)
51
+ : lane.filter((task) => isTaskAfterCursor(task, parsed));
52
52
  const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Math.floor(Number(limit) || LANE_PAGE_LIMIT)));
53
- const items = lane.slice(offset, offset + size);
54
- const next = offset + items.length;
53
+ const items = remaining.slice(0, size);
55
54
  return {
56
55
  items,
57
- total: Number.isFinite(total) && total >= 0 ? total : lane.length,
58
- cursor: next,
59
- hasMore: next < (Number.isFinite(total) && total >= 0 ? total : lane.length),
56
+ total: totalRows,
57
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
58
+ hasMore: remaining.length > items.length,
60
59
  state,
61
60
  };
62
61
  }
@@ -79,7 +78,7 @@ export class SnapshotCache {
79
78
  this.building = null;
80
79
  this.lastBuildAt = 0;
81
80
  this.metrics = { builds: 0, versionChecks: 0, eventBytesRead: 0, eventLinesParsed: 0, cliCalls: 0 };
82
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
81
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
83
82
  }
84
83
 
85
84
  eventsPath() { return path.join(this.repo, ".hive", "events.jsonl"); }
@@ -102,13 +101,13 @@ export class SnapshotCache {
102
101
  let stat = null;
103
102
  try { stat = this.statSync(file); } catch { stat = null; }
104
103
  if (stat === null) {
105
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
104
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
106
105
  return;
107
106
  }
108
107
  const size = Number(stat.size) || 0;
109
108
  if (size < this.events.offset || (this.events.mtimeMs !== null && stat.mtimeMs < this.events.mtimeMs)) {
110
109
  // Truncated/rewritten log: restart the byte cursor.
111
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
110
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
112
111
  }
113
112
  if (size === this.events.offset && stat.mtimeMs === this.events.mtimeMs) return;
114
113
  let bytes = "";
@@ -127,10 +126,14 @@ export class SnapshotCache {
127
126
  const lines = bytes.split("\n");
128
127
  lines.pop(); // an incomplete trailing line is left for the next read
129
128
  for (const line of lines) {
129
+ if (line === "") continue;
130
+ const lineIndex = this.events.lineIndex;
131
+ this.events.lineIndex += 1;
130
132
  if (!line.trim()) continue;
131
133
  this.metrics.eventLinesParsed += 1;
132
134
  const event = parseJson(line, null);
133
135
  if (event === null || typeof event !== "object") continue;
136
+ event.key = eventLineKey(lineIndex, line);
134
137
  this.events.total += 1;
135
138
  const kind = String(event.kind || "");
136
139
  if (kind) this.events.kinds.set(kind, (this.events.kinds.get(kind) || 0) + 1);
@@ -231,7 +234,10 @@ export class SnapshotCache {
231
234
  const total = data.eventTotal;
232
235
  const tailCount = Math.min(EVENT_TAIL_MAX, total);
233
236
  const firstIndex = total - tailCount;
234
- const start = Math.max(0, Math.min(total, Math.floor(Number(after) || 0)));
237
+ const parsedKey = parseEventLineKey(after);
238
+ const start = parsedKey !== null
239
+ ? parsedKey.index + 1
240
+ : Math.max(0, Math.min(total, Math.floor(Number(after) || 0)));
235
241
  const wanted = String(kind || "");
236
242
  const fresh = [];
237
243
  for (let index = Math.max(start, firstIndex); index < total; index += 1) {
@@ -240,18 +246,37 @@ export class SnapshotCache {
240
246
  }
241
247
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
242
248
  const items = fresh.slice(Math.max(0, fresh.length - size)).reverse();
243
- return { items, total, cursor: total, hasMore: fresh.length > size, kind: wanted, dropped: start < firstIndex };
249
+ const latest = data.events[0];
250
+ const cursor = latest && latest.key ? latest.key : String(after || "");
251
+ return {
252
+ items,
253
+ total,
254
+ cursor,
255
+ hasMore: fresh.length > size,
256
+ kind: wanted,
257
+ dropped: parsedKey !== null ? parsedKey.index < firstIndex : start < firstIndex,
258
+ };
244
259
  }
245
- async tasksPage({ state = "", cursor = 0, limit = LANE_PAGE_LIMIT, search = "" } = {}) {
260
+ async tasksPage({ state = "", cursor = "", limit = LANE_PAGE_LIMIT } = {}) {
246
261
  const data = await this.snapshot();
247
262
  const all = Array.isArray(data.allTasks) ? data.allTasks : data.tasks;
248
263
  if (!state) {
249
- const offset = Math.max(0, Number(cursor) || 0);
264
+ const sorted = [...all].sort(compareTasks);
265
+ const parsed = decodeTaskCursor(cursor);
266
+ const remaining = parsed && parsed.legacyOffset !== undefined
267
+ ? sorted.slice(parsed.legacyOffset)
268
+ : sorted.filter((task) => isTaskAfterCursor(task, parsed));
250
269
  const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Number(limit) || LANE_PAGE_LIMIT));
251
- const items = [...all].sort(compareTasks).slice(offset, offset + size);
252
- return { items, total: all.length, cursor: offset + items.length, hasMore: offset + items.length < all.length, state: "", search: String(search || "") };
270
+ const items = remaining.slice(0, size);
271
+ return {
272
+ items,
273
+ total: sorted.length,
274
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
275
+ hasMore: remaining.length > items.length,
276
+ state: "",
277
+ };
253
278
  }
254
- return lanePage(all, data.stats, String(state), cursor, limit, search);
279
+ return lanePage(all, data.stats, String(state), cursor, limit);
255
280
  }
256
281
 
257
282
  async eventsPage({ cursor = 0, limit = 80, kind = "" } = {}) {
package/src/data.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
+ import { eventLineKey, parseEventLineKey } from "./event-store.js";
4
5
 
5
6
  function run(file, args, cwd) {
6
7
  const result = spawnSync(file, args, { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
@@ -24,8 +25,12 @@ export const EVENT_PAGE_LIMIT = 80;
24
25
  export function readEventRows(repo) {
25
26
  const file = path.join(repo, ".hive", "events.jsonl");
26
27
  if (!fs.existsSync(file)) return [];
27
- return fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => {
28
- try { return JSON.parse(line); } catch { return null; }
28
+ return fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((line, index) => {
29
+ try {
30
+ const event = JSON.parse(line);
31
+ event.key = eventLineKey(index, line);
32
+ return event;
33
+ } catch { return null; }
29
34
  }).filter(Boolean).reverse();
30
35
  }
31
36
 
@@ -125,6 +130,38 @@ function laneTotal(stats, state, rows) {
125
130
  return Number.isFinite(value) && value >= 0 ? value : rows.length;
126
131
  }
127
132
 
133
+ /** Stable pagination cursor: sort timestamp plus task id, base64url encoded. */
134
+ export function encodeTaskCursor(task) {
135
+ const time = taskSortTime(task);
136
+ return Buffer.from(JSON.stringify([Number.isFinite(time) ? time : null, String(task && task.id || "")]), "utf8").toString("base64url");
137
+ }
138
+
139
+ /** Decode a cursor; numeric values are accepted for backwards compatibility. */
140
+ export function decodeTaskCursor(value) {
141
+ const text = String(value === undefined || value === null ? "" : value).trim();
142
+ if (text === "" || text === "0") return null;
143
+ if (/^\d+$/.test(text)) return { legacyOffset: Number(text) };
144
+ try {
145
+ const parsed = JSON.parse(Buffer.from(text, "base64url").toString("utf8"));
146
+ if (!Array.isArray(parsed) || parsed.length !== 2) return null;
147
+ const time = parsed[0] === null ? null : Number(parsed[0]);
148
+ if (time !== null && !Number.isFinite(time)) return null;
149
+ return { time, id: String(parsed[1] ?? "") };
150
+ } catch { return null; }
151
+ }
152
+
153
+ /** True when the task sorts after the cursor in newest-first order. */
154
+ export function isTaskAfterCursor(task, cursor) {
155
+ if (!cursor || cursor.legacyOffset !== undefined) return true;
156
+ const time = taskSortTime(task);
157
+ const id = String(task && task.id || "");
158
+ if (cursor.time === null) return !Number.isFinite(time) && id.localeCompare(cursor.id) < 0;
159
+ if (!Number.isFinite(time)) return true;
160
+ if (time < cursor.time) return true;
161
+ if (time > cursor.time) return false;
162
+ return id.localeCompare(cursor.id) < 0;
163
+ }
164
+
128
165
  export function paginateTasks(tasks, stats, limit = TASK_PAGE_LIMIT) {
129
166
  const size = Number.isFinite(limit) && limit > 0 ? Math.min(200, Math.floor(limit)) : TASK_PAGE_LIMIT;
130
167
  const lanePages = {};
@@ -137,30 +174,31 @@ export function paginateTasks(tasks, stats, limit = TASK_PAGE_LIMIT) {
137
174
  lanePages[state] = {
138
175
  items,
139
176
  total,
140
- cursor: items.length,
177
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
141
178
  hasMore: items.length < total,
142
179
  };
143
180
  }
144
181
  return lanePages;
145
182
  }
146
183
 
147
- export function snapshotTasksPage(repo, { state = "", cursor = 0, limit = TASK_PAGE_LIMIT, search = "" } = {}, env = process.env) {
184
+ export function snapshotTasksPage(repo, { state = "", cursor = "", limit = TASK_PAGE_LIMIT } = {}, env = process.env) {
148
185
  let rows = readTasks(repo, env);
149
- const query = String(search || "").trim().toLowerCase();
150
186
  if (state) rows = rows.filter((task) => (task.state || "pending") === state);
151
- if (query) {
152
- rows = rows.filter((task) =>
153
- String(task.id || "").toLowerCase().includes(query) ||
154
- String(task.title || "").toLowerCase().includes(query),
155
- );
156
- }
157
187
  rows.sort(compareTasksNewestFirst);
158
188
  const total = rows.length;
159
- const offset = Math.max(0, Math.floor(Number(cursor) || 0));
189
+ const parsed = decodeTaskCursor(cursor);
190
+ const remaining = parsed && parsed.legacyOffset !== undefined
191
+ ? rows.slice(parsed.legacyOffset)
192
+ : rows.filter((task) => isTaskAfterCursor(task, parsed));
160
193
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || TASK_PAGE_LIMIT)));
161
- const items = rows.slice(offset, offset + size);
162
- const next = offset + items.length;
163
- return { items, total, cursor: next, hasMore: next < total, state: String(state || ""), search: String(search || "") };
194
+ const items = remaining.slice(0, size);
195
+ return {
196
+ items,
197
+ total,
198
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
199
+ hasMore: remaining.length > items.length,
200
+ state: String(state || ""),
201
+ };
164
202
  }
165
203
 
166
204
  export function findTaskById(repo, id, env = process.env) {
@@ -220,13 +258,22 @@ export function readNewEvents(repo, { after = 0, limit = 50, kind = "" } = {}) {
220
258
  } catch {
221
259
  lines = [];
222
260
  }
223
- const cursor = Math.max(0, Math.floor(Number(after) || 0));
261
+ const parsedKey = parseEventLineKey(after);
262
+ const start = parsedKey !== null
263
+ ? parsedKey.index + 1
264
+ : Math.max(0, Math.floor(Number(after) || 0));
224
265
  const wanted = String(kind || "");
225
266
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
226
267
  const fresh = [];
227
- for (let index = Math.max(cursor, 0); index < lines.length; index += 1) {
268
+ let latestKey = "";
269
+ for (let index = 0; index < lines.length; index += 1) {
270
+ const line = lines[index];
271
+ const key = eventLineKey(index, line);
272
+ latestKey = key;
273
+ if (index < start) continue;
228
274
  try {
229
- const event = JSON.parse(lines[index]);
275
+ const event = JSON.parse(line);
276
+ event.key = key;
230
277
  if (wanted && String(event.kind || "") !== wanted) continue;
231
278
  fresh.push(event);
232
279
  } catch {
@@ -236,9 +283,10 @@ export function readNewEvents(repo, { after = 0, limit = 50, kind = "" } = {}) {
236
283
  return {
237
284
  items: fresh.slice(-size).reverse(),
238
285
  total: lines.length,
239
- cursor: lines.length,
286
+ cursor: latestKey || String(after || ""),
240
287
  hasMore: fresh.length > size,
241
288
  kind: wanted,
289
+ dropped: false,
242
290
  };
243
291
  }
244
292
 
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
 
@@ -13,29 +14,38 @@ function readLines(file) {
13
14
  }
14
15
  }
15
16
 
16
- function eventKey(event) {
17
- const raw = event && typeof event === "object" ? event : {};
18
- return JSON.stringify([String(raw.ts ?? ""), String(raw.kind ?? ""), String(raw.actor ?? ""), String(raw.task ?? "")]);
17
+ /**
18
+ * Stable identity of one event log row: 0-based line index plus a short hash of
19
+ * the raw line. Identical event objects on different lines therefore stay
20
+ * distinct, and a stale key can never delete a different row.
21
+ * @param {number} index
22
+ * @param {string} line
23
+ * @returns {string}
24
+ */
25
+ export function eventLineKey(index, line) {
26
+ const hash = crypto.createHash("sha1").update(String(line)).digest("hex").slice(0, 16);
27
+ return String(Math.max(0, Math.floor(Number(index) || 0))) + ":" + hash;
19
28
  }
20
29
 
21
- /** Delete exact event keys, returning one result per key. Best effort, never throws. */
30
+ /** @param {unknown} key */
31
+ export function parseEventLineKey(key) {
32
+ const match = /^(\d+):([0-9a-f]{16})$/.exec(String(key || ""));
33
+ if (!match) return null;
34
+ return { index: Number(match[1]), hash: match[2] };
35
+ }
36
+
37
+ /** Delete exact event rows, returning one result per key. Best effort, never throws. */
22
38
  export function deleteEvents(repo, keys) {
23
39
  const wanted = new Set((Array.isArray(keys) ? keys : []).map(String));
24
40
  const file = eventFile(repo);
25
41
  const lines = readLines(file);
26
42
  const kept = [];
27
43
  const removed = new Set();
28
- let parseErrors = 0;
29
- for (const line of lines) {
30
- try {
31
- const event = JSON.parse(line);
32
- const key = eventKey(event);
33
- if (wanted.has(key)) removed.add(key);
34
- else kept.push(line);
35
- } catch {
36
- parseErrors += 1;
37
- kept.push(line);
38
- }
44
+ for (let index = 0; index < lines.length; index += 1) {
45
+ const line = lines[index];
46
+ const key = eventLineKey(index, line);
47
+ if (wanted.has(key)) removed.add(key);
48
+ else kept.push(line);
39
49
  }
40
50
  if (removed.size > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
41
51
  return [...wanted].map((key) => ({
@@ -66,3 +76,19 @@ export function pruneEventsBefore(repo, before) {
66
76
  if (deleted > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
67
77
  return [{ key: "before", ok: true, error: "", deleted }];
68
78
  }
79
+
80
+ /** Count events strictly older than the cutoff, for the UI confirmation. */
81
+ export function countEventsBefore(repo, before) {
82
+ const cutoff = Date.parse(before);
83
+ if (!Number.isFinite(cutoff)) return { ok: false, error: "invalid timestamp", count: 0 };
84
+ let count = 0;
85
+ for (const line of readLines(eventFile(repo))) {
86
+ try {
87
+ const ts = Date.parse(JSON.parse(line).ts);
88
+ if (Number.isFinite(ts) && ts < cutoff) count += 1;
89
+ } catch {
90
+ // Invalid lines are preserved by prune; they are not counted as prunable.
91
+ }
92
+ }
93
+ return { ok: true, count };
94
+ }
package/src/server.js CHANGED
@@ -5,6 +5,7 @@ import { execFile } from "node:child_process";
5
5
  import { isInitialised, status } from "./data.js";
6
6
  import { createSnapshotCache } from "./cache.js";
7
7
  import { listActions, runAction } from "./actions.js";
8
+ import { deleteEvents, pruneEventsBefore, countEventsBefore } from "./event-store.js";
8
9
 
9
10
  const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml" };
10
11
 
@@ -31,6 +32,7 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
31
32
  const tasks = env.HIVE_TASKS_BIN || "hive-tasks";
32
33
  const snapshotCache = createSnapshotCache({ repo, env });
33
34
  const server = http.createServer(async (request, response) => {
35
+ try {
34
36
  const url = new URL(request.url, "http://localhost");
35
37
 
36
38
  if (url.pathname === "/api/health") {
@@ -87,6 +89,12 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
87
89
  return response.end(JSON.stringify(page));
88
90
  }
89
91
 
92
+ if (request.method === "GET" && url.pathname === "/api/events" && url.searchParams.get("before") !== null) {
93
+ const counted = countEventsBefore(repo, url.searchParams.get("before") || "");
94
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
95
+ return response.end(JSON.stringify(counted));
96
+ }
97
+
90
98
  if (request.method === "GET" && url.pathname === "/api/events") {
91
99
  const page = await snapshotCache.eventsPage({
92
100
  cursor: url.searchParams.get("cursor") || "0",
@@ -102,14 +110,19 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
102
110
  state: url.searchParams.get("state") || "",
103
111
  cursor: url.searchParams.get("cursor") || "0",
104
112
  limit: url.searchParams.get("limit") || "200",
105
- search: url.searchParams.get("search") || url.searchParams.get("q") || "",
106
113
  });
107
114
  response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
108
115
  return response.end(JSON.stringify(page));
109
116
  }
110
117
 
111
118
  if (request.method === "GET" && url.pathname.startsWith("/api/tasks/")) {
112
- const id = decodeURIComponent(url.pathname.slice("/api/tasks/".length));
119
+ let id;
120
+ try {
121
+ id = decodeURIComponent(url.pathname.slice("/api/tasks/".length));
122
+ } catch {
123
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
124
+ return response.end(JSON.stringify({ ok: false, error: "invalid task id encoding" }));
125
+ }
113
126
  const cached = await snapshotCache.snapshot();
114
127
  const allTasks = Array.isArray(cached.allTasks) ? cached.allTasks : cached.tasks;
115
128
  const task = allTasks.find((entry) => String(entry.id) === String(id)) ?? null;
@@ -174,6 +187,14 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
174
187
  }
175
188
  response.writeHead(200, { "content-type": MIME[path.extname(file)] || "application/octet-stream", "cache-control": "no-store" });
176
189
  fs.createReadStream(file).pipe(response);
190
+ } catch (error) {
191
+ if (response.headersSent) {
192
+ response.destroy();
193
+ return;
194
+ }
195
+ response.writeHead(500, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
196
+ response.end(JSON.stringify({ ok: false, error: "internal server error" }));
197
+ }
177
198
  });
178
199
 
179
200
  return server;