@codyn06/cboard 0.3.4 → 0.3.6
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 +2 -2
- package/dist/api.d.ts +1 -5
- package/dist/api.js +20 -19
- package/dist/cboard.js +7 -1
- package/dist/issues.d.ts +31 -3
- package/dist/issues.js +200 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ npx @codyn06/cboard connect # browser login and project
|
|
|
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
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
|
|
14
|
+
npx @codyn06/cboard issues sync # mirror GitHub issues, link closed ones to the files their PRs changed
|
|
15
15
|
npx @codyn06/cboard docs sync # import README, docs/ and ADRs into the graph
|
|
16
16
|
```
|
|
17
17
|
|
|
@@ -61,7 +61,7 @@ Runtime: web-tree-sitter **0.27.1** (MIT), with @vscode/tree-sitter-wasm **0.3.1
|
|
|
61
61
|
|
|
62
62
|
Repository, modules/directories, files, symbols, manifest configs and dependencies carry repository/commit/path/line provenance. Symbol bodies contain bounded source excerpts, with explicit truncation metadata; no semantic/model summaries are generated. Relative file imports are extracted. Same-file lexical calls, type references and implements relationships are deterministic name heuristics labelled `inferred`; unresolved calls, package aliases, CommonJS and dynamic imports are omitted.
|
|
63
63
|
|
|
64
|
-
Stable repository-scoped keys reconcile against server state. A same-commit rerun creates no revisions. New commits update source metadata; absent nodes and owned relationships are superseded, never deleted. Overload implementations are traversed. Node and edge pagination must complete before reconciliation.
|
|
64
|
+
Stable repository-scoped keys reconcile against server state. A same-commit rerun creates no revisions. New commits update source metadata; absent nodes and owned relationships are superseded, never deleted. Overload implementations are traversed. Node and edge pagination must complete before reconciliation. Node batches are capped at 50 items and relationship batches at 200. Both are cut at 180 KB to leave room for server defaults and are atomic; a batch that fails with a server error or statement timeout is retried once as two half-size batches, after the server confirms it never recorded the original; successful earlier batches remain if a later batch conflicts. A rerun resumes reconciliation without trusting local receipt state. Reads use the `/v1/graph` HTTP routes; batches are submitted through the `/mcp` `submit_contribution` tool as base64 (`contribution_b64`), because the CDN firewall in front of the hosted service blocks some code-sync payloads (source excerpts that look like attacks). A server without `contribution_b64` support rejects these calls, so release the server before syncing with a newer client.
|
|
65
65
|
|
|
66
66
|
The local marker in Git metadata (`--state PATH` overrides) records the last successful snapshot without storing a token. The server remains authoritative. Scripts/migrate-cboard.ts reuses the reviewed pure Phase A parser, reading committed documentation blobs and translating acceptance rows and scoped amendments to the approved vocabulary. It never imports prototype application/server code or writes a store directly.
|
|
67
67
|
|
package/dist/api.d.ts
CHANGED
|
@@ -55,12 +55,8 @@ export declare class ContextApi {
|
|
|
55
55
|
*/
|
|
56
56
|
edgeHeads(namespace: string, fresh?: boolean): Promise<Result["edges"]>;
|
|
57
57
|
}
|
|
58
|
-
/**
|
|
59
|
-
* Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
|
|
60
|
-
* grows roughly quadratically with batch size; 50 stays under the 5 s statement timeout (#43).
|
|
61
|
-
*/
|
|
62
58
|
export declare const BATCH_ITEMS = 50;
|
|
63
|
-
export declare function chunks<T>(items: T[], make: (items: T[]) => Contribution): T[][];
|
|
59
|
+
export declare function chunks<T>(items: T[], make: (items: T[]) => Contribution, maxItems?: number): T[][];
|
|
64
60
|
/**
|
|
65
61
|
* Submits one batch. On a server error or statement timeout the batch is retried once as two
|
|
66
62
|
* halves, but only after the server confirms it never recorded the original contribution. A
|
package/dist/api.js
CHANGED
|
@@ -213,25 +213,17 @@ export class ContextApi {
|
|
|
213
213
|
return read.rows;
|
|
214
214
|
}
|
|
215
215
|
}
|
|
216
|
-
|
|
217
|
-
* Batch sizing: the server accepts 200 items and 200,000 bytes per contribution. The item cap
|
|
218
|
-
* stays at 50 (below) because server cost per contribution is roughly quadratic in items; raising
|
|
219
|
-
* it risks the statement timeout for little gain. Write requests scale as nodes/50, reads as pages.
|
|
220
|
-
* The server allows 200,000 bytes, measured after the MCP tool schema fills defaults (aliases,
|
|
221
|
-
* namespace, properties…). Batches leave 20,000 bytes for those.
|
|
222
|
-
*/
|
|
216
|
+
// Leave room for defaults filled by the server before it checks the 200,000-byte limit.
|
|
223
217
|
const BATCH_BYTES = 180_000;
|
|
224
|
-
|
|
225
|
-
* Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
|
|
226
|
-
* grows roughly quadratically with batch size; 50 stays under the 5 s statement timeout (#43).
|
|
227
|
-
*/
|
|
218
|
+
// Node writes run pairwise similarity checks (#43); relationship-only writes skip those checks.
|
|
228
219
|
export const BATCH_ITEMS = 50;
|
|
229
|
-
|
|
220
|
+
const EDGE_BATCH_ITEMS = 200;
|
|
221
|
+
export function chunks(items, make, maxItems = BATCH_ITEMS) {
|
|
230
222
|
const result = [];
|
|
231
223
|
let current = [];
|
|
232
224
|
for (const item of items) {
|
|
233
225
|
const candidate = [...current, item];
|
|
234
|
-
if (candidate.length >
|
|
226
|
+
if (candidate.length > maxItems ||
|
|
235
227
|
Buffer.byteLength(JSON.stringify(make(candidate))) > BATCH_BYTES) {
|
|
236
228
|
if (!current.length)
|
|
237
229
|
throw new Error("Single contribution item exceeds 200KB");
|
|
@@ -309,8 +301,9 @@ const edgeKey = (e) => stable([
|
|
|
309
301
|
e.properties.contextNamespace ?? null,
|
|
310
302
|
e.type === "amends" ? (e.properties.scope ?? null) : null,
|
|
311
303
|
]);
|
|
312
|
-
/** Up to this many absent keys
|
|
304
|
+
/** Up to this many absent keys get individual lookups; more use the project-wide types scan. */
|
|
313
305
|
const KEY_LOOKUP_MAX = 50;
|
|
306
|
+
const KEY_LOOKUP_CONCURRENCY = 5;
|
|
314
307
|
/**
|
|
315
308
|
* The head cache is a mirror refreshed from the server by revision, and the server stays
|
|
316
309
|
* authoritative: a doubtful cache is dropped for a full read, never trusted.
|
|
@@ -331,9 +324,16 @@ anchors = new Map()) {
|
|
|
331
324
|
if (absent.has(n.clientKey))
|
|
332
325
|
candidates.set(n.clientKey, [...(candidates.get(n.clientKey) ?? []), n]);
|
|
333
326
|
};
|
|
334
|
-
if (absent.size <= KEY_LOOKUP_MAX)
|
|
335
|
-
|
|
336
|
-
|
|
327
|
+
if (absent.size <= KEY_LOOKUP_MAX) {
|
|
328
|
+
const keys = [...absent];
|
|
329
|
+
for (let start = 0; start < keys.length; start += KEY_LOOKUP_CONCURRENCY) {
|
|
330
|
+
const results = await Promise.all(keys
|
|
331
|
+
.slice(start, start + KEY_LOOKUP_CONCURRENCY)
|
|
332
|
+
.map((client_key) => api.all({ client_key, include_inactive: "true" })));
|
|
333
|
+
for (const { nodes } of results)
|
|
334
|
+
nodes.forEach(offer);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
337
|
else {
|
|
338
338
|
const types = [...new Set(snapshot.nodes.map((n) => n.type))].join(",");
|
|
339
339
|
(await api.all({ types, include_inactive: "true" })).nodes.forEach(offer);
|
|
@@ -446,7 +446,8 @@ anchors = new Map()) {
|
|
|
446
446
|
const active = new Set([...currentEdges.values()].filter((e) => e.lifecycle === "active").map(edgeKey));
|
|
447
447
|
const wanted = new Set(edges.map(edgeKey));
|
|
448
448
|
const missing = edges.filter((e) => !active.has(edgeKey(e)));
|
|
449
|
-
|
|
449
|
+
// The server serializes contributions for a project. Keep dependent writes and retries ordered.
|
|
450
|
+
for (const batch of chunks(missing, (edges) => ({ ...empty(), edges }), EDGE_BATCH_ITEMS))
|
|
450
451
|
contributions += (await submitBatch(api, batch, (edges) => ({ ...empty(), edges }))).length;
|
|
451
452
|
const activeByKey = new Map();
|
|
452
453
|
const duplicateIds = new Set();
|
|
@@ -489,7 +490,7 @@ anchors = new Map()) {
|
|
|
489
490
|
: "Absent from repository snapshot",
|
|
490
491
|
}))
|
|
491
492
|
.concat(updated);
|
|
492
|
-
for (const batch of chunks(edgeRevisions, (edgeRevisions) => ({ ...empty(), edgeRevisions })))
|
|
493
|
+
for (const batch of chunks(edgeRevisions, (edgeRevisions) => ({ ...empty(), edgeRevisions }), EDGE_BATCH_ITEMS))
|
|
493
494
|
contributions += (await submitBatch(api, batch, (edgeRevisions) => ({ ...empty(), edgeRevisions }))).length;
|
|
494
495
|
return {
|
|
495
496
|
contributions,
|
package/dist/cboard.js
CHANGED
|
@@ -43,13 +43,19 @@ const SYNC_HELP = `Usage: cboard sync [--repo PATH] [--project UUID] [--server U
|
|
|
43
43
|
|
|
44
44
|
Project, server and token come from .cboard.json and the repo token file when the flags are omitted.
|
|
45
45
|
`;
|
|
46
|
-
const ISSUES_HELP = `Usage: cboard issues sync [--state all|open] [--limit N] [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
|
|
46
|
+
const ISSUES_HELP = `Usage: cboard issues sync [--state all|open] [--limit N] [--link-code on|off] [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
|
|
47
47
|
|
|
48
48
|
Mirrors the origin repository's GitHub issues (not pull requests) as open_issue nodes linked to the
|
|
49
49
|
repository node; run "cboard sync" first. Reads through "gh api", or GITHUB_TOKEN when gh is
|
|
50
50
|
unavailable. --state open or --limit mirrors a partial list and keeps issues it did not see.
|
|
51
51
|
Closed issues become resolved, wontfix (label wontfix or not_planned) or moot (label duplicate/invalid);
|
|
52
52
|
bodies cut at 4000 characters set bodyTruncated.
|
|
53
|
+
Closed issues also get "implements" edges to the files (in the code snapshot) changed by the merged pull
|
|
54
|
+
requests that closed them, at most 50 files and skipping pull requests that changed more; --link-code off
|
|
55
|
+
disables this. The pull request lookup costs one request per closed issue changed since the last run,
|
|
56
|
+
and reads only the first 5 pull requests GitHub lists as closing the issue. A failed lookup keeps that
|
|
57
|
+
issue's existing links. Partial syncs (--state open, --limit) do not retire stale links; the next full
|
|
58
|
+
sync does.
|
|
53
59
|
`;
|
|
54
60
|
const DOCS_HELP = `Usage: cboard docs sync [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
|
|
55
61
|
|
package/dist/issues.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ContextApi } from "./api.js";
|
|
2
|
+
import { type HeadStore } from "./cache.js";
|
|
2
3
|
export interface GithubIssue {
|
|
3
4
|
number: number;
|
|
4
5
|
title: string;
|
|
@@ -10,6 +11,8 @@ export interface GithubIssue {
|
|
|
10
11
|
})[];
|
|
11
12
|
state_reason?: string | null;
|
|
12
13
|
pull_request?: unknown;
|
|
14
|
+
updated_at?: string | null;
|
|
15
|
+
closed_at?: string | null;
|
|
13
16
|
}
|
|
14
17
|
export interface IssueRequest {
|
|
15
18
|
owner: string;
|
|
@@ -18,21 +21,43 @@ export interface IssueRequest {
|
|
|
18
21
|
limit?: number | undefined;
|
|
19
22
|
}
|
|
20
23
|
export type IssueSource = (request: IssueRequest) => Promise<GithubIssue[]>;
|
|
24
|
+
/** A pull request that closed an issue, with the paths it changed (at most `fileLimit` read). */
|
|
25
|
+
export interface ClosingPr {
|
|
26
|
+
number: number;
|
|
27
|
+
merged: boolean;
|
|
28
|
+
changedFiles: number;
|
|
29
|
+
files: string[];
|
|
30
|
+
}
|
|
31
|
+
export interface ClosingPrRequest {
|
|
32
|
+
owner: string;
|
|
33
|
+
name: string;
|
|
34
|
+
issue: number;
|
|
35
|
+
fileLimit: number;
|
|
36
|
+
}
|
|
37
|
+
export type ClosingPrSource = (request: ClosingPrRequest) => Promise<ClosingPr[]>;
|
|
21
38
|
export interface IssuesOptions {
|
|
22
39
|
state: "all" | "open";
|
|
23
40
|
limit?: number | undefined;
|
|
41
|
+
/** false (--link-code off) skips linking closed issues to the files their merged PRs changed. */
|
|
42
|
+
linkCode?: boolean | undefined;
|
|
24
43
|
}
|
|
44
|
+
/** Most files one issue is linked to; a PR that changed more is skipped as noise (#97). */
|
|
45
|
+
export declare const LINK_FILE_CAP = 50;
|
|
25
46
|
/** owner/name from an https or ssh GitHub remote URL. */
|
|
26
47
|
export declare function parseGithubRemote(remote: string): {
|
|
27
48
|
owner: string;
|
|
28
49
|
name: string;
|
|
29
50
|
};
|
|
30
|
-
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
51
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N, --link-code on|off. */
|
|
31
52
|
export declare function issuesSyncOptions(argv: string[]): Record<string, string> & IssuesOptions;
|
|
32
53
|
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
33
54
|
export declare const githubSource: IssueSource;
|
|
55
|
+
/** One GraphQL request per issue; gh api first, GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
56
|
+
export declare const githubClosingPrs: ClosingPrSource;
|
|
34
57
|
/** Stable namespace of the issue mirror for a repository (also how docs sync finds issue nodes). */
|
|
35
58
|
export declare const issuesNamespace: (repo: string) => string;
|
|
59
|
+
/** Namespace that owns the issue -> file edges, apart from the issues' so neither sync retires the other's edges. */
|
|
60
|
+
export declare const issueLinksNamespace: (repo: string) => string;
|
|
36
61
|
/**
|
|
37
62
|
* open -> open. Closed: label wontfix or state_reason not_planned -> wontfix; label duplicate or
|
|
38
63
|
* invalid (or state_reason duplicate) -> moot; otherwise resolved. A wontfix label wins over
|
|
@@ -46,8 +71,11 @@ export declare function issueStatus(i: GithubIssue): string;
|
|
|
46
71
|
export declare function runIssuesSync(api: ContextApi, identity: {
|
|
47
72
|
repo: string;
|
|
48
73
|
namespace: string;
|
|
49
|
-
}, source: IssueSource, options: IssuesOptions
|
|
74
|
+
}, source: IssueSource, options: IssuesOptions, links?: {
|
|
75
|
+
source: ClosingPrSource;
|
|
76
|
+
store?: HeadStore | undefined;
|
|
77
|
+
}): Promise<{
|
|
50
78
|
issues: number;
|
|
51
79
|
contributions: number;
|
|
52
80
|
}>;
|
|
53
|
-
export declare function issuesSync(argv: string[], source?: IssueSource): Promise<void>;
|
|
81
|
+
export declare function issuesSync(argv: string[], source?: IssueSource, closing?: ClosingPrSource): Promise<void>;
|
package/dist/issues.js
CHANGED
|
@@ -8,6 +8,8 @@ import { resolveSync } from "./cli.js";
|
|
|
8
8
|
import { repository } from "./extract.js";
|
|
9
9
|
const run = promisify(execFile);
|
|
10
10
|
const BODY_MAX = 4000;
|
|
11
|
+
/** Most files one issue is linked to; a PR that changed more is skipped as noise (#97). */
|
|
12
|
+
export const LINK_FILE_CAP = 50;
|
|
11
13
|
/** owner/name from an https or ssh GitHub remote URL. */
|
|
12
14
|
export function parseGithubRemote(remote) {
|
|
13
15
|
const match = /github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(remote);
|
|
@@ -15,17 +17,17 @@ export function parseGithubRemote(remote) {
|
|
|
15
17
|
throw new Error(`The origin remote is not a GitHub repository: ${remote || "(none)"}`);
|
|
16
18
|
return { owner: match[1], name: match[2] };
|
|
17
19
|
}
|
|
18
|
-
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
20
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N, --link-code on|off. */
|
|
19
21
|
export function issuesSyncOptions(argv) {
|
|
20
22
|
const result = {};
|
|
21
23
|
for (let i = 0; i < argv.length; i += 2) {
|
|
22
24
|
const name = argv[i]?.replace(/^--/, "");
|
|
23
25
|
const value = argv[i + 1];
|
|
24
26
|
if (!name ||
|
|
25
|
-
!["repo", "project", "server", "token-env", "state", "limit"].includes(name) ||
|
|
27
|
+
!["repo", "project", "server", "token-env", "state", "limit", "link-code"].includes(name) ||
|
|
26
28
|
!value ||
|
|
27
29
|
value.startsWith("--"))
|
|
28
|
-
throw new Error("Invalid arguments; use [--state all|open] [--limit N] [--repo PATH --project UUID --server URL --token-env ENV_NAME]");
|
|
30
|
+
throw new Error("Invalid arguments; use [--state all|open] [--limit N] [--link-code on|off] [--repo PATH --project UUID --server URL --token-env ENV_NAME]");
|
|
29
31
|
result[name] = value;
|
|
30
32
|
}
|
|
31
33
|
const state = result.state ?? "all";
|
|
@@ -34,7 +36,15 @@ export function issuesSyncOptions(argv) {
|
|
|
34
36
|
const limit = result.limit === undefined ? undefined : Number(result.limit);
|
|
35
37
|
if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
|
|
36
38
|
throw new Error("--limit must be a positive integer");
|
|
37
|
-
|
|
39
|
+
const link = result["link-code"] ?? "on";
|
|
40
|
+
if (link !== "on" && link !== "off")
|
|
41
|
+
throw new Error("--link-code must be on|off");
|
|
42
|
+
return {
|
|
43
|
+
...result,
|
|
44
|
+
state,
|
|
45
|
+
linkCode: link === "on",
|
|
46
|
+
...(limit === undefined ? {} : { limit }),
|
|
47
|
+
};
|
|
38
48
|
}
|
|
39
49
|
const NO_ACCESS = "Cannot read GitHub issues: install and authenticate the gh CLI (gh auth login) or set GITHUB_TOKEN";
|
|
40
50
|
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
@@ -75,8 +85,59 @@ async function fetchIssues(path, token, limit) {
|
|
|
75
85
|
return issues;
|
|
76
86
|
}
|
|
77
87
|
}
|
|
88
|
+
const CLOSING_PRS = `query($owner:String!,$name:String!,$n:Int!,$files:Int!){repository(owner:$owner,name:$name){issue(number:$n){closedByPullRequestsReferences(first:5){nodes{number merged changedFiles files(first:$files){nodes{path}}}}}}}`;
|
|
89
|
+
const closingPrs = (data) => (data.data?.repository?.issue?.closedByPullRequestsReferences?.nodes ?? [])
|
|
90
|
+
.filter((p) => !!p)
|
|
91
|
+
.map((p) => ({
|
|
92
|
+
number: p.number,
|
|
93
|
+
merged: p.merged,
|
|
94
|
+
changedFiles: p.changedFiles,
|
|
95
|
+
files: (p.files?.nodes ?? []).map((f) => f.path),
|
|
96
|
+
}));
|
|
97
|
+
/** One GraphQL request per issue; gh api first, GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
98
|
+
export const githubClosingPrs = async ({ owner, name, issue, fileLimit }) => {
|
|
99
|
+
try {
|
|
100
|
+
const { stdout } = await run("gh", [
|
|
101
|
+
"api",
|
|
102
|
+
"graphql",
|
|
103
|
+
"-f",
|
|
104
|
+
`query=${CLOSING_PRS}`,
|
|
105
|
+
"-f",
|
|
106
|
+
`owner=${owner}`,
|
|
107
|
+
"-f",
|
|
108
|
+
`name=${name}`,
|
|
109
|
+
"-F",
|
|
110
|
+
`n=${String(issue)}`,
|
|
111
|
+
"-F",
|
|
112
|
+
`files=${String(fileLimit)}`,
|
|
113
|
+
]);
|
|
114
|
+
return closingPrs(JSON.parse(stdout));
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
const token = process.env.GITHUB_TOKEN?.trim();
|
|
118
|
+
if (!token)
|
|
119
|
+
throw new Error(NO_ACCESS, { cause: error });
|
|
120
|
+
const response = await fetch("https://api.github.com/graphql", {
|
|
121
|
+
method: "POST",
|
|
122
|
+
headers: {
|
|
123
|
+
authorization: `Bearer ${token}`,
|
|
124
|
+
"content-type": "application/json",
|
|
125
|
+
"user-agent": "cboard",
|
|
126
|
+
},
|
|
127
|
+
body: JSON.stringify({
|
|
128
|
+
query: CLOSING_PRS,
|
|
129
|
+
variables: { owner, name, n: issue, files: fileLimit },
|
|
130
|
+
}),
|
|
131
|
+
});
|
|
132
|
+
if (!response.ok)
|
|
133
|
+
throw new Error(`GitHub API ${String(response.status)} for graphql`, { cause: error });
|
|
134
|
+
return closingPrs(await response.json());
|
|
135
|
+
}
|
|
136
|
+
};
|
|
78
137
|
/** Stable namespace of the issue mirror for a repository (also how docs sync finds issue nodes). */
|
|
79
138
|
export const issuesNamespace = (repo) => `issues:${createHash("sha256").update(repo).digest("hex").slice(0, 32)}`;
|
|
139
|
+
/** Namespace that owns the issue -> file edges, apart from the issues' so neither sync retires the other's edges. */
|
|
140
|
+
export const issueLinksNamespace = (repo) => `issue-links:${createHash("sha256").update(repo).digest("hex").slice(0, 32)}`;
|
|
80
141
|
const labelNames = (i) => (i.labels ?? []).map((l) => (typeof l === "string" ? l : l.name)).filter((l) => !!l);
|
|
81
142
|
/**
|
|
82
143
|
* open -> open. Closed: label wontfix or state_reason not_planned -> wontfix; label duplicate or
|
|
@@ -131,11 +192,138 @@ function snapshotOf(issues, namespace, repoKey) {
|
|
|
131
192
|
}
|
|
132
193
|
return { nodes, edges };
|
|
133
194
|
}
|
|
195
|
+
/**
|
|
196
|
+
* Edges "issue implements file" for closed issues whose merged pull requests changed files that
|
|
197
|
+
* exist in the code snapshot. Files per issue are cached by the issue's updated_at stamp, so an
|
|
198
|
+
* unchanged issue costs no request. Reconciled in a namespace of its own: only these edges are
|
|
199
|
+
* added or retired, hand-written edges are never touched.
|
|
200
|
+
*/
|
|
201
|
+
async function linkIssuesToCode(api, identity, issues, complete, source, store, repoNode) {
|
|
202
|
+
const { owner, name } = parseGithubRemote(identity.repo);
|
|
203
|
+
const issuesNs = issuesNamespace(identity.repo);
|
|
204
|
+
const cacheKey = `issue-prs|${identity.repo}`;
|
|
205
|
+
let cache = { v: 1, issues: {} };
|
|
206
|
+
try {
|
|
207
|
+
const parsed = JSON.parse(store?.get(cacheKey) ?? "null");
|
|
208
|
+
if (parsed?.v === 1)
|
|
209
|
+
cache = parsed;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
/* unreadable cache: fetch again */
|
|
213
|
+
}
|
|
214
|
+
// A partial list (--state open, --limit) did not see every issue: keep the others' links.
|
|
215
|
+
const reopened = new Set(issues.filter((i) => i.state !== "closed").map((i) => String(i.number)));
|
|
216
|
+
const next = {
|
|
217
|
+
v: 1,
|
|
218
|
+
issues: complete
|
|
219
|
+
? {}
|
|
220
|
+
: Object.fromEntries(Object.entries(cache.issues).filter(([k]) => !reopened.has(k))),
|
|
221
|
+
};
|
|
222
|
+
let fetched = 0;
|
|
223
|
+
let failed = 0;
|
|
224
|
+
const lostKeys = new Set();
|
|
225
|
+
const closed = issues.filter((x) => x.state === "closed");
|
|
226
|
+
for (const i of closed) {
|
|
227
|
+
const key = String(i.number);
|
|
228
|
+
const stamp = i.updated_at ?? i.closed_at ?? "";
|
|
229
|
+
const hit = cache.issues[key];
|
|
230
|
+
if (hit && stamp && hit.stamp === stamp) {
|
|
231
|
+
next.issues[key] = hit;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if ((fetched + failed) % 50 === 49)
|
|
235
|
+
console.error(`linking issues to code: ${String(fetched + failed + 1)} lookups (${String(closed.length)} closed issues)`);
|
|
236
|
+
try {
|
|
237
|
+
const prs = await source({ owner, name, issue: i.number, fileLimit: LINK_FILE_CAP });
|
|
238
|
+
fetched++;
|
|
239
|
+
const files = new Set();
|
|
240
|
+
for (const pr of prs)
|
|
241
|
+
if (pr.merged && pr.changedFiles <= LINK_FILE_CAP)
|
|
242
|
+
pr.files.forEach((p) => files.add(p));
|
|
243
|
+
next.issues[key] = { stamp, files: [...files].sort() };
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
failed++;
|
|
247
|
+
if (hit)
|
|
248
|
+
next.issues[key] = hit;
|
|
249
|
+
else
|
|
250
|
+
lostKeys.add(key);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
store?.set(cacheKey, JSON.stringify(next));
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
/* an unwritable cache only costs requests next time */
|
|
258
|
+
}
|
|
259
|
+
const fileIds = new Map((await api.nodeHeads(identity.namespace)).rows
|
|
260
|
+
.filter((n) => n.type === "file" && n.lifecycle === "active")
|
|
261
|
+
.map((n) => [n.clientKey, n.id]));
|
|
262
|
+
const issueIds = new Map((await api.nodeHeads(issuesNs)).rows
|
|
263
|
+
.filter((n) => n.type === "open_issue" && n.lifecycle === "active")
|
|
264
|
+
.map((n) => [n.clientKey, n.id]));
|
|
265
|
+
const commit = repoNode.provenance[0]?.commit ?? "";
|
|
266
|
+
const anchors = new Map();
|
|
267
|
+
const edges = [];
|
|
268
|
+
for (const number of Object.keys(next.issues).map(Number)) {
|
|
269
|
+
const from = `${issuesNs}:#${String(number)}`;
|
|
270
|
+
const fromId = issueIds.get(from);
|
|
271
|
+
if (!fromId)
|
|
272
|
+
continue;
|
|
273
|
+
const present = (next.issues[String(number)]?.files ?? [])
|
|
274
|
+
.map((path) => ({ path, to: `${identity.namespace}:${path}` }))
|
|
275
|
+
.filter((f) => fileIds.has(f.to))
|
|
276
|
+
.slice(0, LINK_FILE_CAP);
|
|
277
|
+
for (const { path, to } of present) {
|
|
278
|
+
anchors.set(from, fromId);
|
|
279
|
+
anchors.set(to, fileIds.get(to) ?? "");
|
|
280
|
+
edges.push({
|
|
281
|
+
type: "implements",
|
|
282
|
+
from,
|
|
283
|
+
to,
|
|
284
|
+
provenance: [{ kind: "repo", repo: identity.repo, commit, path, startLine: 1, endLine: 1 }],
|
|
285
|
+
derivation: "inferred",
|
|
286
|
+
properties: {},
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// A failed lookup with nothing cached must not look like "no files": keep its current edges.
|
|
291
|
+
if (lostKeys.size) {
|
|
292
|
+
const fileKeys = new Map([...fileIds].map(([key, id]) => [id, key]));
|
|
293
|
+
const issueKeys = new Map([...issueIds].map(([key, id]) => [id, key]));
|
|
294
|
+
const linksNs = issueLinksNamespace(identity.repo);
|
|
295
|
+
for (const e of await api.edgeHeads(linksNs)) {
|
|
296
|
+
const from = issueKeys.get(e.from);
|
|
297
|
+
const to = fileKeys.get(e.to);
|
|
298
|
+
if (e.type !== "implements" || e.properties.contextNamespace !== linksNs || !from || !to)
|
|
299
|
+
continue;
|
|
300
|
+
if (!lostKeys.has(from.slice(from.lastIndexOf("#") + 1)))
|
|
301
|
+
continue;
|
|
302
|
+
anchors.set(from, e.from);
|
|
303
|
+
anchors.set(to, e.to);
|
|
304
|
+
edges.push({
|
|
305
|
+
type: "implements",
|
|
306
|
+
from,
|
|
307
|
+
to,
|
|
308
|
+
provenance: e.provenance,
|
|
309
|
+
derivation: e.derivation,
|
|
310
|
+
properties: {},
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const result = await reconcile(api, { nodes: [], edges }, issueLinksNamespace(identity.repo), complete, anchors);
|
|
315
|
+
return {
|
|
316
|
+
links: edges.length,
|
|
317
|
+
linkRequests: fetched,
|
|
318
|
+
linkFailures: failed,
|
|
319
|
+
linkContributions: result.contributions,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
134
322
|
/**
|
|
135
323
|
* Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
|
|
136
324
|
* list is partial (--state open or --limit) unseen issues are kept, not superseded.
|
|
137
325
|
*/
|
|
138
|
-
export async function runIssuesSync(api, identity, source, options) {
|
|
326
|
+
export async function runIssuesSync(api, identity, source, options, links) {
|
|
139
327
|
const { owner, name } = parseGithubRemote(identity.repo);
|
|
140
328
|
const repoKey = `${identity.namespace}:.`;
|
|
141
329
|
const repoNode = (await api.all({ namespace: identity.namespace, types: "repository" })).nodes.find((n) => n.clientKey === repoKey && n.lifecycle === "active");
|
|
@@ -150,12 +338,16 @@ export async function runIssuesSync(api, identity, source, options) {
|
|
|
150
338
|
const snapshot = snapshotOf(issues, namespace, repoKey);
|
|
151
339
|
const complete = options.state === "all" && options.limit === undefined;
|
|
152
340
|
const result = await reconcile(api, snapshot, namespace, complete, new Map([[repoKey, repoNode.id]]));
|
|
153
|
-
|
|
341
|
+
const linked = links && options.linkCode !== false
|
|
342
|
+
? await linkIssuesToCode(api, identity, issues, complete, links.source, links.store, repoNode)
|
|
343
|
+
: {};
|
|
344
|
+
return { issues: issues.length, contributions: result.contributions, ...linked };
|
|
154
345
|
}
|
|
155
|
-
export async function issuesSync(argv, source = githubSource) {
|
|
346
|
+
export async function issuesSync(argv, source = githubSource, closing = githubClosingPrs) {
|
|
156
347
|
const args = issuesSyncOptions(argv);
|
|
157
348
|
const root = resolve(args.repo ?? process.cwd());
|
|
158
349
|
const { project, token, server } = resolveSync(args, root);
|
|
159
|
-
const
|
|
350
|
+
const heads = fileHeadStore();
|
|
351
|
+
const result = await runIssuesSync(new ContextApi(server, project, token, { heads }), repository(root), source, { state: args.state, limit: args.limit, linkCode: args.linkCode }, { source: closing, store: heads });
|
|
160
352
|
console.log(JSON.stringify(result));
|
|
161
353
|
}
|