@codyn06/cboard 0.0.1 → 0.2.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/LICENSE +21 -0
- package/README.md +71 -3
- package/THIRD_PARTY_NOTICES +29 -0
- package/bin/cboard-context.js +15 -0
- package/bin/cboard.js +5 -0
- package/dist/adapters/bash.d.ts +2 -0
- package/dist/adapters/bash.js +14 -0
- package/dist/adapters/c-family.d.ts +2 -0
- package/dist/adapters/c-family.js +81 -0
- package/dist/adapters/csharp.d.ts +2 -0
- package/dist/adapters/csharp.js +47 -0
- package/dist/adapters/extra-languages.d.ts +3 -0
- package/dist/adapters/extra-languages.js +15 -0
- package/dist/adapters/go.d.ts +2 -0
- package/dist/adapters/go.js +42 -0
- package/dist/adapters/grammar.d.ts +21 -0
- package/dist/adapters/grammar.js +54 -0
- package/dist/adapters/index.d.ts +20 -0
- package/dist/adapters/index.js +62 -0
- package/dist/adapters/java.d.ts +2 -0
- package/dist/adapters/java.js +36 -0
- package/dist/adapters/kotlin.d.ts +2 -0
- package/dist/adapters/kotlin.js +65 -0
- package/dist/adapters/lua-family.d.ts +2 -0
- package/dist/adapters/lua-family.js +186 -0
- package/dist/adapters/php.d.ts +2 -0
- package/dist/adapters/php.js +28 -0
- package/dist/adapters/python.d.ts +2 -0
- package/dist/adapters/python.js +68 -0
- package/dist/adapters/ruby.d.ts +2 -0
- package/dist/adapters/ruby.js +46 -0
- package/dist/adapters/rust.d.ts +2 -0
- package/dist/adapters/rust.js +85 -0
- package/dist/adapters/swift.d.ts +2 -0
- package/dist/adapters/swift.js +38 -0
- package/dist/adapters/types.d.ts +61 -0
- package/dist/adapters/types.js +1 -0
- package/dist/adapters/typescript.d.ts +2 -0
- package/dist/adapters/typescript.js +52 -0
- package/dist/api.d.ts +56 -0
- package/dist/api.js +439 -0
- package/dist/cboard.d.ts +2 -0
- package/dist/cboard.js +151 -0
- package/dist/cli.d.ts +27 -0
- package/dist/cli.js +180 -0
- package/dist/docs-parse.d.ts +64 -0
- package/dist/docs-parse.js +762 -0
- package/dist/docs.d.ts +39 -0
- package/dist/docs.js +243 -0
- package/dist/extract.d.ts +36 -0
- package/dist/extract.js +480 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/issues.d.ts +44 -0
- package/dist/issues.js +138 -0
- package/dist/languages.d.ts +9 -0
- package/dist/languages.js +128 -0
- package/dist/model.d.ts +85 -0
- package/dist/model.js +1 -0
- package/dist/wake.d.ts +13 -0
- package/dist/wake.js +33 -0
- package/grammars/LICENSES/README.md +3 -0
- package/grammars/LICENSES/c.LICENSE +21 -0
- package/grammars/LICENSES/kotlin.LICENSE +21 -0
- package/grammars/LICENSES/lua.LICENSE +21 -0
- package/grammars/LICENSES/luau.LICENSE +21 -0
- package/grammars/LICENSES/swift.LICENSE +21 -0
- package/grammars/manifest.json +39 -0
- package/grammars/tree-sitter-c.wasm +0 -0
- package/grammars/tree-sitter-kotlin.wasm +0 -0
- package/grammars/tree-sitter-lua.wasm +0 -0
- package/grammars/tree-sitter-luau.wasm +0 -0
- package/grammars/tree-sitter-swift.wasm +0 -0
- package/kit/cboard-connect.js +869 -0
- package/kit/cboard-kit/brief.js +512 -0
- package/kit/cboard-kit/config.js +250 -0
- package/kit/cboard-kit/connect-check.js +95 -0
- package/kit/cboard-kit/device.js +192 -0
- package/kit/cboard-kit/drift.js +55 -0
- package/kit/cboard-kit/headers.js +46 -0
- package/kit/cboard-kit/mcp.js +97 -0
- package/kit/cboard-kit/references.js +70 -0
- package/kit/cboard-kit/skill/SKILL.md +170 -0
- package/kit/cboard-kit/wait.js +45 -0
- package/package.json +47 -5
- package/queries/bash/imports.scm +11 -0
- package/queries/bash/symbols.scm +1 -0
- package/queries/c/imports.scm +2 -0
- package/queries/c/symbols.scm +10 -0
- package/queries/cpp/imports.scm +2 -0
- package/queries/cpp/symbols.scm +11 -0
- package/queries/csharp/imports.scm +2 -0
- package/queries/csharp/symbols.scm +10 -0
- package/queries/go/imports.scm +2 -0
- package/queries/go/symbols.scm +8 -0
- package/queries/java/imports.scm +2 -0
- package/queries/java/symbols.scm +9 -0
- package/queries/javascript/imports.scm +3 -0
- package/queries/javascript/symbols.scm +16 -0
- package/queries/kotlin/imports.scm +2 -0
- package/queries/kotlin/symbols.scm +4 -0
- package/queries/lua/imports.scm +5 -0
- package/queries/lua/symbols.scm +6 -0
- package/queries/luau/imports.scm +5 -0
- package/queries/luau/symbols.scm +9 -0
- package/queries/php/imports.scm +6 -0
- package/queries/php/symbols.scm +7 -0
- package/queries/python/imports.scm +3 -0
- package/queries/python/symbols.scm +8 -0
- package/queries/ruby/imports.scm +2 -0
- package/queries/ruby/symbols.scm +4 -0
- package/queries/rust/imports.scm +5 -0
- package/queries/rust/symbols.scm +11 -0
- package/queries/swift/imports.scm +2 -0
- package/queries/swift/symbols.scm +5 -0
- package/queries/typescript/imports.scm +3 -0
- package/queries/typescript/symbols.scm +20 -0
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type WakeOptions } from "./wake.js";
|
|
2
|
+
import type { Contribution, Receipt, Result, Snapshot } from "./model.js";
|
|
3
|
+
export declare class GraphHttpError extends Error {
|
|
4
|
+
readonly status: number;
|
|
5
|
+
constructor(status: number);
|
|
6
|
+
}
|
|
7
|
+
export declare class GraphToolError extends Error {
|
|
8
|
+
readonly tool: string;
|
|
9
|
+
readonly code: string;
|
|
10
|
+
constructor(tool: string, code: string);
|
|
11
|
+
}
|
|
12
|
+
export declare class ContextApi {
|
|
13
|
+
private readonly project;
|
|
14
|
+
private readonly token;
|
|
15
|
+
private readonly base;
|
|
16
|
+
private readonly mcp;
|
|
17
|
+
private readonly wake;
|
|
18
|
+
constructor(server: string, project: string, token: string, wake?: WakeOptions);
|
|
19
|
+
/** Retries a request while the hosted service wakes; announces that once per client. */
|
|
20
|
+
private waking;
|
|
21
|
+
private request;
|
|
22
|
+
/**
|
|
23
|
+
* Writes go through the MCP submit_contribution tool: the CDN firewall in front of the hosted
|
|
24
|
+
* service blocks code-sync payloads on the REST contribution route (Cloudflare 403 "Blocked").
|
|
25
|
+
*/
|
|
26
|
+
private callTool;
|
|
27
|
+
/** True when the server has recorded this contribution (it was applied or deliberately returned). */
|
|
28
|
+
contributionRecorded(id: string): Promise<boolean>;
|
|
29
|
+
query(filters: Record<string, string>): Promise<Result>;
|
|
30
|
+
all(filters: Record<string, string>): Promise<Result>;
|
|
31
|
+
submit(body: Contribution): Promise<Receipt>;
|
|
32
|
+
nodeEdges(id: string): Promise<Result["edges"]>;
|
|
33
|
+
allEdges(namespace: string): Promise<Result["edges"]>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
|
|
37
|
+
* grows roughly quadratically with batch size; 50 stays under the 5 s statement timeout (#43).
|
|
38
|
+
*/
|
|
39
|
+
export declare const BATCH_ITEMS = 50;
|
|
40
|
+
export declare function chunks<T>(items: T[], make: (items: T[]) => Contribution): T[][];
|
|
41
|
+
/**
|
|
42
|
+
* Submits one batch. On a server error or statement timeout the batch is retried once as two
|
|
43
|
+
* halves, but only after the server confirms it never recorded the original contribution. A
|
|
44
|
+
* failure of either half propagates and stops the run. Returns one receipt per submitted piece.
|
|
45
|
+
*/
|
|
46
|
+
export declare function submitBatch<T>(api: ContextApi, group: T[], make: (items: T[]) => Contribution): Promise<{
|
|
47
|
+
items: T[];
|
|
48
|
+
receipt: Receipt;
|
|
49
|
+
}[]>;
|
|
50
|
+
/** Server state is authoritative; local state is never used to skip reconciliation. */
|
|
51
|
+
export declare function reconcile(api: ContextApi, snapshot: Snapshot, namespace: string, supersede?: boolean,
|
|
52
|
+
/** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
|
|
53
|
+
anchors?: Map<string, string>): Promise<{
|
|
54
|
+
contributions: number;
|
|
55
|
+
digest: string;
|
|
56
|
+
}>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { WAKE_BUDGET_MS, retryWake } from "./wake.js";
|
|
3
|
+
export class GraphHttpError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(status) {
|
|
6
|
+
super(`Graph HTTP ${String(status)}`);
|
|
7
|
+
this.status = status;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const LOCAL_HOSTS = ["127.0.0.1", "localhost", "[::1]"];
|
|
11
|
+
export class GraphToolError extends Error {
|
|
12
|
+
tool;
|
|
13
|
+
code;
|
|
14
|
+
constructor(tool, code) {
|
|
15
|
+
super(`Graph MCP ${tool}: ${code}`);
|
|
16
|
+
this.tool = tool;
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class ContextApi {
|
|
21
|
+
project;
|
|
22
|
+
token;
|
|
23
|
+
base;
|
|
24
|
+
mcp;
|
|
25
|
+
wake;
|
|
26
|
+
constructor(server, project, token, wake = {}) {
|
|
27
|
+
this.project = project;
|
|
28
|
+
this.token = token;
|
|
29
|
+
const url = new URL(server);
|
|
30
|
+
if (url.username ||
|
|
31
|
+
url.password ||
|
|
32
|
+
url.search ||
|
|
33
|
+
url.hash ||
|
|
34
|
+
!["http:", "https:"].includes(url.protocol))
|
|
35
|
+
throw new Error("Invalid server URL");
|
|
36
|
+
if (url.protocol === "http:" && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))
|
|
37
|
+
throw new Error("Remote servers require HTTPS");
|
|
38
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(project))
|
|
39
|
+
throw new Error("Project must be a UUID");
|
|
40
|
+
const root = server.replace(/\/$/, "");
|
|
41
|
+
this.base = `${root}/v1/graph/projects/${project}`;
|
|
42
|
+
this.mcp = `${root}/mcp`;
|
|
43
|
+
// A sleeping hosted service needs a minute or so to wake; a local graph is up or it is not.
|
|
44
|
+
this.wake = { budgetMs: LOCAL_HOSTS.includes(url.hostname) ? 0 : WAKE_BUDGET_MS, ...wake };
|
|
45
|
+
}
|
|
46
|
+
/** Retries a request while the hosted service wakes; announces that once per client. */
|
|
47
|
+
waking(attempt) {
|
|
48
|
+
return retryWake(attempt, this.wake);
|
|
49
|
+
}
|
|
50
|
+
async request(path) {
|
|
51
|
+
return this.waking(async (timeoutMs) => {
|
|
52
|
+
const response = await fetch(this.base + path, {
|
|
53
|
+
redirect: "error",
|
|
54
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
55
|
+
headers: { authorization: `Bearer ${this.token}` },
|
|
56
|
+
});
|
|
57
|
+
if (!response.ok)
|
|
58
|
+
throw new GraphHttpError(response.status);
|
|
59
|
+
return (await response.json());
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Writes go through the MCP submit_contribution tool: the CDN firewall in front of the hosted
|
|
64
|
+
* service blocks code-sync payloads on the REST contribution route (Cloudflare 403 "Blocked").
|
|
65
|
+
*/
|
|
66
|
+
async callTool(name, args) {
|
|
67
|
+
const response = await this.waking(async (timeoutMs) => {
|
|
68
|
+
const res = await fetch(this.mcp, {
|
|
69
|
+
method: "POST",
|
|
70
|
+
redirect: "error",
|
|
71
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
+
headers: {
|
|
73
|
+
authorization: `Bearer ${this.token}`,
|
|
74
|
+
"content-type": "application/json",
|
|
75
|
+
accept: "application/json, text/event-stream",
|
|
76
|
+
},
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
jsonrpc: "2.0",
|
|
79
|
+
id: 1,
|
|
80
|
+
method: "tools/call",
|
|
81
|
+
params: { name, arguments: args },
|
|
82
|
+
}),
|
|
83
|
+
});
|
|
84
|
+
if (!res.ok)
|
|
85
|
+
throw new GraphHttpError(res.status);
|
|
86
|
+
return res;
|
|
87
|
+
});
|
|
88
|
+
const reply = (await response.json());
|
|
89
|
+
const text = reply.result?.content?.[0]?.text;
|
|
90
|
+
if (reply.error || typeof text !== "string")
|
|
91
|
+
throw new Error(`Graph MCP ${name}: ${reply.error?.message ?? "malformed response"}`);
|
|
92
|
+
const payload = JSON.parse(text);
|
|
93
|
+
if (reply.result?.isError)
|
|
94
|
+
throw new GraphToolError(name, payload.code ?? "error");
|
|
95
|
+
if (payload.truncated || payload.data === undefined)
|
|
96
|
+
throw new Error(`Graph MCP ${name}: response truncated`);
|
|
97
|
+
return payload.data;
|
|
98
|
+
}
|
|
99
|
+
/** True when the server has recorded this contribution (it was applied or deliberately returned). */
|
|
100
|
+
async contributionRecorded(id) {
|
|
101
|
+
try {
|
|
102
|
+
await this.callTool("get_contribution_status", {
|
|
103
|
+
project_id: this.project,
|
|
104
|
+
contribution_id: id,
|
|
105
|
+
});
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (error instanceof GraphToolError && error.code === "NOT_FOUND")
|
|
110
|
+
return false;
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async query(filters) {
|
|
115
|
+
return this.request(`/query?${new URLSearchParams(filters)}`);
|
|
116
|
+
}
|
|
117
|
+
async all(filters) {
|
|
118
|
+
const nodes = [];
|
|
119
|
+
const edges = new Map();
|
|
120
|
+
let cursor;
|
|
121
|
+
let revision;
|
|
122
|
+
const seen = new Set();
|
|
123
|
+
do {
|
|
124
|
+
const page = await this.query({ ...filters, limit: "300", ...(cursor ? { cursor } : {}) });
|
|
125
|
+
nodes.push(...page.nodes);
|
|
126
|
+
page.edges.forEach((e) => edges.set(e.id, e));
|
|
127
|
+
revision = page.revision;
|
|
128
|
+
cursor = page.nextCursor;
|
|
129
|
+
if (page.truncated && !cursor)
|
|
130
|
+
throw new Error("Graph response truncated without continuation");
|
|
131
|
+
if (cursor && seen.has(cursor))
|
|
132
|
+
throw new Error("Repeated graph cursor");
|
|
133
|
+
if (cursor)
|
|
134
|
+
seen.add(cursor);
|
|
135
|
+
} while (cursor);
|
|
136
|
+
return { nodes, edges: [...edges.values()], revision, truncated: false };
|
|
137
|
+
}
|
|
138
|
+
async submit(body) {
|
|
139
|
+
const result = await this.callTool("submit_contribution", {
|
|
140
|
+
project_id: this.project,
|
|
141
|
+
// Encoded so the hosted CDN firewall cannot match source excerpts as attacks (#65).
|
|
142
|
+
contribution_b64: Buffer.from(JSON.stringify(body)).toString("base64"),
|
|
143
|
+
});
|
|
144
|
+
if (result.status !== "applied")
|
|
145
|
+
throw new Error(`Contribution returned; batch applied nothing: ${JSON.stringify(result.conflicts)}`);
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
async nodeEdges(id) {
|
|
149
|
+
const edges = [];
|
|
150
|
+
let cursor;
|
|
151
|
+
do {
|
|
152
|
+
const page = await this.request(`/nodes/${id}?include_inactive=true${cursor ? `&edge_cursor=${cursor}` : ""}`);
|
|
153
|
+
edges.push(...page.edges);
|
|
154
|
+
if (page.truncated && !page.nextEdgeCursor)
|
|
155
|
+
throw new Error("Node edges truncated without continuation");
|
|
156
|
+
cursor = page.nextEdgeCursor;
|
|
157
|
+
} while (cursor);
|
|
158
|
+
return edges;
|
|
159
|
+
}
|
|
160
|
+
async allEdges(namespace) {
|
|
161
|
+
const edges = [];
|
|
162
|
+
let cursor;
|
|
163
|
+
const seen = new Set();
|
|
164
|
+
do {
|
|
165
|
+
const page = await this.request(`/edges?${new URLSearchParams({ namespace, limit: "300", include_inactive: "true", ...(cursor ? { cursor } : {}) })}`);
|
|
166
|
+
edges.push(...page.edges);
|
|
167
|
+
cursor = page.nextCursor;
|
|
168
|
+
if (page.truncated && !cursor)
|
|
169
|
+
throw new Error("Edge list truncated without continuation");
|
|
170
|
+
if (cursor && seen.has(cursor))
|
|
171
|
+
throw new Error("Repeated edge cursor");
|
|
172
|
+
if (cursor)
|
|
173
|
+
seen.add(cursor);
|
|
174
|
+
} while (cursor);
|
|
175
|
+
return edges;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Batch sizing: the server accepts 200 items and 200,000 bytes per contribution. The item cap
|
|
180
|
+
* stays at 50 (below) because server cost per contribution is roughly quadratic in items; raising
|
|
181
|
+
* it risks the statement timeout for little gain. Write requests scale as nodes/50, reads as pages.
|
|
182
|
+
* The server allows 200,000 bytes, measured after the MCP tool schema fills defaults (aliases,
|
|
183
|
+
* namespace, properties…). Batches leave 20,000 bytes for those.
|
|
184
|
+
*/
|
|
185
|
+
const BATCH_BYTES = 180_000;
|
|
186
|
+
/**
|
|
187
|
+
* Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
|
|
188
|
+
* grows roughly quadratically with batch size; 50 stays under the 5 s statement timeout (#43).
|
|
189
|
+
*/
|
|
190
|
+
export const BATCH_ITEMS = 50;
|
|
191
|
+
export function chunks(items, make) {
|
|
192
|
+
const result = [];
|
|
193
|
+
let current = [];
|
|
194
|
+
for (const item of items) {
|
|
195
|
+
const candidate = [...current, item];
|
|
196
|
+
if (candidate.length > BATCH_ITEMS ||
|
|
197
|
+
Buffer.byteLength(JSON.stringify(make(candidate))) > BATCH_BYTES) {
|
|
198
|
+
if (!current.length)
|
|
199
|
+
throw new Error("Single contribution item exceeds 200KB");
|
|
200
|
+
result.push(current);
|
|
201
|
+
current = [item];
|
|
202
|
+
if (Buffer.byteLength(JSON.stringify(make(current))) > BATCH_BYTES)
|
|
203
|
+
throw new Error("Single contribution item exceeds 200KB");
|
|
204
|
+
}
|
|
205
|
+
else
|
|
206
|
+
current = candidate;
|
|
207
|
+
}
|
|
208
|
+
if (current.length)
|
|
209
|
+
result.push(current);
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* A failure that suggests the transaction did not commit. A PostgreSQL statement timeout reaches
|
|
214
|
+
* the client through the MCP tool wrapper as HTTP 200 with isError and the code "INTERNAL" (the raw
|
|
215
|
+
* 57014/"timeout" text is never exposed), so that exact code is matched. HTTP 5xx only comes from a
|
|
216
|
+
* gateway or proxy in front of the server.
|
|
217
|
+
* Known race: after a 502/504 the server may still commit after get_contribution_status returned
|
|
218
|
+
* NOT_FOUND; the halves then hit conflicts and the run stops. That is safe but not self-healing.
|
|
219
|
+
*/
|
|
220
|
+
function isRolledBack(error) {
|
|
221
|
+
if (error instanceof GraphHttpError)
|
|
222
|
+
return error.status >= 500;
|
|
223
|
+
return error instanceof GraphToolError && error.code === "INTERNAL";
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Submits one batch. On a server error or statement timeout the batch is retried once as two
|
|
227
|
+
* halves, but only after the server confirms it never recorded the original contribution. A
|
|
228
|
+
* failure of either half propagates and stops the run. Returns one receipt per submitted piece.
|
|
229
|
+
*/
|
|
230
|
+
export async function submitBatch(api, group, make) {
|
|
231
|
+
const whole = make(group);
|
|
232
|
+
try {
|
|
233
|
+
return [{ items: group, receipt: await api.submit(whole) }];
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (group.length < 2 || !isRolledBack(error))
|
|
237
|
+
throw error;
|
|
238
|
+
if (await api.contributionRecorded(whole.contributionId))
|
|
239
|
+
throw error;
|
|
240
|
+
const mid = Math.ceil(group.length / 2);
|
|
241
|
+
const out = [];
|
|
242
|
+
for (const half of [group.slice(0, mid), group.slice(mid)])
|
|
243
|
+
out.push({ items: half, receipt: await api.submit(make(half)) });
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
function stable(value) {
|
|
248
|
+
const sort = (v) => Array.isArray(v)
|
|
249
|
+
? v.map(sort)
|
|
250
|
+
: v && typeof v === "object"
|
|
251
|
+
? Object.fromEntries(Object.entries(v)
|
|
252
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
253
|
+
.map(([k, x]) => [k, sort(x)]))
|
|
254
|
+
: v;
|
|
255
|
+
return JSON.stringify(sort(value));
|
|
256
|
+
}
|
|
257
|
+
const comparable = (n) => stable([
|
|
258
|
+
n.title,
|
|
259
|
+
n.body,
|
|
260
|
+
n.status ?? null,
|
|
261
|
+
n.properties,
|
|
262
|
+
n.derivation,
|
|
263
|
+
n.provenance.map((p) => [p.repo, p.commit, p.path, p.startLine, p.endLine]),
|
|
264
|
+
]);
|
|
265
|
+
const edgeKey = (e) => stable([
|
|
266
|
+
e.type,
|
|
267
|
+
e.from,
|
|
268
|
+
e.to,
|
|
269
|
+
e.properties.contextNamespace ?? null,
|
|
270
|
+
e.type === "amends" ? (e.properties.scope ?? null) : null,
|
|
271
|
+
]);
|
|
272
|
+
/** Server state is authoritative; local state is never used to skip reconciliation. */
|
|
273
|
+
export async function reconcile(api, snapshot, namespace, supersede = true,
|
|
274
|
+
/** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
|
|
275
|
+
anchors = new Map()) {
|
|
276
|
+
const existing = await api.all({ namespace, include_inactive: "true" });
|
|
277
|
+
const byKey = new Map(existing.nodes.map((n) => [n.clientKey, n]));
|
|
278
|
+
// Entities imported before namespace adoption carry the same client key outside the namespace.
|
|
279
|
+
// One project-wide scan of the snapshot's node types (pages of 300) replaces one exact
|
|
280
|
+
// client_key request per absent node, so a first sync of N nodes costs pages, not N requests.
|
|
281
|
+
const absent = new Set(snapshot.nodes.filter((n) => !byKey.has(n.clientKey)).map((n) => n.clientKey));
|
|
282
|
+
if (absent.size) {
|
|
283
|
+
const types = [...new Set(snapshot.nodes.map((n) => n.type))].join(",");
|
|
284
|
+
const found = new Map();
|
|
285
|
+
for (const n of (await api.all({ types, include_inactive: "true" })).nodes)
|
|
286
|
+
if (absent.has(n.clientKey)) {
|
|
287
|
+
if (found.has(n.clientKey))
|
|
288
|
+
throw new Error(`Ambiguous client key ${n.clientKey}`);
|
|
289
|
+
found.set(n.clientKey, n);
|
|
290
|
+
}
|
|
291
|
+
for (const [key, n] of found)
|
|
292
|
+
byKey.set(key, n);
|
|
293
|
+
}
|
|
294
|
+
const ids = new Map([...anchors, ...[...byKey].map(([key, n]) => [key, n.id])]);
|
|
295
|
+
const desired = new Set(snapshot.nodes.map((n) => n.clientKey));
|
|
296
|
+
const revisions = [];
|
|
297
|
+
const fresh = snapshot.nodes.filter((n) => !byKey.has(n.clientKey));
|
|
298
|
+
for (const n of snapshot.nodes) {
|
|
299
|
+
const old = byKey.get(n.clientKey);
|
|
300
|
+
if (old && (comparable(n) !== comparable(old) || old.lifecycle !== "active"))
|
|
301
|
+
revisions.push({
|
|
302
|
+
nodeId: old.id,
|
|
303
|
+
expectedRevision: old.revision,
|
|
304
|
+
title: n.title,
|
|
305
|
+
body: n.body,
|
|
306
|
+
...(n.status ? { status: n.status } : {}),
|
|
307
|
+
properties: n.properties,
|
|
308
|
+
provenance: n.provenance,
|
|
309
|
+
derivation: n.derivation,
|
|
310
|
+
lifecycle: "active",
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
if (supersede)
|
|
314
|
+
for (const old of existing.nodes)
|
|
315
|
+
if (!desired.has(old.clientKey) && old.lifecycle === "active")
|
|
316
|
+
revisions.push({
|
|
317
|
+
nodeId: old.id,
|
|
318
|
+
expectedRevision: old.revision,
|
|
319
|
+
lifecycle: "superseded",
|
|
320
|
+
reason: "Absent from repository snapshot",
|
|
321
|
+
provenance: old.provenance,
|
|
322
|
+
});
|
|
323
|
+
let contributions = 0;
|
|
324
|
+
const empty = () => ({
|
|
325
|
+
contributionId: randomUUID(),
|
|
326
|
+
summary: "Deterministic repository context sync",
|
|
327
|
+
nodes: [],
|
|
328
|
+
edges: [],
|
|
329
|
+
revisions: [],
|
|
330
|
+
edgeRevisions: [],
|
|
331
|
+
});
|
|
332
|
+
for (const batch of chunks(fresh, (nodes) => ({ ...empty(), nodes })))
|
|
333
|
+
for (const { items: group, receipt } of await submitBatch(api, batch, (nodes) => ({
|
|
334
|
+
...empty(),
|
|
335
|
+
nodes,
|
|
336
|
+
}))) {
|
|
337
|
+
contributions++;
|
|
338
|
+
if (receipt.nodeIds.length !== group.length)
|
|
339
|
+
throw new Error("Receipt node mapping incomplete");
|
|
340
|
+
group.forEach((n, i) => {
|
|
341
|
+
const id = receipt.nodeIds[i];
|
|
342
|
+
if (!id)
|
|
343
|
+
throw new Error("Missing node receipt id");
|
|
344
|
+
ids.set(n.clientKey, id);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
for (const batch of chunks(revisions, (revisions) => ({ ...empty(), revisions })))
|
|
348
|
+
contributions += (await submitBatch(api, batch, (revisions) => ({ ...empty(), revisions })))
|
|
349
|
+
.length;
|
|
350
|
+
const currentEdges = new Map((await api.allEdges(namespace)).map((e) => [e.id, e]));
|
|
351
|
+
const desiredEdges = snapshot.edges.map((e) => {
|
|
352
|
+
const from = ids.get(e.from), to = ids.get(e.to);
|
|
353
|
+
if (!from || !to)
|
|
354
|
+
throw new Error("Unresolved edge endpoint");
|
|
355
|
+
return { ...e, from, to, properties: { ...e.properties, contextNamespace: namespace } };
|
|
356
|
+
});
|
|
357
|
+
const grouped = new Map();
|
|
358
|
+
for (const edge of desiredEdges) {
|
|
359
|
+
const key = edgeKey(edge);
|
|
360
|
+
const old = grouped.get(key);
|
|
361
|
+
if (old) {
|
|
362
|
+
if (stable(old.properties) !== stable(edge.properties) || old.derivation !== edge.derivation)
|
|
363
|
+
throw new Error("Ambiguous duplicate relationship metadata");
|
|
364
|
+
old.provenance.push(...edge.provenance);
|
|
365
|
+
}
|
|
366
|
+
else
|
|
367
|
+
grouped.set(key, { ...edge, provenance: [...edge.provenance] });
|
|
368
|
+
}
|
|
369
|
+
const edges = [...grouped.values()].map((edge) => {
|
|
370
|
+
const sources = new Map();
|
|
371
|
+
for (const locator of edge.provenance) {
|
|
372
|
+
const key = stable([locator.repo, locator.commit, locator.path]);
|
|
373
|
+
const old = sources.get(key);
|
|
374
|
+
sources.set(key, old
|
|
375
|
+
? {
|
|
376
|
+
...locator,
|
|
377
|
+
startLine: Math.min(old.startLine, locator.startLine),
|
|
378
|
+
endLine: Math.max(old.endLine, locator.endLine),
|
|
379
|
+
}
|
|
380
|
+
: locator);
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
...edge,
|
|
384
|
+
provenance: [...sources.values()].sort((a, b) => stable(a).localeCompare(stable(b))),
|
|
385
|
+
};
|
|
386
|
+
});
|
|
387
|
+
const active = new Set([...currentEdges.values()].filter((e) => e.lifecycle === "active").map(edgeKey));
|
|
388
|
+
const wanted = new Set(edges.map(edgeKey));
|
|
389
|
+
const missing = edges.filter((e) => !active.has(edgeKey(e)));
|
|
390
|
+
for (const batch of chunks(missing, (edges) => ({ ...empty(), edges })))
|
|
391
|
+
contributions += (await submitBatch(api, batch, (edges) => ({ ...empty(), edges }))).length;
|
|
392
|
+
const activeByKey = new Map();
|
|
393
|
+
const duplicateIds = new Set();
|
|
394
|
+
for (const edge of [...currentEdges.values()]
|
|
395
|
+
.filter((e) => e.lifecycle === "active" && e.properties.contextNamespace === namespace)
|
|
396
|
+
.sort((a, b) => a.id.localeCompare(b.id))) {
|
|
397
|
+
const key = edgeKey(edge);
|
|
398
|
+
if (activeByKey.has(key))
|
|
399
|
+
duplicateIds.add(edge.id);
|
|
400
|
+
else
|
|
401
|
+
activeByKey.set(key, edge);
|
|
402
|
+
}
|
|
403
|
+
const updated = [];
|
|
404
|
+
for (const edge of edges) {
|
|
405
|
+
const old = activeByKey.get(edgeKey(edge));
|
|
406
|
+
if (old &&
|
|
407
|
+
stable([old.provenance, old.derivation, old.properties]) !==
|
|
408
|
+
stable([edge.provenance, edge.derivation, edge.properties]))
|
|
409
|
+
updated.push({
|
|
410
|
+
edgeId: old.id,
|
|
411
|
+
expectedRevision: old.revision,
|
|
412
|
+
provenance: edge.provenance,
|
|
413
|
+
derivation: edge.derivation,
|
|
414
|
+
properties: edge.properties,
|
|
415
|
+
lifecycle: "active",
|
|
416
|
+
reason: "Repository snapshot metadata changed",
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
const edgeRevisions = [...currentEdges.values()]
|
|
420
|
+
.filter((e) => e.lifecycle === "active" &&
|
|
421
|
+
e.properties.contextNamespace === namespace &&
|
|
422
|
+
(!wanted.has(edgeKey(e)) || duplicateIds.has(e.id)))
|
|
423
|
+
.map((e) => ({
|
|
424
|
+
edgeId: e.id,
|
|
425
|
+
expectedRevision: e.revision,
|
|
426
|
+
provenance: e.provenance,
|
|
427
|
+
lifecycle: "superseded",
|
|
428
|
+
reason: duplicateIds.has(e.id)
|
|
429
|
+
? "Duplicate relationship consolidated with retained provenance"
|
|
430
|
+
: "Absent from repository snapshot",
|
|
431
|
+
}))
|
|
432
|
+
.concat(updated);
|
|
433
|
+
for (const batch of chunks(edgeRevisions, (edgeRevisions) => ({ ...empty(), edgeRevisions })))
|
|
434
|
+
contributions += (await submitBatch(api, batch, (edgeRevisions) => ({ ...empty(), edgeRevisions }))).length;
|
|
435
|
+
return {
|
|
436
|
+
contributions,
|
|
437
|
+
digest: createHash("sha256").update(JSON.stringify(snapshot)).digest("hex"),
|
|
438
|
+
};
|
|
439
|
+
}
|
package/dist/cboard.d.ts
ADDED
package/dist/cboard.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { sync } from "./cli.js";
|
|
5
|
+
import { docsSync } from "./docs.js";
|
|
6
|
+
import { issuesSync } from "./issues.js";
|
|
7
|
+
const HELP = `cboard — client for cboard project graphs
|
|
8
|
+
|
|
9
|
+
Usage: cboard <command> [flags]
|
|
10
|
+
|
|
11
|
+
Commands:
|
|
12
|
+
connect Connect this repository to a cboard project (writes .cboard.json, .cboard/, .mcp.json, hooks)
|
|
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
|
|
16
|
+
check Check that this repository can reach its cboard graph
|
|
17
|
+
|
|
18
|
+
Run "cboard <command> --help" for a command's flags.
|
|
19
|
+
Options:
|
|
20
|
+
--help, -h Show this help
|
|
21
|
+
--version, -v Show the version
|
|
22
|
+
`;
|
|
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.
|
|
31
|
+
|
|
32
|
+
Writes .cboard.json, the committed kit in .cboard/ (hooks and the MCP header helper run it, never npx),
|
|
33
|
+
.mcp.json, the SessionStart hooks, an AGENTS.md block, the cboard-graph skill and a .gitattributes
|
|
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).
|
|
41
|
+
`;
|
|
42
|
+
const SYNC_HELP = `Usage: cboard sync [--repo PATH] [--project UUID] [--server URL] [--token-env NAME] [--state PATH]
|
|
43
|
+
|
|
44
|
+
Project, server and token come from .cboard.json and the repo token file when the flags are omitted.
|
|
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
|
+
`;
|
|
57
|
+
const CHECK_HELP = `Usage: cboard check
|
|
58
|
+
|
|
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).
|
|
61
|
+
Exits 1 when it is not connected.
|
|
62
|
+
`;
|
|
63
|
+
const packageFile = new URL("../package.json", import.meta.url);
|
|
64
|
+
function version() {
|
|
65
|
+
return JSON.parse(readFileSync(packageFile, "utf8")).version;
|
|
66
|
+
}
|
|
67
|
+
/** The kit lives at ../kit in the installed package (copied by scripts/build-kit.js) and under scripts/ in a checkout. */
|
|
68
|
+
function kitFile(name) {
|
|
69
|
+
for (const base of ["../kit/", "../../../scripts/"]) {
|
|
70
|
+
const file = fileURLToPath(new URL(base + name, import.meta.url));
|
|
71
|
+
if (existsSync(file))
|
|
72
|
+
return file;
|
|
73
|
+
}
|
|
74
|
+
throw new Error(`the connect kit is missing (${name}); reinstall @codyn06/cboard`);
|
|
75
|
+
}
|
|
76
|
+
function run(script, args) {
|
|
77
|
+
const result = spawnSync(process.execPath, [script, ...args], { stdio: "inherit" });
|
|
78
|
+
return result.status ?? 1;
|
|
79
|
+
}
|
|
80
|
+
/** @returns the process exit code */
|
|
81
|
+
export async function main(argv) {
|
|
82
|
+
const [command, ...rest] = argv;
|
|
83
|
+
const wantsHelp = rest.includes("--help") || rest.includes("-h");
|
|
84
|
+
switch (command) {
|
|
85
|
+
case "--version":
|
|
86
|
+
case "-v":
|
|
87
|
+
console.log(version());
|
|
88
|
+
return 0;
|
|
89
|
+
case "--help":
|
|
90
|
+
case "-h":
|
|
91
|
+
case "help":
|
|
92
|
+
console.log(HELP);
|
|
93
|
+
return 0;
|
|
94
|
+
case "connect":
|
|
95
|
+
if (wantsHelp) {
|
|
96
|
+
console.log(CONNECT_HELP);
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
return run(kitFile("cboard-connect.js"), rest);
|
|
100
|
+
case "check":
|
|
101
|
+
if (wantsHelp) {
|
|
102
|
+
console.log(CHECK_HELP);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
return run(kitFile("cboard-kit/connect-check.js"), rest);
|
|
106
|
+
case "sync":
|
|
107
|
+
if (wantsHelp) {
|
|
108
|
+
console.log(SYNC_HELP);
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
await sync(rest);
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
console.error(error instanceof Error ? error.message : "Context sync failed");
|
|
117
|
+
return 1;
|
|
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
|
+
}
|
|
145
|
+
default:
|
|
146
|
+
if (command)
|
|
147
|
+
console.error(`cboard: unknown command "${command}"\n`);
|
|
148
|
+
console.error(HELP);
|
|
149
|
+
return 2;
|
|
150
|
+
}
|
|
151
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export declare function options(argv: string[]): Record<string, string>;
|
|
3
|
+
interface RepoConfig {
|
|
4
|
+
server?: string;
|
|
5
|
+
projectId?: string;
|
|
6
|
+
tokenFile?: string;
|
|
7
|
+
tokenEnv?: string;
|
|
8
|
+
}
|
|
9
|
+
/** The repository's .cboard.json (written by cboard-connect), or {} when absent. */
|
|
10
|
+
export declare function repoConfig(root: string): RepoConfig;
|
|
11
|
+
export declare const DEFAULT_SERVER = "https://cboard-fij7.onrender.com";
|
|
12
|
+
export declare const DEFAULT_TOKEN_ENV = "CBOARD_PAT";
|
|
13
|
+
/**
|
|
14
|
+
* Which server, project and token a sync uses. Explicit flags win over the environment, which
|
|
15
|
+
* wins over .cboard.json. .cboard.json is tracked, so a cloned repository must not be able to
|
|
16
|
+
* steer a token elsewhere: these rules mirror resolveConfig in scripts/cboard-kit/config.js
|
|
17
|
+
* (keep them in step): tokenEnv must be CBOARD_*, tokenFile must stay inside the repository, a
|
|
18
|
+
* non-default server named only by the file needs CBOARD_TRUSTED_SERVERS, non-local servers
|
|
19
|
+
* must be https, and a local server never receives the hosted token file. The token is never logged.
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolveSync(args: Record<string, string>, root: string): {
|
|
22
|
+
project: string;
|
|
23
|
+
token: string;
|
|
24
|
+
server: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function sync(argv: string[]): Promise<void>;
|
|
27
|
+
export {};
|