@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 +5 -2
- package/dist/api.d.ts +36 -4
- package/dist/api.js +128 -51
- package/dist/cache.d.ts +28 -0
- package/dist/cache.js +101 -0
- package/dist/cboard.js +57 -3
- package/dist/cli.js +2 -1
- package/dist/docs.d.ts +39 -0
- package/dist/docs.js +244 -0
- package/dist/extract.js +23 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/issues.d.ts +44 -0
- package/dist/issues.js +139 -0
- package/dist/wake.d.ts +13 -0
- package/dist/wake.js +33 -0
- package/kit/cboard-connect.js +425 -46
- package/kit/cboard-kit/brief.js +144 -18
- package/kit/cboard-kit/config.js +38 -3
- package/kit/cboard-kit/connect-check.js +56 -13
- package/kit/cboard-kit/device.js +192 -0
- package/kit/cboard-kit/drift.js +55 -0
- package/kit/cboard-kit/headers.js +24 -3
- package/kit/cboard-kit/mcp.js +38 -3
- package/kit/cboard-kit/references.js +70 -0
- package/kit/cboard-kit/skill/SKILL.md +16 -0
- package/kit/cboard-kit/wait.js +45 -0
- package/package.json +1 -1
package/dist/docs.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Snapshot } from "./model.js";
|
|
2
|
+
/** `.cboard.json` `docs` block: globs relative to the repository root. */
|
|
3
|
+
export interface DocsConfig {
|
|
4
|
+
include?: string[];
|
|
5
|
+
exclude?: string[];
|
|
6
|
+
}
|
|
7
|
+
/** The optional `docs` block of `.cboard.json`; malformed values are ignored. */
|
|
8
|
+
export declare function docsConfig(root: string): DocsConfig;
|
|
9
|
+
export interface Section {
|
|
10
|
+
heading: string;
|
|
11
|
+
/** Heading line plus content, H3 and deeper folded in. */
|
|
12
|
+
text: string;
|
|
13
|
+
startLine: number;
|
|
14
|
+
endLine: number;
|
|
15
|
+
/** No content except headings. */
|
|
16
|
+
headingOnly: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Splits Markdown at H2 headings (fenced code is skipped). Merges heading-only fragments. */
|
|
19
|
+
export declare function parseMarkdown(text: string): {
|
|
20
|
+
title: string | undefined;
|
|
21
|
+
intro: string;
|
|
22
|
+
sections: Section[];
|
|
23
|
+
};
|
|
24
|
+
/** Maps an ADR status to the decision vocabulary; unknown wording gives no status. */
|
|
25
|
+
export declare function adrStatus(text: string): string | undefined;
|
|
26
|
+
export interface DocsSummary {
|
|
27
|
+
files: number;
|
|
28
|
+
sections: number;
|
|
29
|
+
truncated: number;
|
|
30
|
+
}
|
|
31
|
+
/** Reads the committed HEAD tree and builds the docs-layer snapshot. */
|
|
32
|
+
export declare function extractDocs(root: string, config?: DocsConfig): Snapshot & {
|
|
33
|
+
repo: string;
|
|
34
|
+
commit: string;
|
|
35
|
+
namespace: string;
|
|
36
|
+
summary: DocsSummary;
|
|
37
|
+
};
|
|
38
|
+
/** `cboard docs sync`: Markdown docs of this repository into the graph. */
|
|
39
|
+
export declare function docsSync(argv: string[]): Promise<void>;
|
package/dist/docs.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { posix, resolve } from "node:path";
|
|
4
|
+
import { ContextApi, reconcile } from "./api.js";
|
|
5
|
+
import { fileHeadStore } from "./cache.js";
|
|
6
|
+
import { options, resolveSync } from "./cli.js";
|
|
7
|
+
import { repository } from "./extract.js";
|
|
8
|
+
import { globMatcher } from "./languages.js";
|
|
9
|
+
const DEFAULT_INCLUDE = ["README.md", "docs/**/*.md", "docs/adr/**", "adr/**", "docs/decisions/**"];
|
|
10
|
+
const ADR = ["docs/adr/**", "adr/**", "docs/decisions/**"].map(globMatcher);
|
|
11
|
+
const PLAN = globMatcher("docs/plans/**");
|
|
12
|
+
const MARKDOWN = /\.(md|markdown)$/i;
|
|
13
|
+
/** The server stores 8192 bytes; leave room like the code layer does. */
|
|
14
|
+
const BODY_BYTES = 7800;
|
|
15
|
+
/** The optional `docs` block of `.cboard.json`; malformed values are ignored. */
|
|
16
|
+
export function docsConfig(root) {
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(readFileSync(resolve(root, ".cboard.json"), "utf8"));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
const found = parsed?.docs;
|
|
25
|
+
if (typeof found !== "object" || !found)
|
|
26
|
+
return {};
|
|
27
|
+
const docs = found;
|
|
28
|
+
const globs = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : undefined;
|
|
29
|
+
const config = {};
|
|
30
|
+
const include = globs(docs.include), exclude = globs(docs.exclude);
|
|
31
|
+
if (include)
|
|
32
|
+
config.include = include;
|
|
33
|
+
if (exclude)
|
|
34
|
+
config.exclude = exclude;
|
|
35
|
+
return config;
|
|
36
|
+
}
|
|
37
|
+
function capBody(text) {
|
|
38
|
+
if (Buffer.byteLength(text) <= BODY_BYTES)
|
|
39
|
+
return { body: text, truncated: false };
|
|
40
|
+
let bytes = 0, body = "";
|
|
41
|
+
for (const character of text) {
|
|
42
|
+
const size = Buffer.byteLength(character);
|
|
43
|
+
if (bytes + size > BODY_BYTES)
|
|
44
|
+
break;
|
|
45
|
+
bytes += size;
|
|
46
|
+
body += character;
|
|
47
|
+
}
|
|
48
|
+
return { body, truncated: true };
|
|
49
|
+
}
|
|
50
|
+
const plain = (s) => s
|
|
51
|
+
.replace(/\*\*|`/g, "")
|
|
52
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
53
|
+
.replace(/\s+/g, " ")
|
|
54
|
+
.trim();
|
|
55
|
+
const slugOf = (s) => plain(s)
|
|
56
|
+
.toLowerCase()
|
|
57
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
58
|
+
.replace(/^-+|-+$/g, "")
|
|
59
|
+
.slice(0, 60) || "section";
|
|
60
|
+
/** Splits Markdown at H2 headings (fenced code is skipped). Merges heading-only fragments. */
|
|
61
|
+
export function parseMarkdown(text) {
|
|
62
|
+
const lines = text.split(/\r?\n/);
|
|
63
|
+
let title;
|
|
64
|
+
const introLines = [];
|
|
65
|
+
const raw = [];
|
|
66
|
+
let fence = "";
|
|
67
|
+
lines.forEach((line, index) => {
|
|
68
|
+
const mark = /^\s*(```+|~~~+)/.exec(line)?.[1];
|
|
69
|
+
let heading = null;
|
|
70
|
+
if (mark) {
|
|
71
|
+
if (!fence)
|
|
72
|
+
fence = mark;
|
|
73
|
+
else if (mark === fence)
|
|
74
|
+
fence = "";
|
|
75
|
+
}
|
|
76
|
+
else if (!fence)
|
|
77
|
+
heading = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
|
|
78
|
+
const level = heading?.[1]?.length ?? 0;
|
|
79
|
+
const current = raw[raw.length - 1];
|
|
80
|
+
if (heading && level === 1 && !title && !current)
|
|
81
|
+
title = plain(heading[2] ?? "");
|
|
82
|
+
else if (heading && level <= 2) {
|
|
83
|
+
raw.push({
|
|
84
|
+
heading: plain(heading[2] ?? ""),
|
|
85
|
+
lines: [line],
|
|
86
|
+
start: index + 1,
|
|
87
|
+
content: false,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else if (current) {
|
|
91
|
+
current.lines.push(line);
|
|
92
|
+
if (!heading && line.trim())
|
|
93
|
+
current.content = true;
|
|
94
|
+
}
|
|
95
|
+
else
|
|
96
|
+
introLines.push(line);
|
|
97
|
+
});
|
|
98
|
+
const sections = raw.map((r) => ({
|
|
99
|
+
heading: r.heading,
|
|
100
|
+
text: r.lines.join("\n").trimEnd(),
|
|
101
|
+
startLine: r.start,
|
|
102
|
+
endLine: r.start + r.lines.length - 1,
|
|
103
|
+
headingOnly: !r.content,
|
|
104
|
+
}));
|
|
105
|
+
// A heading-only fragment joins the section before it (its parent), else the one after it.
|
|
106
|
+
const merged = [];
|
|
107
|
+
let pending = [];
|
|
108
|
+
for (const s of sections) {
|
|
109
|
+
if (s.headingOnly) {
|
|
110
|
+
const previous = merged[merged.length - 1];
|
|
111
|
+
if (previous) {
|
|
112
|
+
previous.text += `\n\n${s.text}`;
|
|
113
|
+
previous.endLine = s.endLine;
|
|
114
|
+
}
|
|
115
|
+
else
|
|
116
|
+
pending.push(s);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (pending.length) {
|
|
120
|
+
s.text = `${pending.map((p) => p.text).join("\n\n")}\n\n${s.text}`;
|
|
121
|
+
s.startLine = pending[0]?.startLine ?? s.startLine;
|
|
122
|
+
pending = [];
|
|
123
|
+
}
|
|
124
|
+
merged.push(s);
|
|
125
|
+
}
|
|
126
|
+
return { title, intro: introLines.join("\n").trim(), sections: merged };
|
|
127
|
+
}
|
|
128
|
+
/** Maps an ADR status to the decision vocabulary; unknown wording gives no status. */
|
|
129
|
+
export function adrStatus(text) {
|
|
130
|
+
let value = /^\s*[*_]*status[*_]*\s*:[*_]*\s*(.+)$/im.exec(text)?.[1];
|
|
131
|
+
value ??= /^#{1,6}\s+status\s*\r?\n+\s*(\S.*)$/im.exec(text)?.[1];
|
|
132
|
+
const word = value ? plain(value).toLowerCase() : "";
|
|
133
|
+
if (/^(accepted|approved|adopted)/.test(word))
|
|
134
|
+
return "accepted";
|
|
135
|
+
if (/^decided/.test(word))
|
|
136
|
+
return "decided";
|
|
137
|
+
if (/^(proposed|draft|pending)/.test(word))
|
|
138
|
+
return "proposed";
|
|
139
|
+
if (/^rejected/.test(word))
|
|
140
|
+
return "rejected";
|
|
141
|
+
if (/^(superseded|deprecated|obsolete)/.test(word))
|
|
142
|
+
return "superseded";
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
/** Reads the committed HEAD tree and builds the docs-layer snapshot. */
|
|
146
|
+
export function extractDocs(root, config = {}) {
|
|
147
|
+
root = resolve(root);
|
|
148
|
+
const { repo, commit, namespace: codeNamespace } = repository(root);
|
|
149
|
+
const namespace = codeNamespace.replace(/^code:/, "docs:");
|
|
150
|
+
const nodes = [], edges = [];
|
|
151
|
+
const summary = { files: 0, sections: 0, truncated: 0 };
|
|
152
|
+
const location = (path, startLine = 1, endLine = startLine) => [
|
|
153
|
+
{ kind: "repo", repo, commit, path, startLine, endLine },
|
|
154
|
+
];
|
|
155
|
+
const add = (path, symbol, type, title, body, start, end, status, properties = {}) => {
|
|
156
|
+
const clientKey = `${namespace}:${path}${symbol ? `#${symbol}` : ""}`;
|
|
157
|
+
const capped = capBody(body);
|
|
158
|
+
title = title.length > 300 ? `${title.slice(0, 299)}…` : title;
|
|
159
|
+
if (clientKey.length > 1024)
|
|
160
|
+
throw new Error(`Document identity exceeds graph limits: ${path}`);
|
|
161
|
+
nodes.push({
|
|
162
|
+
clientKey,
|
|
163
|
+
namespace,
|
|
164
|
+
type,
|
|
165
|
+
title,
|
|
166
|
+
body: capped.body,
|
|
167
|
+
...(status ? { status } : {}),
|
|
168
|
+
properties: capped.truncated ? { ...properties, bodyTruncated: true } : properties,
|
|
169
|
+
provenance: location(path, start, end),
|
|
170
|
+
derivation: "extracted",
|
|
171
|
+
});
|
|
172
|
+
if (capped.truncated)
|
|
173
|
+
summary.truncated++;
|
|
174
|
+
return clientKey;
|
|
175
|
+
};
|
|
176
|
+
const link = (type, from, to, path) => edges.push({
|
|
177
|
+
type,
|
|
178
|
+
from,
|
|
179
|
+
to,
|
|
180
|
+
provenance: location(path),
|
|
181
|
+
derivation: "extracted",
|
|
182
|
+
properties: {},
|
|
183
|
+
});
|
|
184
|
+
const repoKey = add(".", "", "repository", `Repository ${repo} (docs)`, "", 1, 1);
|
|
185
|
+
const include = (config.include?.length ? config.include : DEFAULT_INCLUDE).map(globMatcher);
|
|
186
|
+
const exclude = (config.exclude ?? []).map(globMatcher);
|
|
187
|
+
const tracked = execFileSync("git", ["ls-tree", "-r", "-z", commit], {
|
|
188
|
+
cwd: root,
|
|
189
|
+
encoding: "utf8",
|
|
190
|
+
maxBuffer: Infinity,
|
|
191
|
+
})
|
|
192
|
+
.split("\0")
|
|
193
|
+
.filter(Boolean)
|
|
194
|
+
.flatMap((entry) => {
|
|
195
|
+
const tab = entry.indexOf("\t");
|
|
196
|
+
const [mode, type, sha] = entry.slice(0, tab).split(/\s+/);
|
|
197
|
+
const path = entry.slice(tab + 1);
|
|
198
|
+
return type === "blob" && mode !== "120000" && sha && MARKDOWN.test(path)
|
|
199
|
+
? [{ path, sha }]
|
|
200
|
+
: [];
|
|
201
|
+
})
|
|
202
|
+
.filter(({ path }) => include.some((m) => m(path)) && !exclude.some((m) => m(path)))
|
|
203
|
+
.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
204
|
+
for (const { path, sha } of tracked) {
|
|
205
|
+
const text = execFileSync("git", ["cat-file", "blob", sha], {
|
|
206
|
+
cwd: root,
|
|
207
|
+
encoding: "utf8",
|
|
208
|
+
maxBuffer: Infinity,
|
|
209
|
+
}).replace(new RegExp(`^${String.fromCharCode(0xfeff)}`), "");
|
|
210
|
+
const parsed = parseMarkdown(text);
|
|
211
|
+
const isAdr = ADR.some((m) => m(path));
|
|
212
|
+
const type = isAdr ? "decision" : PLAN(path) ? "plan" : "source";
|
|
213
|
+
const status = isAdr ? adrStatus(text) : type === "plan" ? "planned" : "recorded";
|
|
214
|
+
const lineCount = text.split(/\r?\n/).length;
|
|
215
|
+
const fileKey = add(path, "", type, parsed.title || posix.basename(path), isAdr ? text : parsed.intro, 1, lineCount, status, { path });
|
|
216
|
+
summary.files++;
|
|
217
|
+
link("derived_from", fileKey, repoKey, path);
|
|
218
|
+
const used = new Map();
|
|
219
|
+
for (const section of parsed.sections) {
|
|
220
|
+
const base = slugOf(section.heading);
|
|
221
|
+
const n = (used.get(base) ?? 0) + 1;
|
|
222
|
+
used.set(base, n);
|
|
223
|
+
const sectionKey = add(path, n > 1 ? `${base}-${String(n)}` : base, "excerpt", `${path}: ${section.heading}`, section.text, section.startLine, section.endLine, undefined, { path, heading: section.heading });
|
|
224
|
+
summary.sections++;
|
|
225
|
+
link("part_of", sectionKey, fileKey, path);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return { nodes, edges, repo, commit, namespace, summary };
|
|
229
|
+
}
|
|
230
|
+
/** `cboard docs sync`: Markdown docs of this repository into the graph. */
|
|
231
|
+
export async function docsSync(argv) {
|
|
232
|
+
const args = options(argv);
|
|
233
|
+
const root = resolve(args.repo ?? process.cwd());
|
|
234
|
+
const { project, token, server } = resolveSync(args, root);
|
|
235
|
+
const snapshot = extractDocs(root, docsConfig(root));
|
|
236
|
+
const result = await reconcile(new ContextApi(server, project, token, { heads: fileHeadStore() }), snapshot, snapshot.namespace);
|
|
237
|
+
console.log(JSON.stringify({
|
|
238
|
+
commit: snapshot.commit,
|
|
239
|
+
nodes: snapshot.nodes.length,
|
|
240
|
+
edges: snapshot.edges.length,
|
|
241
|
+
contributions: result.contributions,
|
|
242
|
+
summary: snapshot.summary,
|
|
243
|
+
}));
|
|
244
|
+
}
|
package/dist/extract.js
CHANGED
|
@@ -5,6 +5,17 @@ import { posix, resolve } from "node:path";
|
|
|
5
5
|
import { adapterFor, openAdapter } from "./adapters/index.js";
|
|
6
6
|
import { globMatcher, languageOf } from "./languages.js";
|
|
7
7
|
const git = (root, args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
|
|
8
|
+
let warnedLocal = false;
|
|
9
|
+
/** Stable identity that `connect` stores in `.cboard.json` (the root commit hash). */
|
|
10
|
+
function configuredRepoId(root) {
|
|
11
|
+
try {
|
|
12
|
+
const id = JSON.parse(readFileSync(resolve(root, ".cboard.json"), "utf8")).repoId;
|
|
13
|
+
return typeof id === "string" ? id : "";
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return "";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
8
19
|
export function repository(root) {
|
|
9
20
|
root = resolve(root);
|
|
10
21
|
const commit = git(root, ["rev-parse", "HEAD"]);
|
|
@@ -26,7 +37,18 @@ export function repository(root) {
|
|
|
26
37
|
url.hash = "";
|
|
27
38
|
repo = url.toString();
|
|
28
39
|
}
|
|
29
|
-
|
|
40
|
+
if (!repo) {
|
|
41
|
+
const repoId = configuredRepoId(root);
|
|
42
|
+
if (repoId)
|
|
43
|
+
repo = `local:${repoId}`;
|
|
44
|
+
else {
|
|
45
|
+
repo = `local:${git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).replace(/\\/g, "/")}`;
|
|
46
|
+
if (!warnedLocal) {
|
|
47
|
+
warnedLocal = true;
|
|
48
|
+
console.error("cboard: no origin remote and no repoId in .cboard.json; this clone gets its own namespace. Run `cboard connect` to store a stable repoId.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
30
52
|
const namespace = `code:${createHash("sha256").update(repo).digest("hex").slice(0, 32)}`;
|
|
31
53
|
return { repo, commit, namespace };
|
|
32
54
|
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/issues.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ContextApi } from "./api.js";
|
|
2
|
+
export interface GithubIssue {
|
|
3
|
+
number: number;
|
|
4
|
+
title: string;
|
|
5
|
+
body?: string | null;
|
|
6
|
+
state: string;
|
|
7
|
+
html_url: string;
|
|
8
|
+
labels?: (string | {
|
|
9
|
+
name?: string;
|
|
10
|
+
})[];
|
|
11
|
+
pull_request?: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface IssueRequest {
|
|
14
|
+
owner: string;
|
|
15
|
+
name: string;
|
|
16
|
+
state: "all" | "open";
|
|
17
|
+
limit?: number | undefined;
|
|
18
|
+
}
|
|
19
|
+
export type IssueSource = (request: IssueRequest) => Promise<GithubIssue[]>;
|
|
20
|
+
export interface IssuesOptions {
|
|
21
|
+
state: "all" | "open";
|
|
22
|
+
limit?: number | undefined;
|
|
23
|
+
}
|
|
24
|
+
/** owner/name from an https or ssh GitHub remote URL. */
|
|
25
|
+
export declare function parseGithubRemote(remote: string): {
|
|
26
|
+
owner: string;
|
|
27
|
+
name: string;
|
|
28
|
+
};
|
|
29
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
30
|
+
export declare function issuesSyncOptions(argv: string[]): Record<string, string> & IssuesOptions;
|
|
31
|
+
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
32
|
+
export declare const githubSource: IssueSource;
|
|
33
|
+
/**
|
|
34
|
+
* Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
|
|
35
|
+
* list is partial (--state open or --limit) unseen issues are kept, not superseded.
|
|
36
|
+
*/
|
|
37
|
+
export declare function runIssuesSync(api: ContextApi, identity: {
|
|
38
|
+
repo: string;
|
|
39
|
+
namespace: string;
|
|
40
|
+
}, source: IssueSource, options: IssuesOptions): Promise<{
|
|
41
|
+
issues: number;
|
|
42
|
+
contributions: number;
|
|
43
|
+
}>;
|
|
44
|
+
export declare function issuesSync(argv: string[], source?: IssueSource): Promise<void>;
|
package/dist/issues.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { ContextApi, reconcile } from "./api.js";
|
|
6
|
+
import { fileHeadStore } from "./cache.js";
|
|
7
|
+
import { resolveSync } from "./cli.js";
|
|
8
|
+
import { repository } from "./extract.js";
|
|
9
|
+
const run = promisify(execFile);
|
|
10
|
+
const BODY_MAX = 4000;
|
|
11
|
+
/** owner/name from an https or ssh GitHub remote URL. */
|
|
12
|
+
export function parseGithubRemote(remote) {
|
|
13
|
+
const match = /github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(remote);
|
|
14
|
+
if (!match?.[1] || !match[2])
|
|
15
|
+
throw new Error(`The origin remote is not a GitHub repository: ${remote || "(none)"}`);
|
|
16
|
+
return { owner: match[1], name: match[2] };
|
|
17
|
+
}
|
|
18
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
19
|
+
export function issuesSyncOptions(argv) {
|
|
20
|
+
const result = {};
|
|
21
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
22
|
+
const name = argv[i]?.replace(/^--/, "");
|
|
23
|
+
const value = argv[i + 1];
|
|
24
|
+
if (!name ||
|
|
25
|
+
!["repo", "project", "server", "token-env", "state", "limit"].includes(name) ||
|
|
26
|
+
!value ||
|
|
27
|
+
value.startsWith("--"))
|
|
28
|
+
throw new Error("Invalid arguments; use [--state all|open] [--limit N] [--repo PATH --project UUID --server URL --token-env ENV_NAME]");
|
|
29
|
+
result[name] = value;
|
|
30
|
+
}
|
|
31
|
+
const state = result.state ?? "all";
|
|
32
|
+
if (state !== "all" && state !== "open")
|
|
33
|
+
throw new Error("--state must be all|open");
|
|
34
|
+
const limit = result.limit === undefined ? undefined : Number(result.limit);
|
|
35
|
+
if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
|
|
36
|
+
throw new Error("--limit must be a positive integer");
|
|
37
|
+
return { ...result, state, ...(limit === undefined ? {} : { limit }) };
|
|
38
|
+
}
|
|
39
|
+
const NO_ACCESS = "Cannot read GitHub issues: install and authenticate the gh CLI (gh auth login) or set GITHUB_TOKEN";
|
|
40
|
+
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
41
|
+
export const githubSource = async ({ owner, name, state, limit }) => {
|
|
42
|
+
const path = `repos/${owner}/${name}/issues?state=${state}&per_page=100`;
|
|
43
|
+
try {
|
|
44
|
+
const { stdout } = await run("gh", ["api", "--paginate", path, "--jq", ".[]"], {
|
|
45
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
46
|
+
});
|
|
47
|
+
return stdout
|
|
48
|
+
.split("\n")
|
|
49
|
+
.filter(Boolean)
|
|
50
|
+
.map((line) => JSON.parse(line));
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
const token = process.env.GITHUB_TOKEN?.trim();
|
|
54
|
+
if (!token)
|
|
55
|
+
throw new Error(NO_ACCESS, { cause: error });
|
|
56
|
+
return fetchIssues(path, token, limit);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
async function fetchIssues(path, token, limit) {
|
|
60
|
+
const issues = [];
|
|
61
|
+
for (let page = 1;; page++) {
|
|
62
|
+
const response = await fetch(`https://api.github.com/${path}&page=${String(page)}`, {
|
|
63
|
+
headers: {
|
|
64
|
+
authorization: `Bearer ${token}`,
|
|
65
|
+
accept: "application/vnd.github+json",
|
|
66
|
+
"user-agent": "cboard",
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
if (!response.ok)
|
|
70
|
+
throw new Error(`GitHub API ${String(response.status)} for ${path}`);
|
|
71
|
+
const batch = (await response.json());
|
|
72
|
+
issues.push(...batch);
|
|
73
|
+
// Pull requests are dropped later, so the limit is applied there, not here.
|
|
74
|
+
if (batch.length < 100 || (limit !== undefined && issues.length >= limit * 4))
|
|
75
|
+
return issues;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function snapshotOf(issues, namespace, repoKey) {
|
|
79
|
+
const nodes = [];
|
|
80
|
+
const edges = [];
|
|
81
|
+
for (const i of issues) {
|
|
82
|
+
const clientKey = `${namespace}:#${String(i.number)}`;
|
|
83
|
+
// Issue nodes cite the issue URL (the graph's url provenance), not a repository commit.
|
|
84
|
+
const provenance = [{ kind: "url", ref: i.html_url }];
|
|
85
|
+
nodes.push({
|
|
86
|
+
clientKey,
|
|
87
|
+
namespace,
|
|
88
|
+
type: "open_issue",
|
|
89
|
+
title: `#${String(i.number)} ${i.title}`.slice(0, 300),
|
|
90
|
+
body: (i.body ?? "").trim().slice(0, BODY_MAX),
|
|
91
|
+
status: i.state === "open" ? "open" : "resolved",
|
|
92
|
+
properties: {
|
|
93
|
+
url: i.html_url,
|
|
94
|
+
labels: (i.labels ?? [])
|
|
95
|
+
.map((l) => (typeof l === "string" ? l : l.name))
|
|
96
|
+
.filter((l) => !!l),
|
|
97
|
+
},
|
|
98
|
+
provenance,
|
|
99
|
+
derivation: "extracted",
|
|
100
|
+
});
|
|
101
|
+
edges.push({
|
|
102
|
+
type: "part_of",
|
|
103
|
+
from: clientKey,
|
|
104
|
+
to: repoKey,
|
|
105
|
+
provenance,
|
|
106
|
+
derivation: "extracted",
|
|
107
|
+
properties: {},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return { nodes, edges };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
|
|
114
|
+
* list is partial (--state open or --limit) unseen issues are kept, not superseded.
|
|
115
|
+
*/
|
|
116
|
+
export async function runIssuesSync(api, identity, source, options) {
|
|
117
|
+
const { owner, name } = parseGithubRemote(identity.repo);
|
|
118
|
+
const repoKey = `${identity.namespace}:.`;
|
|
119
|
+
const repoNode = (await api.all({ namespace: identity.namespace, types: "repository" })).nodes.find((n) => n.clientKey === repoKey && n.lifecycle === "active");
|
|
120
|
+
if (!repoNode)
|
|
121
|
+
throw new Error("The repository node is missing from the graph; run `cboard sync` first");
|
|
122
|
+
const namespace = `issues:${createHash("sha256").update(identity.repo).digest("hex").slice(0, 32)}`;
|
|
123
|
+
const fetched = await source({ owner, name, state: options.state, limit: options.limit });
|
|
124
|
+
const issues = fetched
|
|
125
|
+
.filter((i) => !i.pull_request)
|
|
126
|
+
.sort((a, b) => a.number - b.number)
|
|
127
|
+
.slice(0, options.limit);
|
|
128
|
+
const snapshot = snapshotOf(issues, namespace, repoKey);
|
|
129
|
+
const complete = options.state === "all" && options.limit === undefined;
|
|
130
|
+
const result = await reconcile(api, snapshot, namespace, complete, new Map([[repoKey, repoNode.id]]));
|
|
131
|
+
return { issues: issues.length, contributions: result.contributions };
|
|
132
|
+
}
|
|
133
|
+
export async function issuesSync(argv, source = githubSource) {
|
|
134
|
+
const args = issuesSyncOptions(argv);
|
|
135
|
+
const root = resolve(args.repo ?? process.cwd());
|
|
136
|
+
const { project, token, server } = resolveSync(args, root);
|
|
137
|
+
const result = await runIssuesSync(new ContextApi(server, project, token, { heads: fileHeadStore() }), repository(root), source, { state: args.state, limit: args.limit });
|
|
138
|
+
console.log(JSON.stringify(result));
|
|
139
|
+
}
|
package/dist/wake.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const WAKE_MESSAGE = "hosted service is waking up (up to a minute)";
|
|
2
|
+
export declare const WAKE_BUDGET_MS = 90000;
|
|
3
|
+
export interface WakeOptions {
|
|
4
|
+
budgetMs?: number;
|
|
5
|
+
attemptMs?: number;
|
|
6
|
+
onWake?: (message: string) => void;
|
|
7
|
+
sleep?: (ms: number) => Promise<void>;
|
|
8
|
+
now?: () => number;
|
|
9
|
+
}
|
|
10
|
+
/** A failure that may be the service waking: a network error, a timeout or a 5xx. */
|
|
11
|
+
export declare function isTransient(error: unknown): boolean;
|
|
12
|
+
/** Runs `attempt` until it succeeds, fails for good, or the budget is spent (backoff 1 s to 10 s). */
|
|
13
|
+
export declare function retryWake<T>(attempt: (timeoutMs: number) => Promise<T>, { budgetMs, attemptMs, onWake, sleep, now, }?: WakeOptions): Promise<T>;
|
package/dist/wake.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Cold-start wait for the code-sync client. Mirrors scripts/cboard-kit/wait.js (the kit is plain
|
|
2
|
+
// JS that ships separately and cannot be imported here); keep the two in step.
|
|
3
|
+
export const WAKE_MESSAGE = "hosted service is waking up (up to a minute)";
|
|
4
|
+
export const WAKE_BUDGET_MS = 90_000;
|
|
5
|
+
/** A failure that may be the service waking: a network error, a timeout or a 5xx. */
|
|
6
|
+
export function isTransient(error) {
|
|
7
|
+
const status = error?.status;
|
|
8
|
+
if (typeof status === "number")
|
|
9
|
+
return status >= 500;
|
|
10
|
+
return error instanceof TypeError || error?.name === "TimeoutError";
|
|
11
|
+
}
|
|
12
|
+
/** Runs `attempt` until it succeeds, fails for good, or the budget is spent (backoff 1 s to 10 s). */
|
|
13
|
+
export async function retryWake(attempt, { budgetMs = WAKE_BUDGET_MS, attemptMs = 30_000, onWake = (m) => void process.stderr.write(`cboard: ${m}\n`), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now, } = {}) {
|
|
14
|
+
const start = now();
|
|
15
|
+
let delay = 1000;
|
|
16
|
+
let woke = false;
|
|
17
|
+
for (;;) {
|
|
18
|
+
const left = budgetMs - (now() - start);
|
|
19
|
+
try {
|
|
20
|
+
return await attempt(Math.max(1000, Math.min(attemptMs, left)));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (!isTransient(error) || budgetMs - (now() - start) <= delay)
|
|
24
|
+
throw error;
|
|
25
|
+
if (!woke) {
|
|
26
|
+
woke = true;
|
|
27
|
+
onWake(WAKE_MESSAGE);
|
|
28
|
+
}
|
|
29
|
+
await sleep(delay);
|
|
30
|
+
delay = Math.min(delay * 2, 10_000);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|