@codyn06/cboard 0.1.0 → 0.3.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/README.md CHANGED
@@ -10,6 +10,9 @@ Requires Node 20 or newer. No native modules and no install scripts.
10
10
  npx @codyn06/cboard connect --project <project-uuid> # once per repository; rerun to update the kit
11
11
  npx @codyn06/cboard sync # sync the committed code to the graph
12
12
  npx @codyn06/cboard check # is the token accepted, is the project visible?
13
+ npx @codyn06/cboard connect --goal "<one line>" # record the project goal as a requirement node
14
+ npx @codyn06/cboard issues sync # mirror GitHub issues into the graph
15
+ npx @codyn06/cboard docs sync # import README, docs/ and ADRs into the graph
13
16
  ```
14
17
 
15
18
  Or install it once and use the `cboard` command directly:
@@ -36,8 +39,8 @@ changed. `cboard connect` also keeps the generated files on LF with a marked `#
36
39
 
37
40
  ## The token
38
41
 
39
- Create a token in the cboard web app (the "Agent tokens" button in the project header; scopes
40
- `graph:read`, `graph:contribute`, `graph:context`) and save it to `.cboard/token` in the repository
42
+ Create a token in the cboard web app (the "Agent tokens" button in the project header; members pick
43
+ `graph:read`, `graph:contribute` and `graph:context`, viewers are read-only) and save it to `.cboard/token` in the repository
41
44
  (`connect` adds it to `.gitignore`), or export it as `CBOARD_PAT`. The repository's token file takes
42
45
  precedence over `CBOARD_PAT`. The token is only ever sent to the default cboard server or to a server you
43
46
  list in `CBOARD_TRUSTED_SERVERS`.
package/dist/api.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type WakeOptions } from "./wake.js";
2
+ import { type HeadStore } from "./cache.js";
1
3
  import type { Contribution, Receipt, Result, Snapshot } from "./model.js";
2
4
  export declare class GraphHttpError extends Error {
3
5
  readonly status: number;
@@ -8,12 +10,21 @@ export declare class GraphToolError extends Error {
8
10
  readonly code: string;
9
11
  constructor(tool: string, code: string);
10
12
  }
13
+ export interface ContextApiOptions extends WakeOptions {
14
+ /** Mirror of the heads read at the previous sync; reconcile then fetches only what changed. */
15
+ heads?: HeadStore;
16
+ }
11
17
  export declare class ContextApi {
12
18
  private readonly project;
13
19
  private readonly token;
14
20
  private readonly base;
15
21
  private readonly mcp;
16
- constructor(server: string, project: string, token: string);
22
+ private readonly wake;
23
+ private readonly heads;
24
+ private readonly server;
25
+ constructor(server: string, project: string, token: string, { heads, ...wake }?: ContextApiOptions);
26
+ /** Retries a request while the hosted service wakes; announces that once per client. */
27
+ private waking;
17
28
  private request;
18
29
  /**
19
30
  * Writes go through the MCP submit_contribution tool: the CDN firewall in front of the hosted
@@ -26,7 +37,23 @@ export declare class ContextApi {
26
37
  all(filters: Record<string, string>): Promise<Result>;
27
38
  submit(body: Contribution): Promise<Receipt>;
28
39
  nodeEdges(id: string): Promise<Result["edges"]>;
29
- allEdges(namespace: string): Promise<Result["edges"]>;
40
+ /** Edges of a namespace: active ones, or with `since` every head written after that revision. */
41
+ allEdges(namespace: string, since?: number): Promise<{
42
+ edges: Result["edges"];
43
+ revision: number;
44
+ }>;
45
+ private headKey;
46
+ /** Active nodes of a namespace, refreshed from the head cache by revision when there is one. */
47
+ nodeHeads(namespace: string): Promise<{
48
+ rows: Result["nodes"];
49
+ steady: boolean;
50
+ }>;
51
+ /**
52
+ * Active edges of a namespace, refreshed from the head cache by revision when there is one.
53
+ * `fresh` reads them in full: a full read hides edges of inactive nodes, so once a node is
54
+ * revived its unchanged edges reappear without a newer revision for a delta to find.
55
+ */
56
+ edgeHeads(namespace: string, fresh?: boolean): Promise<Result["edges"]>;
30
57
  }
31
58
  /**
32
59
  * Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
@@ -43,8 +70,13 @@ export declare function submitBatch<T>(api: ContextApi, group: T[], make: (items
43
70
  items: T[];
44
71
  receipt: Receipt;
45
72
  }[]>;
46
- /** Server state is authoritative; local state is never used to skip reconciliation. */
47
- export declare function reconcile(api: ContextApi, snapshot: Snapshot, namespace: string, supersede?: boolean): Promise<{
73
+ /**
74
+ * The head cache is a mirror refreshed from the server by revision, and the server stays
75
+ * authoritative: a doubtful cache is dropped for a full read, never trusted.
76
+ */
77
+ export declare function reconcile(api: ContextApi, snapshot: Snapshot, namespace: string, supersede?: boolean,
78
+ /** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
79
+ anchors?: Map<string, string>): Promise<{
48
80
  contributions: number;
49
81
  digest: string;
50
82
  }>;
package/dist/api.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
+ import { WAKE_BUDGET_MS, retryWake } from "./wake.js";
3
+ import { readHeads } from "./cache.js";
2
4
  export class GraphHttpError extends Error {
3
5
  status;
4
6
  constructor(status) {
@@ -6,6 +8,7 @@ export class GraphHttpError extends Error {
6
8
  this.status = status;
7
9
  }
8
10
  }
11
+ const LOCAL_HOSTS = ["127.0.0.1", "localhost", "[::1]"];
9
12
  export class GraphToolError extends Error {
10
13
  tool;
11
14
  code;
@@ -20,9 +23,14 @@ export class ContextApi {
20
23
  token;
21
24
  base;
22
25
  mcp;
23
- constructor(server, project, token) {
26
+ wake;
27
+ heads;
28
+ server;
29
+ constructor(server, project, token, { heads, ...wake } = {}) {
24
30
  this.project = project;
25
31
  this.token = token;
32
+ this.heads = heads;
33
+ this.server = server;
26
34
  const url = new URL(server);
27
35
  if (url.username ||
28
36
  url.password ||
@@ -37,38 +45,51 @@ export class ContextApi {
37
45
  const root = server.replace(/\/$/, "");
38
46
  this.base = `${root}/v1/graph/projects/${project}`;
39
47
  this.mcp = `${root}/mcp`;
48
+ // A sleeping hosted service needs a minute or so to wake; a local graph is up or it is not.
49
+ this.wake = { budgetMs: LOCAL_HOSTS.includes(url.hostname) ? 0 : WAKE_BUDGET_MS, ...wake };
50
+ }
51
+ /** Retries a request while the hosted service wakes; announces that once per client. */
52
+ waking(attempt) {
53
+ return retryWake(attempt, this.wake);
40
54
  }
41
55
  async request(path) {
42
- const response = await fetch(this.base + path, {
43
- redirect: "error",
44
- headers: { authorization: `Bearer ${this.token}` },
56
+ return this.waking(async (timeoutMs) => {
57
+ const response = await fetch(this.base + path, {
58
+ redirect: "error",
59
+ signal: AbortSignal.timeout(timeoutMs),
60
+ headers: { authorization: `Bearer ${this.token}` },
61
+ });
62
+ if (!response.ok)
63
+ throw new GraphHttpError(response.status);
64
+ return (await response.json());
45
65
  });
46
- if (!response.ok)
47
- throw new Error(`Graph HTTP ${String(response.status)}`);
48
- return (await response.json());
49
66
  }
50
67
  /**
51
68
  * Writes go through the MCP submit_contribution tool: the CDN firewall in front of the hosted
52
69
  * service blocks code-sync payloads on the REST contribution route (Cloudflare 403 "Blocked").
53
70
  */
54
71
  async callTool(name, args) {
55
- const response = await fetch(this.mcp, {
56
- method: "POST",
57
- redirect: "error",
58
- headers: {
59
- authorization: `Bearer ${this.token}`,
60
- "content-type": "application/json",
61
- accept: "application/json, text/event-stream",
62
- },
63
- body: JSON.stringify({
64
- jsonrpc: "2.0",
65
- id: 1,
66
- method: "tools/call",
67
- params: { name, arguments: args },
68
- }),
72
+ const response = await this.waking(async (timeoutMs) => {
73
+ const res = await fetch(this.mcp, {
74
+ method: "POST",
75
+ redirect: "error",
76
+ signal: AbortSignal.timeout(timeoutMs),
77
+ headers: {
78
+ authorization: `Bearer ${this.token}`,
79
+ "content-type": "application/json",
80
+ accept: "application/json, text/event-stream",
81
+ },
82
+ body: JSON.stringify({
83
+ jsonrpc: "2.0",
84
+ id: 1,
85
+ method: "tools/call",
86
+ params: { name, arguments: args },
87
+ }),
88
+ });
89
+ if (!res.ok)
90
+ throw new GraphHttpError(res.status);
91
+ return res;
69
92
  });
70
- if (!response.ok)
71
- throw new GraphHttpError(response.status);
72
93
  const reply = (await response.json());
73
94
  const text = reply.result?.content?.[0]?.text;
74
95
  if (reply.error || typeof text !== "string")
@@ -102,13 +123,14 @@ export class ContextApi {
102
123
  const nodes = [];
103
124
  const edges = new Map();
104
125
  let cursor;
105
- let revision;
126
+ // Pages are separate snapshots: the oldest one is the revision the whole read is good for.
127
+ let revision = Number.POSITIVE_INFINITY;
106
128
  const seen = new Set();
107
129
  do {
108
130
  const page = await this.query({ ...filters, limit: "300", ...(cursor ? { cursor } : {}) });
109
131
  nodes.push(...page.nodes);
110
132
  page.edges.forEach((e) => edges.set(e.id, e));
111
- revision = page.revision;
133
+ revision = Math.min(revision, page.revision);
112
134
  cursor = page.nextCursor;
113
135
  if (page.truncated && !cursor)
114
136
  throw new Error("Graph response truncated without continuation");
@@ -141,13 +163,21 @@ export class ContextApi {
141
163
  } while (cursor);
142
164
  return edges;
143
165
  }
144
- async allEdges(namespace) {
166
+ /** Edges of a namespace: active ones, or with `since` every head written after that revision. */
167
+ async allEdges(namespace, since) {
145
168
  const edges = [];
146
169
  let cursor;
170
+ let revision = Number.POSITIVE_INFINITY;
147
171
  const seen = new Set();
148
172
  do {
149
- const page = await this.request(`/edges?${new URLSearchParams({ namespace, limit: "300", include_inactive: "true", ...(cursor ? { cursor } : {}) })}`);
173
+ const page = await this.request(`/edges?${new URLSearchParams({
174
+ namespace,
175
+ limit: "300",
176
+ ...(since === undefined ? {} : { include_inactive: "true", since: String(since) }),
177
+ ...(cursor ? { cursor } : {}),
178
+ })}`);
150
179
  edges.push(...page.edges);
180
+ revision = Math.min(revision, page.revision);
151
181
  cursor = page.nextCursor;
152
182
  if (page.truncated && !cursor)
153
183
  throw new Error("Edge list truncated without continuation");
@@ -156,7 +186,31 @@ export class ContextApi {
156
186
  if (cursor)
157
187
  seen.add(cursor);
158
188
  } while (cursor);
159
- return edges;
189
+ return { edges, revision };
190
+ }
191
+ headKey(kind, namespace) {
192
+ return `${kind}|${this.server}|${this.project}|${namespace}`;
193
+ }
194
+ /** Active nodes of a namespace, refreshed from the head cache by revision when there is one. */
195
+ nodeHeads(namespace) {
196
+ return readHeads(this.heads, this.headKey("nodes", namespace), async (since) => {
197
+ const read = await this.all(since === undefined
198
+ ? { namespace }
199
+ : { namespace, include_inactive: "true", since: String(since) });
200
+ return { rows: read.nodes, revision: read.revision };
201
+ });
202
+ }
203
+ /**
204
+ * Active edges of a namespace, refreshed from the head cache by revision when there is one.
205
+ * `fresh` reads them in full: a full read hides edges of inactive nodes, so once a node is
206
+ * revived its unchanged edges reappear without a newer revision for a delta to find.
207
+ */
208
+ async edgeHeads(namespace, fresh = false) {
209
+ const read = await readHeads(this.heads, this.headKey("edges", namespace), async (since) => {
210
+ const read = await this.allEdges(namespace, since);
211
+ return { rows: read.edges, revision: read.revision };
212
+ }, fresh);
213
+ return read.rows;
160
214
  }
161
215
  }
162
216
  /**
@@ -238,13 +292,15 @@ function stable(value) {
238
292
  : v;
239
293
  return JSON.stringify(sort(value));
240
294
  }
295
+ /** A commit-only change is not a content change (#145); the repository node keeps it for the lag brief. */
296
+ const withoutCommit = (locators) => locators.map((p) => ({ ...p, commit: undefined }));
241
297
  const comparable = (n) => stable([
242
298
  n.title,
243
299
  n.body,
244
300
  n.status ?? null,
245
301
  n.properties,
246
302
  n.derivation,
247
- n.provenance.map((p) => [p.repo, p.commit, p.path, p.startLine, p.endLine]),
303
+ n.type === "repository" ? n.provenance : withoutCommit(n.provenance),
248
304
  ]);
249
305
  const edgeKey = (e) => stable([
250
306
  e.type,
@@ -253,27 +309,45 @@ const edgeKey = (e) => stable([
253
309
  e.properties.contextNamespace ?? null,
254
310
  e.type === "amends" ? (e.properties.scope ?? null) : null,
255
311
  ]);
256
- /** Server state is authoritative; local state is never used to skip reconciliation. */
257
- export async function reconcile(api, snapshot, namespace, supersede = true) {
258
- const existing = await api.all({ namespace, include_inactive: "true" });
259
- const byKey = new Map(existing.nodes.map((n) => [n.clientKey, n]));
260
- // Entities imported before namespace adoption carry the same client key outside the namespace.
261
- // One project-wide scan of the snapshot's node types (pages of 300) replaces one exact
262
- // client_key request per absent node, so a first sync of N nodes costs pages, not N requests.
312
+ /** Up to this many absent keys are looked up one by one; more use the project-wide types scan. */
313
+ const KEY_LOOKUP_MAX = 50;
314
+ /**
315
+ * The head cache is a mirror refreshed from the server by revision, and the server stays
316
+ * authoritative: a doubtful cache is dropped for a full read, never trusted.
317
+ */
318
+ export async function reconcile(api, snapshot, namespace, supersede = true,
319
+ /** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
320
+ anchors = new Map()) {
321
+ // Active heads only: history is not re-downloaded on every sync (#145).
322
+ const { rows: existing, steady } = await api.nodeHeads(namespace);
323
+ const byKey = new Map(existing.map((n) => [n.clientKey, n]));
324
+ // Absent keys are new, superseded/withdrawn in this namespace (revived below), or legacy nodes
325
+ // outside the namespace with the same client key. A few are looked up by key; many use one
326
+ // project-wide scan of the snapshot's node types, so a first sync costs pages, not N requests.
263
327
  const absent = new Set(snapshot.nodes.filter((n) => !byKey.has(n.clientKey)).map((n) => n.clientKey));
264
328
  if (absent.size) {
265
- const types = [...new Set(snapshot.nodes.map((n) => n.type))].join(",");
266
- const found = new Map();
267
- for (const n of (await api.all({ types, include_inactive: "true" })).nodes)
268
- if (absent.has(n.clientKey)) {
269
- if (found.has(n.clientKey))
270
- throw new Error(`Ambiguous client key ${n.clientKey}`);
271
- found.set(n.clientKey, n);
272
- }
273
- for (const [key, n] of found)
274
- byKey.set(key, n);
329
+ const candidates = new Map();
330
+ const offer = (n) => {
331
+ if (absent.has(n.clientKey))
332
+ candidates.set(n.clientKey, [...(candidates.get(n.clientKey) ?? []), n]);
333
+ };
334
+ if (absent.size <= KEY_LOOKUP_MAX)
335
+ for (const client_key of absent)
336
+ (await api.all({ client_key, include_inactive: "true" })).nodes.forEach(offer);
337
+ else {
338
+ const types = [...new Set(snapshot.nodes.map((n) => n.type))].join(",");
339
+ (await api.all({ types, include_inactive: "true" })).nodes.forEach(offer);
340
+ }
341
+ for (const [key, list] of candidates) {
342
+ const inside = list.filter((n) => n.namespace === namespace);
343
+ const pool = inside.length ? inside : list;
344
+ const [only] = pool;
345
+ if (pool.length > 1 || !only)
346
+ throw new Error(`Ambiguous client key ${key}`);
347
+ byKey.set(key, only);
348
+ }
275
349
  }
276
- const ids = new Map([...byKey].map(([key, n]) => [key, n.id]));
350
+ const ids = new Map([...anchors, ...[...byKey].map(([key, n]) => [key, n.id])]);
277
351
  const desired = new Set(snapshot.nodes.map((n) => n.clientKey));
278
352
  const revisions = [];
279
353
  const fresh = snapshot.nodes.filter((n) => !byKey.has(n.clientKey));
@@ -293,7 +367,7 @@ export async function reconcile(api, snapshot, namespace, supersede = true) {
293
367
  });
294
368
  }
295
369
  if (supersede)
296
- for (const old of existing.nodes)
370
+ for (const old of existing)
297
371
  if (!desired.has(old.clientKey) && old.lifecycle === "active")
298
372
  revisions.push({
299
373
  nodeId: old.id,
@@ -329,7 +403,10 @@ export async function reconcile(api, snapshot, namespace, supersede = true) {
329
403
  for (const batch of chunks(revisions, (revisions) => ({ ...empty(), revisions })))
330
404
  contributions += (await submitBatch(api, batch, (revisions) => ({ ...empty(), revisions })))
331
405
  .length;
332
- const currentEdges = new Map((await api.allEdges(namespace)).map((e) => [e.id, e]));
406
+ // A revived node (here or elsewhere) can bring back edges no delta reports: read them in full.
407
+ const revived = !steady ||
408
+ snapshot.nodes.some((n) => (byKey.get(n.clientKey)?.lifecycle ?? "active") !== "active");
409
+ const currentEdges = new Map((await api.edgeHeads(namespace, revived)).map((e) => [e.id, e]));
333
410
  const desiredEdges = snapshot.edges.map((e) => {
334
411
  const from = ids.get(e.from), to = ids.get(e.to);
335
412
  if (!from || !to)
@@ -386,8 +463,8 @@ export async function reconcile(api, snapshot, namespace, supersede = true) {
386
463
  for (const edge of edges) {
387
464
  const old = activeByKey.get(edgeKey(edge));
388
465
  if (old &&
389
- stable([old.provenance, old.derivation, old.properties]) !==
390
- stable([edge.provenance, edge.derivation, edge.properties]))
466
+ stable([withoutCommit(old.provenance), old.derivation, old.properties]) !==
467
+ stable([withoutCommit(edge.provenance), edge.derivation, edge.properties]))
391
468
  updated.push({
392
469
  edgeId: old.id,
393
470
  expectedRevision: old.revision,
@@ -0,0 +1,28 @@
1
+ /** Key-value store for the heads read at the previous sync (#145). */
2
+ export interface HeadStore {
3
+ get(key: string): string | undefined;
4
+ set(key: string, value: string): void;
5
+ }
6
+ /** One file per key under the user cache directory; a missing or unreadable file is a cache miss. */
7
+ export declare function fileHeadStore(dir?: string): HeadStore;
8
+ interface Head {
9
+ id: string;
10
+ revision: number;
11
+ lifecycle: string;
12
+ }
13
+ /**
14
+ * Active heads for `key`. The stored copy is a mirror refreshed from the server by revision: only
15
+ * rows written after the stored revision are fetched and merged (higher row revision wins).
16
+ * Anything doubtful - no or invalid entry, a server that rejects `since`, a server revision
17
+ * behind the stored one, or `fresh` - reads everything again.
18
+ * `steady` is true only for a delta read that brought back no row: every active row it added is
19
+ * new at revision 1. Callers use it to tell when visibility that depends on these rows changed.
20
+ */
21
+ export declare function readHeads<T extends Head>(store: HeadStore | undefined, key: string, fetch: (since?: number) => Promise<{
22
+ rows: T[];
23
+ revision: number;
24
+ }>, fresh?: boolean): Promise<{
25
+ rows: T[];
26
+ steady: boolean;
27
+ }>;
28
+ export {};
package/dist/cache.js ADDED
@@ -0,0 +1,101 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ /** One file per key under the user cache directory; a missing or unreadable file is a cache miss. */
6
+ export function fileHeadStore(dir = join(process.env.XDG_CACHE_HOME || process.env.LOCALAPPDATA || join(homedir(), ".cache"), "cboard", "sync")) {
7
+ const file = (key) => join(dir, `${createHash("sha256").update(key).digest("hex")}.json`);
8
+ return {
9
+ get(key) {
10
+ try {
11
+ return readFileSync(file(key), "utf8");
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ },
17
+ set(key, value) {
18
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
19
+ const target = file(key);
20
+ const tmp = `${target}.${randomUUID()}.tmp`;
21
+ try {
22
+ writeFileSync(tmp, value, { mode: 0o600 });
23
+ renameSync(tmp, target);
24
+ }
25
+ catch (error) {
26
+ rmSync(tmp, { force: true });
27
+ throw error;
28
+ }
29
+ },
30
+ };
31
+ }
32
+ function parse(raw) {
33
+ if (raw === undefined)
34
+ return undefined;
35
+ try {
36
+ const value = JSON.parse(raw);
37
+ if (value?.v === 1 &&
38
+ typeof value.revision === "number" &&
39
+ Number.isInteger(value.revision) &&
40
+ value.revision >= 0 &&
41
+ Array.isArray(value.rows) &&
42
+ value.rows.every((r) => !!r &&
43
+ typeof r === "object" &&
44
+ typeof r.id === "string" &&
45
+ Number.isInteger(r.revision) &&
46
+ typeof r.lifecycle === "string"))
47
+ return value;
48
+ }
49
+ catch {
50
+ /* unparseable: read in full */
51
+ }
52
+ return undefined;
53
+ }
54
+ /** A 400 is how a server without `since` support answers (duck-typed: api.ts imports this module). */
55
+ const rejectsSince = (error) => error instanceof Error && error.status === 400;
56
+ /**
57
+ * Active heads for `key`. The stored copy is a mirror refreshed from the server by revision: only
58
+ * rows written after the stored revision are fetched and merged (higher row revision wins).
59
+ * Anything doubtful - no or invalid entry, a server that rejects `since`, a server revision
60
+ * behind the stored one, or `fresh` - reads everything again.
61
+ * `steady` is true only for a delta read that brought back no row: every active row it added is
62
+ * new at revision 1. Callers use it to tell when visibility that depends on these rows changed.
63
+ */
64
+ export async function readHeads(store, key, fetch, fresh = false) {
65
+ const cached = fresh ? undefined : parse(store?.get(key));
66
+ let result;
67
+ let merged = new Map();
68
+ if (cached) {
69
+ try {
70
+ const delta = await fetch(cached.revision);
71
+ if (delta.revision >= cached.revision) {
72
+ result = delta;
73
+ merged = new Map(cached.rows.map((r) => [r.id, r]));
74
+ }
75
+ }
76
+ catch (error) {
77
+ if (!rejectsSince(error))
78
+ throw error;
79
+ }
80
+ }
81
+ let steady = !!result;
82
+ result ??= await fetch();
83
+ for (const row of result.rows) {
84
+ const old = merged.get(row.id);
85
+ if (old && row.revision < old.revision)
86
+ continue;
87
+ // Active, unknown and past revision 1: revived (or never cached), so dependent reads may lag.
88
+ if (row.lifecycle === "active" && !old && row.revision > 1)
89
+ steady = false;
90
+ merged.set(row.id, row);
91
+ }
92
+ const rows = [...merged.values()].filter((r) => r.lifecycle === "active");
93
+ const entry = { v: 1, revision: result.revision, rows };
94
+ try {
95
+ store?.set(key, JSON.stringify(entry));
96
+ }
97
+ catch {
98
+ /* an unwritable cache only costs a full read next time */
99
+ }
100
+ return { rows, steady };
101
+ }
package/dist/cboard.js CHANGED
@@ -2,6 +2,8 @@ import { spawnSync } from "node:child_process";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { sync } from "./cli.js";
5
+ import { docsSync } from "./docs.js";
6
+ import { issuesSync } from "./issues.js";
5
7
  const HELP = `cboard — client for cboard project graphs
6
8
 
7
9
  Usage: cboard <command> [flags]
@@ -9,6 +11,8 @@ Usage: cboard <command> [flags]
9
11
  Commands:
10
12
  connect Connect this repository to a cboard project (writes .cboard.json, .cboard/, .mcp.json, hooks)
11
13
  sync Sync this repository's code layer to the cboard graph
14
+ issues Mirror this repository's GitHub issues into the graph ("cboard issues sync")
15
+ docs sync Import this repository's Markdown docs into the cboard graph
12
16
  check Check that this repository can reach its cboard graph
13
17
 
14
18
  Run "cboard <command> --help" for a command's flags.
@@ -16,20 +20,44 @@ Options:
16
20
  --help, -h Show this help
17
21
  --version, -v Show the version
18
22
  `;
19
- const CONNECT_HELP = `Usage: cboard connect --project <uuid> [--server <https url>] [--repo <path>]
20
- [--no-hooks] [--no-agents] [--no-skill] [--strict] [--codex]
23
+ const CONNECT_HELP = `Usage: cboard connect [--project <uuid>] [--server <https url>] [--repo <path>]
24
+ [--no-hooks] [--no-agents] [--no-skill] [--no-login] [--strict] [--codex]
25
+ [--goal "<one line>"] [--reference <projectId> --name <name>]...
26
+ [--remove-reference <name>]...
27
+
28
+ Without a usable token (none saved, or the server rejects it) connect logs in through your browser: it
29
+ prints a URL and a code, you approve and pick the project there, and the token is saved to the repository's
30
+ token file (kept out of Git; never printed). --no-login skips that and needs --project and an existing token.
21
31
 
22
32
  Writes .cboard.json, the committed kit in .cboard/ (hooks and the MCP header helper run it, never npx),
23
33
  .mcp.json, the SessionStart hooks, an AGENTS.md block, the cboard-graph skill and a .gitattributes
24
34
  block. Rerun to update the kit. --codex also prints the Codex MCP config snippet.
35
+ --goal creates (or, with a different text, revises) the project's one goal requirement node and remembers
36
+ its id in .cboard.json; it needs a token (graph:read, graph:contribute). Rerunning without --goal leaves it alone.
37
+ --reference <projectId> --name <name> (repeatable, in pairs) lets this repository read another project without
38
+ writing to it: it records the reference in .cboard.json, adds an MCP server "cboard-ref-<name>" and expects a
39
+ graph:read token for that project in .cboard/ref-<name>.token (kept out of Git). The project owner must have
40
+ added you as a member. --remove-reference <name> removes it (the token file is left in place).
25
41
  `;
26
42
  const SYNC_HELP = `Usage: cboard sync [--repo PATH] [--project UUID] [--server URL] [--token-env NAME] [--state PATH]
27
43
 
28
44
  Project, server and token come from .cboard.json and the repo token file when the flags are omitted.
29
45
  `;
46
+ const ISSUES_HELP = `Usage: cboard issues sync [--state all|open] [--limit N] [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
47
+
48
+ Mirrors the origin repository's GitHub issues (not pull requests) as open_issue nodes linked to the
49
+ repository node; run "cboard sync" first. Reads through "gh api", or GITHUB_TOKEN when gh is
50
+ unavailable. --state open or --limit mirrors a partial list and keeps issues it did not see.
51
+ `;
52
+ const DOCS_HELP = `Usage: cboard docs sync [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
53
+
54
+ Imports README.md, docs/**/*.md and ADR folders (docs/adr, adr, docs/decisions) as source,
55
+ excerpt, decision and plan nodes. Configure paths with .cboard.json "docs": {"include": [...], "exclude": [...]}.
56
+ `;
30
57
  const CHECK_HELP = `Usage: cboard check
31
58
 
32
- Reports whether the token in this repository is accepted and its configured project is visible.
59
+ Reports whether the token in this repository is accepted and its configured project is visible, and tests each
60
+ reference project (token present, project visible, token read-only).
33
61
  Exits 1 when it is not connected.
34
62
  `;
35
63
  const packageFile = new URL("../package.json", import.meta.url);
@@ -88,6 +116,32 @@ export async function main(argv) {
88
116
  console.error(error instanceof Error ? error.message : "Context sync failed");
89
117
  return 1;
90
118
  }
119
+ case "issues":
120
+ if (wantsHelp || rest[0] !== "sync") {
121
+ console.log(ISSUES_HELP);
122
+ return wantsHelp ? 0 : 2;
123
+ }
124
+ try {
125
+ await issuesSync(rest.slice(1));
126
+ return 0;
127
+ }
128
+ catch (error) {
129
+ console.error(error instanceof Error ? error.message : "Issues sync failed");
130
+ return 1;
131
+ }
132
+ case "docs":
133
+ if (wantsHelp || rest[0] !== "sync") {
134
+ console.log(DOCS_HELP);
135
+ return wantsHelp ? 0 : 2;
136
+ }
137
+ try {
138
+ await docsSync(rest.slice(1));
139
+ return 0;
140
+ }
141
+ catch (error) {
142
+ console.error(error instanceof Error ? error.message : "Docs sync failed");
143
+ return 1;
144
+ }
91
145
  default:
92
146
  if (command)
93
147
  console.error(`cboard: unknown command "${command}"\n`);
package/dist/cli.js CHANGED
@@ -5,6 +5,7 @@ import { mkdir, writeFile, rename } from "node:fs/promises";
5
5
  import { dirname, isAbsolute, posix, relative, resolve, sep, win32 } from "node:path";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { ContextApi, reconcile } from "./api.js";
8
+ import { fileHeadStore } from "./cache.js";
8
9
  import { codeConfig, extract } from "./extract.js";
9
10
  export function options(argv) {
10
11
  const result = {};
@@ -136,7 +137,7 @@ export async function sync(argv) {
136
137
  const args = options(argv);
137
138
  const root = resolve(args.repo ?? process.cwd());
138
139
  const { project, token, server } = resolveSync(args, root);
139
- const api = new ContextApi(server, project, token);
140
+ const api = new ContextApi(server, project, token, { heads: fileHeadStore() });
140
141
  const snapshot = await extract(root, [], codeConfig(root));
141
142
  const result = await reconcile(api, snapshot, snapshot.namespace);
142
143
  const state = args.state