@codyn06/cboard 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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 into the graph
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
 
package/dist/api.d.ts CHANGED
@@ -72,7 +72,9 @@ export declare function submitBatch<T>(api: ContextApi, group: T[], make: (items
72
72
  */
73
73
  export declare function reconcile(api: ContextApi, snapshot: Snapshot, namespace: string, supersede?: boolean,
74
74
  /** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
75
- anchors?: Map<string, string>): Promise<{
75
+ anchors?: Map<string, string>,
76
+ /** Nodes outside the namespace (hand-written) the snapshot takes over, by client key; revised in place, never superseded. */
77
+ adopted?: Map<string, import("./model.js").RemoteNode>): Promise<{
76
78
  contributions: number;
77
79
  digest: string;
78
80
  }>;
package/dist/api.js CHANGED
@@ -310,10 +310,15 @@ const KEY_LOOKUP_CONCURRENCY = 5;
310
310
  */
311
311
  export async function reconcile(api, snapshot, namespace, supersede = true,
312
312
  /** Nodes outside the snapshot (other namespaces) that edges may point to, by client key. */
313
- anchors = new Map()) {
313
+ anchors = new Map(),
314
+ /** Nodes outside the namespace (hand-written) the snapshot takes over, by client key; revised in place, never superseded. */
315
+ adopted = new Map()) {
314
316
  // Active heads only: history is not re-downloaded on every sync (#145).
315
317
  const { rows: existing, steady } = await api.nodeHeads(namespace);
316
318
  const byKey = new Map(existing.map((n) => [n.clientKey, n]));
319
+ for (const [key, n] of adopted)
320
+ if (!byKey.has(key))
321
+ byKey.set(key, n);
317
322
  // Absent keys are new, superseded/withdrawn in this namespace (revived below), or legacy nodes
318
323
  // outside the namespace with the same client key. A few are looked up by key; many use one
319
324
  // project-wide scan of the snapshot's node types, so a first sync costs pages, not N requests.
package/dist/cboard.js CHANGED
@@ -43,13 +43,24 @@ 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
+ An existing active open_issue node in the default namespace that is titled "#<number> ..." (or cites that
54
+ issue's URL) is taken over, not duplicated: it is revised in place, marked with the issueMirror property, and
55
+ kept up to date and linked to code from then on. It gets the GitHub title, body and status (earlier versions
56
+ stay in the node history) and keeps its other properties. Two such nodes for one issue, or an issue whose
57
+ earlier mirror node is inactive, are skipped with a warning; a node another repository's mirror took over is left alone.
58
+ Closed issues also get "implements" edges to the files (in the code snapshot) changed by the merged pull
59
+ requests that closed them, at most 50 files and skipping pull requests that changed more; --link-code off
60
+ disables this. The pull request lookup costs one request per closed issue changed since the last run,
61
+ and reads only the first 5 pull requests GitHub lists as closing the issue. A failed lookup keeps that
62
+ issue's existing links. Partial syncs (--state open, --limit) do not retire stale links; the next full
63
+ sync does.
53
64
  `;
54
65
  const DOCS_HELP = `Usage: cboard docs sync [--repo PATH] [--project UUID] [--server URL] [--token-env NAME]
55
66
 
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): Promise<{
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
- return { ...result, state, ...(limit === undefined ? {} : { limit }) };
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
@@ -97,13 +158,90 @@ export function issueStatus(i) {
97
158
  return "moot";
98
159
  return "resolved";
99
160
  }
100
- function snapshotOf(issues, namespace, repoKey) {
161
+ const ISSUE_URL = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)\/?$/i;
162
+ /** Property that marks a hand-written node as taken over by the mirror (its own client key cannot change). */
163
+ const MIRROR_MARK = "issueMirror";
164
+ /**
165
+ * The issue number a hand-written open_issue node stands for: its "#N " title prefix (every
166
+ * hand-written issue node has one; most cite a pull request, not the issue, so the URL alone
167
+ * would miss them), else the URL of one of this repository's issues in its provenance. A node that
168
+ * cites another repository's issue is nobody's match.
169
+ */
170
+ function handWrittenNumber(n, owner, name) {
171
+ const prefix = /^#(\d+) /.exec(n.title);
172
+ if (prefix)
173
+ return Number(prefix[1]);
174
+ let fromUrl;
175
+ for (const p of n.provenance) {
176
+ const m = p.kind === "url" ? ISSUE_URL.exec(p.ref ?? "") : null;
177
+ if (!m)
178
+ continue;
179
+ const same = m[1]?.toLowerCase() === owner.toLowerCase() && m[2]?.toLowerCase() === name.toLowerCase();
180
+ if (!same)
181
+ return undefined;
182
+ fromUrl = Number(m[3]);
183
+ }
184
+ return fromUrl;
185
+ }
186
+ /**
187
+ * Hand-written active open_issue nodes (namespace "default") the mirror takes over, by its client
188
+ * key. A node it already took over (marked) wins over later look-alikes. Two candidates for one
189
+ * issue are ambiguous: that issue is returned in `skipped`, with a warning, and nothing is guessed.
190
+ */
191
+ async function findAdoptable(api, issues, namespace, repo) {
192
+ const adopted = new Map();
193
+ const skipped = new Set();
194
+ const present = new Set((await api.nodeHeads(namespace)).rows.map((n) => n.clientKey));
195
+ const missing = issues.filter((i) => !present.has(`${namespace}:#${String(i.number)}`));
196
+ if (!missing.length)
197
+ return { adopted, skipped };
198
+ const candidates = (await api.all({ types: "open_issue" })).nodes.filter((n) => n.type === "open_issue" && n.lifecycle === "active" && n.namespace === "default");
199
+ for (const i of missing) {
200
+ const key = `${namespace}:#${String(i.number)}`;
201
+ // A node another mirror (another repository in this project) took over is not ours to take back.
202
+ const matches = candidates.filter((n) => handWrittenNumber(n, repo.owner, repo.name) === i.number &&
203
+ (n.properties[MIRROR_MARK] ?? key) === key);
204
+ const owned = matches.filter((n) => n.properties[MIRROR_MARK] === key);
205
+ const pool = owned.length ? owned : matches;
206
+ if (pool.length > 1) {
207
+ skipped.add(i.number);
208
+ console.error(`#${String(i.number)}: ambiguous, ${String(pool.length)} hand-written open_issue nodes match (${pool.map((n) => n.id).join(", ")}); skipped`);
209
+ }
210
+ else if (pool[0]) {
211
+ // The server's duplicate probe also reads inactive heads: a retired mirror node with this
212
+ // title would reject the revision and fail the batch.
213
+ const retired = (await api.all({ client_key: key, include_inactive: "true" })).nodes.some((n) => n.namespace === namespace && n.lifecycle !== "active");
214
+ if (retired) {
215
+ skipped.add(i.number);
216
+ console.error(`#${String(i.number)}: the mirror's earlier node for this issue is inactive (superseded or withdrawn); not adopting ${pool[0].id}, skipped`);
217
+ }
218
+ else
219
+ adopted.set(key, pool[0]);
220
+ }
221
+ }
222
+ return { adopted, skipped };
223
+ }
224
+ /** A taken-over node keeps its own properties; the mirror's overwrite theirs (a stale truncation flag goes). */
225
+ const handProperties = (old) => {
226
+ const rest = { ...old?.properties };
227
+ delete rest.bodyTruncated;
228
+ return rest;
229
+ };
230
+ function snapshotOf(issues, namespace, repoKey, adopted) {
101
231
  const nodes = [];
102
232
  const edges = [];
103
233
  for (const i of issues) {
104
234
  const clientKey = `${namespace}:#${String(i.number)}`;
105
235
  // Issue nodes cite the issue URL (the graph's url provenance), not a repository commit.
106
- const provenance = [{ kind: "url", ref: i.html_url }];
236
+ const url = { kind: "url", ref: i.html_url };
237
+ const old = adopted.get(clientKey);
238
+ // A taken-over node keeps its own evidence and gains the issue URL.
239
+ const own = (old?.provenance ?? []);
240
+ const provenance = (old
241
+ ? own.some((p) => p.kind === "url" && p.ref === url.ref)
242
+ ? own
243
+ : [...own, url]
244
+ : [url]);
107
245
  const full = (i.body ?? "").trim();
108
246
  nodes.push({
109
247
  clientKey,
@@ -113,8 +251,10 @@ function snapshotOf(issues, namespace, repoKey) {
113
251
  body: full.slice(0, BODY_MAX),
114
252
  status: issueStatus(i),
115
253
  properties: {
254
+ ...handProperties(old),
116
255
  url: i.html_url,
117
256
  labels: labelNames(i),
257
+ ...(old ? { [MIRROR_MARK]: clientKey } : {}),
118
258
  ...(full.length > BODY_MAX ? { bodyTruncated: true } : {}),
119
259
  },
120
260
  provenance,
@@ -124,18 +264,147 @@ function snapshotOf(issues, namespace, repoKey) {
124
264
  type: "part_of",
125
265
  from: clientKey,
126
266
  to: repoKey,
127
- provenance,
267
+ provenance: [url],
128
268
  derivation: "extracted",
129
269
  properties: {},
130
270
  });
131
271
  }
132
272
  return { nodes, edges };
133
273
  }
274
+ /**
275
+ * Edges "issue implements file" for closed issues whose merged pull requests changed files that
276
+ * exist in the code snapshot. Files per issue are cached by the issue's updated_at stamp, so an
277
+ * unchanged issue costs no request. Reconciled in a namespace of its own: only these edges are
278
+ * added or retired, hand-written edges are never touched.
279
+ */
280
+ async function linkIssuesToCode(api, identity, issues, complete, source, store, repoNode, adopted) {
281
+ const { owner, name } = parseGithubRemote(identity.repo);
282
+ const issuesNs = issuesNamespace(identity.repo);
283
+ const cacheKey = `issue-prs|${identity.repo}`;
284
+ let cache = { v: 1, issues: {} };
285
+ try {
286
+ const parsed = JSON.parse(store?.get(cacheKey) ?? "null");
287
+ if (parsed?.v === 1)
288
+ cache = parsed;
289
+ }
290
+ catch {
291
+ /* unreadable cache: fetch again */
292
+ }
293
+ // A partial list (--state open, --limit) did not see every issue: keep the others' links.
294
+ const reopened = new Set(issues.filter((i) => i.state !== "closed").map((i) => String(i.number)));
295
+ const next = {
296
+ v: 1,
297
+ issues: complete
298
+ ? {}
299
+ : Object.fromEntries(Object.entries(cache.issues).filter(([k]) => !reopened.has(k))),
300
+ };
301
+ let fetched = 0;
302
+ let failed = 0;
303
+ const lostKeys = new Set();
304
+ const closed = issues.filter((x) => x.state === "closed");
305
+ for (const i of closed) {
306
+ const key = String(i.number);
307
+ const stamp = i.updated_at ?? i.closed_at ?? "";
308
+ const hit = cache.issues[key];
309
+ if (hit && stamp && hit.stamp === stamp) {
310
+ next.issues[key] = hit;
311
+ continue;
312
+ }
313
+ if ((fetched + failed) % 50 === 49)
314
+ console.error(`linking issues to code: ${String(fetched + failed + 1)} lookups (${String(closed.length)} closed issues)`);
315
+ try {
316
+ const prs = await source({ owner, name, issue: i.number, fileLimit: LINK_FILE_CAP });
317
+ fetched++;
318
+ const files = new Set();
319
+ for (const pr of prs)
320
+ if (pr.merged && pr.changedFiles <= LINK_FILE_CAP)
321
+ pr.files.forEach((p) => files.add(p));
322
+ next.issues[key] = { stamp, files: [...files].sort() };
323
+ }
324
+ catch {
325
+ failed++;
326
+ if (hit)
327
+ next.issues[key] = hit;
328
+ else
329
+ lostKeys.add(key);
330
+ }
331
+ }
332
+ try {
333
+ store?.set(cacheKey, JSON.stringify(next));
334
+ }
335
+ catch {
336
+ /* an unwritable cache only costs requests next time */
337
+ }
338
+ const fileIds = new Map((await api.nodeHeads(identity.namespace)).rows
339
+ .filter((n) => n.type === "file" && n.lifecycle === "active")
340
+ .map((n) => [n.clientKey, n.id]));
341
+ const issueIds = new Map((await api.nodeHeads(issuesNs)).rows
342
+ .filter((n) => n.type === "open_issue" && n.lifecycle === "active")
343
+ .map((n) => [n.clientKey, n.id]));
344
+ for (const [key, n] of adopted)
345
+ issueIds.set(key, n.id);
346
+ const commit = repoNode.provenance[0]?.commit ?? "";
347
+ const anchors = new Map();
348
+ const edges = [];
349
+ for (const number of Object.keys(next.issues).map(Number)) {
350
+ const from = `${issuesNs}:#${String(number)}`;
351
+ const fromId = issueIds.get(from);
352
+ if (!fromId)
353
+ continue;
354
+ const present = (next.issues[String(number)]?.files ?? [])
355
+ .map((path) => ({ path, to: `${identity.namespace}:${path}` }))
356
+ .filter((f) => fileIds.has(f.to))
357
+ .slice(0, LINK_FILE_CAP);
358
+ for (const { path, to } of present) {
359
+ anchors.set(from, fromId);
360
+ anchors.set(to, fileIds.get(to) ?? "");
361
+ edges.push({
362
+ type: "implements",
363
+ from,
364
+ to,
365
+ provenance: [{ kind: "repo", repo: identity.repo, commit, path, startLine: 1, endLine: 1 }],
366
+ derivation: "inferred",
367
+ properties: {},
368
+ });
369
+ }
370
+ }
371
+ // A failed lookup with nothing cached must not look like "no files": keep its current edges.
372
+ if (lostKeys.size) {
373
+ const fileKeys = new Map([...fileIds].map(([key, id]) => [id, key]));
374
+ const issueKeys = new Map([...issueIds].map(([key, id]) => [id, key]));
375
+ const linksNs = issueLinksNamespace(identity.repo);
376
+ for (const e of await api.edgeHeads(linksNs)) {
377
+ const from = issueKeys.get(e.from);
378
+ const to = fileKeys.get(e.to);
379
+ if (e.type !== "implements" || e.properties.contextNamespace !== linksNs || !from || !to)
380
+ continue;
381
+ if (!lostKeys.has(from.slice(from.lastIndexOf("#") + 1)))
382
+ continue;
383
+ anchors.set(from, e.from);
384
+ anchors.set(to, e.to);
385
+ edges.push({
386
+ type: "implements",
387
+ from,
388
+ to,
389
+ provenance: e.provenance,
390
+ derivation: e.derivation,
391
+ properties: {},
392
+ });
393
+ }
394
+ }
395
+ const result = await reconcile(api, { nodes: [], edges }, issueLinksNamespace(identity.repo), complete, anchors);
396
+ return {
397
+ links: edges.length,
398
+ linkRequests: fetched,
399
+ linkFailures: failed,
400
+ linkContributions: result.contributions,
401
+ };
402
+ }
134
403
  /**
135
404
  * Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
136
405
  * list is partial (--state open or --limit) unseen issues are kept, not superseded.
137
406
  */
138
- export async function runIssuesSync(api, identity, source, options) {
407
+ export async function runIssuesSync(api, identity, source, options, links) {
139
408
  const { owner, name } = parseGithubRemote(identity.repo);
140
409
  const repoKey = `${identity.namespace}:.`;
141
410
  const repoNode = (await api.all({ namespace: identity.namespace, types: "repository" })).nodes.find((n) => n.clientKey === repoKey && n.lifecycle === "active");
@@ -143,19 +412,25 @@ export async function runIssuesSync(api, identity, source, options) {
143
412
  throw new Error("The repository node is missing from the graph; run `cboard sync` first");
144
413
  const namespace = issuesNamespace(identity.repo);
145
414
  const fetched = await source({ owner, name, state: options.state, limit: options.limit });
146
- const issues = fetched
415
+ const listed = fetched
147
416
  .filter((i) => !i.pull_request)
148
417
  .sort((a, b) => a.number - b.number)
149
418
  .slice(0, options.limit);
150
- const snapshot = snapshotOf(issues, namespace, repoKey);
419
+ const { adopted, skipped } = await findAdoptable(api, listed, namespace, { owner, name });
420
+ const issues = listed.filter((i) => !skipped.has(i.number));
421
+ const snapshot = snapshotOf(issues, namespace, repoKey, adopted);
151
422
  const complete = options.state === "all" && options.limit === undefined;
152
- const result = await reconcile(api, snapshot, namespace, complete, new Map([[repoKey, repoNode.id]]));
153
- return { issues: issues.length, contributions: result.contributions };
423
+ const result = await reconcile(api, snapshot, namespace, complete, new Map([[repoKey, repoNode.id]]), adopted);
424
+ const linked = links && options.linkCode !== false
425
+ ? await linkIssuesToCode(api, identity, issues, complete, links.source, links.store, repoNode, adopted)
426
+ : {};
427
+ return { issues: issues.length, contributions: result.contributions, ...linked };
154
428
  }
155
- export async function issuesSync(argv, source = githubSource) {
429
+ export async function issuesSync(argv, source = githubSource, closing = githubClosingPrs) {
156
430
  const args = issuesSyncOptions(argv);
157
431
  const root = resolve(args.repo ?? process.cwd());
158
432
  const { project, token, server } = resolveSync(args, root);
159
- const result = await runIssuesSync(new ContextApi(server, project, token, { heads: fileHeadStore() }), repository(root), source, { state: args.state, limit: args.limit });
433
+ const heads = fileHeadStore();
434
+ 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
435
  console.log(JSON.stringify(result));
161
436
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codyn06/cboard",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "Client for cboard project graphs: connect a repository, sync its code layer, check the connection.",
5
5
  "keywords": [
6
6
  "cboard",