hive-tasks 1.8.1 → 1.10.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/src/git.js CHANGED
@@ -21,6 +21,25 @@ export function out(args, opts) {
21
21
  return git(args, opts).stdout.trim();
22
22
  }
23
23
 
24
+ /**
25
+ * Run git and return stdout as a Buffer, for binary-framed output such as
26
+ * `cat-file --batch`. Input may be a string or Buffer.
27
+ */
28
+ export function gitBuffer(args, { cwd, env, input, allowFail = false } = {}) {
29
+ const result = spawnSync("git", args, {
30
+ cwd,
31
+ env: env ? { ...process.env, ...env } : process.env,
32
+ input,
33
+ maxBuffer: 512 * 1024 * 1024,
34
+ });
35
+ if (result.error) throw result.error;
36
+ if (!allowFail && result.status !== 0) {
37
+ const detail = String(result.stderr || "").trim();
38
+ throw new Error("git " + args.join(" ") + " failed (exit " + result.status + ")" + (detail ? ": " + detail : ""));
39
+ }
40
+ return result;
41
+ }
42
+
24
43
  export function ok(args, opts) {
25
44
  return git(args, { ...opts, allowFail: true }).status === 0;
26
45
  }
package/src/lease.js CHANGED
@@ -128,6 +128,18 @@ export function claimLeases(repo, { paths, agent, ttlMs, taskId }) {
128
128
  return { granted: true, keys, overlaps };
129
129
  }
130
130
 
131
+ /** Every announcement currently on the board: [{ key, value }]. */
132
+ export function listLeases(repo) {
133
+ const raw = git(["for-each-ref", "refs/hive/v1/lease", "--format=%(refname)"], { cwd: repo.top }).stdout.trim();
134
+ if (!raw) return [];
135
+ const prefix = NS + "/lease/";
136
+ return raw
137
+ .split("\n")
138
+ .filter((ref) => ref.endsWith("/" + KEY_LEAF))
139
+ .map((ref) => ({ key: ref.slice(prefix.length, -(KEY_LEAF.length + 1)), value: readBlob(repo, ref) }))
140
+ .filter((entry) => entry.value);
141
+ }
142
+
131
143
  export function releaseLeases(repo, { paths, agent }) {
132
144
  const released = [];
133
145
  for (const key of paths.map(toKey)) {
package/src/store.js CHANGED
@@ -1,30 +1,236 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
- import { git, out } from "./git.js";
4
+ import { git, gitBuffer, out } from "./git.js";
5
5
 
6
6
  export const TASKS_REF = "refs/hive/v1/tasks";
7
+ /**
8
+ * A lightweight board index next to the task tree: one blob holding
9
+ * [id, state, role, sortTime(ms), createdAt, superseded] per task. It is
10
+ * written with every board write, so list/counts/stats never have to parse
11
+ * every card blob; a reader that finds the index missing or pinned to an older
12
+ * tree rebuilds it once from the task tree (a single `cat-file --batch`).
13
+ */
14
+ export const TASKS_INDEX_REF = "refs/hive/v1/tasks-index";
15
+ export const INDEX_VERSION = 1;
16
+ export const DEFAULT_PAGE_LIMIT = 50;
7
17
 
8
- export function refSha(repo) {
9
- const result = git(["rev-parse", "--verify", "--quiet", TASKS_REF], { cwd: repo.top, allowFail: true });
18
+ function readRefSha(repo, ref) {
19
+ const result = git(["rev-parse", "--verify", "--quiet", ref], { cwd: repo.top, allowFail: true });
10
20
  return result.status === 0 ? result.stdout.trim() : null;
11
21
  }
12
22
 
13
- /** [{ id, value }] from the task tree. An absent ref is an empty board. */
14
- export function listRaw(repo) {
15
- const sha = refSha(repo);
23
+ export function refSha(repo) {
24
+ return readRefSha(repo, TASKS_REF);
25
+ }
26
+
27
+ /** [{ id, blobSha }] for one tree, or [] when the tree is missing. */
28
+ function readTree(repo, sha) {
16
29
  if (!sha) return [];
17
- const raw = git(["ls-tree", sha], { cwd: repo.top }).stdout.trim();
30
+ const result = git(["ls-tree", "-z", sha], { cwd: repo.top, allowFail: true });
31
+ if (result.status !== 0) return [];
32
+ const raw = result.stdout;
18
33
  if (!raw) return [];
19
- return raw.split("\n").map((line) => {
34
+ const entries = [];
35
+ for (const line of raw.split("\u0000")) {
36
+ if (line === "") continue;
20
37
  const tab = line.indexOf("\t");
38
+ if (tab < 0) continue;
21
39
  const meta = line.slice(0, tab).split(/\s+/);
22
- const id = line.slice(tab + 1);
23
- const blob = git(["cat-file", "blob", meta[2]], { cwd: repo.top, allowFail: true }).stdout;
40
+ entries.push({ id: line.slice(tab + 1), blobSha: meta[2] });
41
+ }
42
+ return entries;
43
+ }
44
+
45
+ /**
46
+ * Read blobs by object name in one process: [{ spec }] -> string[].
47
+ * A missing object yields null in its slot. Framing follows git's
48
+ * `<oid> <type> <size>\n<payload>\n` (or `<spec> missing\n`).
49
+ */
50
+ function readBlobs(repo, specs) {
51
+ if (specs.length === 0) return [];
52
+ const result = gitBuffer(["cat-file", "--batch"], { cwd: repo.top, input: specs.join("\n") + "\n", allowFail: true });
53
+ if (result.status !== 0) {
54
+ const detail = String(result.stderr || "").trim();
55
+ throw new Error("git cat-file --batch failed" + (detail ? ": " + detail : ""));
56
+ }
57
+ const buffer = result.stdout;
58
+ const values = [];
59
+ let offset = 0;
60
+ for (let index = 0; index < specs.length; index += 1) {
61
+ const headerEnd = buffer.indexOf(0x0a, offset);
62
+ if (headerEnd < 0) { values.push(null); continue; }
63
+ const header = buffer.toString("utf8", offset, headerEnd);
64
+ offset = headerEnd + 1;
65
+ const parts = header.split(" ");
66
+ if (parts.length < 3) { values.push(null); continue; }
67
+ const size = Number(parts[2]);
68
+ if (!Number.isInteger(size) || size < 0) { values.push(null); continue; }
69
+ values.push(buffer.subarray(offset, offset + size).toString("utf8"));
70
+ offset += size + 1;
71
+ }
72
+ return values;
73
+ }
74
+
75
+ /** [{ id, value }] from the task tree. An absent ref is an empty board. */
76
+ export function listRaw(repo) {
77
+ const sha = refSha(repo);
78
+ if (!sha) return [];
79
+ const entries = readTree(repo, sha);
80
+ if (entries.length === 0) return [];
81
+ const blobs = readBlobs(repo, entries.map((entry) => entry.blobSha));
82
+ const rows = [];
83
+ for (let index = 0; index < entries.length; index += 1) {
84
+ const text = blobs[index];
85
+ if (text === null) continue;
24
86
  let value = null;
25
- try { value = JSON.parse(blob); } catch { value = null; }
26
- return { id, value };
27
- }).filter((entry) => entry.value);
87
+ try { value = JSON.parse(text); } catch { value = null; }
88
+ if (value) rows.push({ id: entries[index].id, value });
89
+ }
90
+ return rows;
91
+ }
92
+
93
+ /** One card by id: a single blob read, never the whole tree. */
94
+ export function readTask(repo, id) {
95
+ const sha = refSha(repo);
96
+ if (!sha) return null;
97
+ const result = git(["cat-file", "blob", sha + ":" + id], { cwd: repo.top, allowFail: true });
98
+ if (result.status !== 0) return null;
99
+ try { return JSON.parse(result.stdout); } catch { return null; }
100
+ }
101
+
102
+ /** Full cards for a known page of ids, in one batch call. */
103
+ export function readTasksByIds(repo, ids) {
104
+ if (!Array.isArray(ids) || ids.length === 0) return [];
105
+ const sha = refSha(repo);
106
+ if (!sha) return [];
107
+ const blobs = readBlobs(repo, ids.map((id) => sha + ":" + id));
108
+ const tasks = [];
109
+ for (const text of blobs) {
110
+ if (text === null) continue;
111
+ try {
112
+ const value = JSON.parse(text);
113
+ if (value) tasks.push(value);
114
+ } catch {
115
+ // A malformed card is skipped, like listRaw does.
116
+ }
117
+ }
118
+ return tasks;
119
+ }
120
+
121
+ /** Sort key shared by the index writer and readers: newest lane change first. */
122
+ export function taskSortTime(task) {
123
+ const value = task && (task.stateChangedAt || task.updatedAt || task.createdAt);
124
+ const time = Date.parse(value || "");
125
+ return Number.isFinite(time) ? time : 0;
126
+ }
127
+
128
+ export function buildIndexEntries(tasks) {
129
+ return tasks.map((task) => [
130
+ task.id,
131
+ task.state,
132
+ task.role || "",
133
+ taskSortTime(task),
134
+ task.createdAt || "",
135
+ task.superseded === true ? 1 : 0,
136
+ ]);
137
+ }
138
+
139
+ function readIndexBlob(repo) {
140
+ const sha = readRefSha(repo, TASKS_INDEX_REF);
141
+ if (!sha) return null;
142
+ const result = git(["cat-file", "blob", sha], { cwd: repo.top, allowFail: true });
143
+ if (result.status !== 0) return null;
144
+ try { return JSON.parse(result.stdout); } catch { return null; }
145
+ }
146
+
147
+ function writeIndex(repo, tasksSha, entries) {
148
+ const blob = out(["hash-object", "-w", "--stdin"], {
149
+ cwd: repo.top,
150
+ input: JSON.stringify({ v: INDEX_VERSION, tasks: tasksSha, entries }),
151
+ });
152
+ git(["update-ref", TASKS_INDEX_REF, blob], { cwd: repo.top, allowFail: true });
153
+ }
154
+
155
+ /**
156
+ * Lightweight rows for the whole board: [{ id, state, role, time, createdAt,
157
+ * superseded }]. Uses the index when it is pinned to the current task tree;
158
+ * otherwise rebuilds and stores the index once.
159
+ */
160
+ export function readIndex(repo) {
161
+ const tasksSha = refSha(repo);
162
+ if (!tasksSha) return { tasksSha: null, entries: [] };
163
+ const cached = readIndexBlob(repo);
164
+ if (cached && cached.v === INDEX_VERSION && cached.tasks === tasksSha && Array.isArray(cached.entries)) {
165
+ return { tasksSha, entries: cached.entries };
166
+ }
167
+ const tasks = listRaw(repo).map((entry) => entry.value);
168
+ const entries = buildIndexEntries(tasks);
169
+ writeIndex(repo, tasksSha, entries);
170
+ return { tasksSha, entries };
171
+ }
172
+
173
+ /** Newest stateChangedAt first; ids break ties so paging is deterministic. */
174
+ export function compareIndexRows(left, right) {
175
+ if (left[3] !== right[3]) return right[3] - left[3];
176
+ return String(left[0]).localeCompare(String(right[0]));
177
+ }
178
+
179
+ /**
180
+ * Pure page computation over index rows: filter, sort newest-first, cut one
181
+ * page. Exported so the 100k-scale behaviour can be tested without git.
182
+ */
183
+ export function paginateIndexEntries(entries, { state = null, role = null, limit = DEFAULT_PAGE_LIMIT, cursor = 0 } = {}) {
184
+ let rows = entries;
185
+ if (state) rows = rows.filter((entry) => entry[1] === state);
186
+ if (role) rows = rows.filter((entry) => entry[2] === role);
187
+ rows = rows.slice().sort(compareIndexRows);
188
+ const total = rows.length;
189
+ const start = Math.min(Math.max(0, cursor), total);
190
+ const page = rows.slice(start, start + limit);
191
+ const next = start + page.length;
192
+ return { page, total, cursor: next, hasMore: next < total };
193
+ }
194
+
195
+ /**
196
+ * One server-side page of tasks, newest stateChangedAt first. Only the page's
197
+ * cards are read from git; filtering, ordering and the total come from the
198
+ * lightweight index.
199
+ */
200
+ export function readTaskPage(repo, options = {}) {
201
+ const { entries } = readIndex(repo);
202
+ const page = paginateIndexEntries(entries, options);
203
+ const tasks = readTasksByIds(repo, page.page.map((entry) => entry[0]));
204
+ const byId = new Map(tasks.map((task) => [task.id, task]));
205
+ const items = page.page.map((entry) => byId.get(entry[0])).filter(Boolean);
206
+ return { items, total: page.total, cursor: page.cursor, hasMore: page.hasMore };
207
+ }
208
+
209
+ /**
210
+ * Pure counts over index rows: per-state and per-role counts, the superseded
211
+ * count and the oldest pending task. Superseded tasks keep their lane but are
212
+ * counted separately, never inside byState/byRole. Exported for the 100k mock.
213
+ */
214
+ export function summarizeEntries(entries) {
215
+ const byState = {};
216
+ const byRole = {};
217
+ let superseded = 0;
218
+ let oldest = null;
219
+ for (const [id, state, role, , createdAt, isSuperseded] of entries) {
220
+ if (isSuperseded) { superseded += 1; continue; }
221
+ byState[state] = (byState[state] || 0) + 1;
222
+ byRole[role] = (byRole[role] || 0) + 1;
223
+ if (state === "pending" && (oldest === null || String(createdAt) < String(oldest.createdAt))) {
224
+ oldest = { id, createdAt: String(createdAt) };
225
+ }
226
+ }
227
+ return { total: entries.length, byState, byRole, superseded, oldestPending: oldest };
228
+ }
229
+
230
+ /** Counts for the whole board from the lightweight index. */
231
+ export function summarizeIndex(repo) {
232
+ const { entries } = readIndex(repo);
233
+ return summarizeEntries(entries);
28
234
  }
29
235
 
30
236
  function hashBlob(repo, value) {
@@ -33,7 +239,8 @@ function hashBlob(repo, value) {
33
239
 
34
240
  /**
35
241
  * Replace the whole board with the given tasks, compare-and-swap on the ref.
36
- * Returns false when the ref moved underneath us (caller retries).
242
+ * The lightweight index is written after the task ref moves. Returns false when
243
+ * the ref moved underneath us (caller retries).
37
244
  */
38
245
  function write(repo, tasks, expectedSha) {
39
246
  const indexFile = path.join(repo.stateDir, "index-tasks-" + process.pid + "-" + crypto.randomBytes(4).toString("hex"));
@@ -44,7 +251,7 @@ function write(repo, tasks, expectedSha) {
44
251
  else git(["read-tree", "--empty"], { cwd: repo.top, env });
45
252
 
46
253
  const keep = new Set(tasks.map((task) => task.id));
47
- for (const entry of listRaw(repo)) {
254
+ for (const entry of readTree(repo, expectedSha)) {
48
255
  if (!keep.has(entry.id)) git(["update-index", "--force-remove", entry.id], { cwd: repo.top, env });
49
256
  }
50
257
  for (const task of tasks) {
@@ -56,7 +263,9 @@ function write(repo, tasks, expectedSha) {
56
263
  cwd: repo.top,
57
264
  allowFail: true,
58
265
  });
59
- return update.status === 0;
266
+ if (update.status !== 0) return false;
267
+ writeIndex(repo, tree, buildIndexEntries(tasks));
268
+ return true;
60
269
  } finally {
61
270
  fs.rmSync(indexFile, { force: true });
62
271
  }
@@ -73,8 +282,3 @@ export function mutate(repo, fn) {
73
282
  }
74
283
  return { ok: false, tasks: [] };
75
284
  }
76
-
77
- export function readTask(repo, id) {
78
- const found = listRaw(repo).find((entry) => entry.id === id);
79
- return found ? found.value : null;
80
- }
package/src/task.js CHANGED
@@ -64,6 +64,11 @@ export function isDraft(task) {
64
64
  return Boolean(task && task.draft === true);
65
65
  }
66
66
 
67
+ /** superseded is a flag, not a state: the task keeps its lane but is never dispatched. */
68
+ export function isSuperseded(task) {
69
+ return Boolean(task && task.superseded === true);
70
+ }
71
+
67
72
  /** A claimed card whose claim expired can be taken over by the next agent. */
68
73
  export function isReclaimable(task, now = Date.now()) {
69
74
  if (task.state !== "claimed") return false;
@@ -82,8 +87,8 @@ function depsDone(task, byId) {
82
87
  * (pending, or claimed and expired so it can be recovered).
83
88
  */
84
89
  export function isReady(task, byId, { modeFree = true, now = Date.now() } = {}) {
85
- // A draft never enters a dispatch computation, whatever its state.
86
- if (isDraft(task)) return false;
90
+ // Draft and superseded never enter a dispatch computation, whatever their state.
91
+ if (isDraft(task) || isSuperseded(task)) return false;
87
92
  const claimable = task.state === "pending" || isReclaimable(task, now);
88
93
  if (!claimable) return false;
89
94
  if (!depsDone(task, byId)) return false;