@blackbelt-technology/pi-dashboard-kb 0.9.0 → 0.11.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.
Files changed (95) hide show
  1. package/bin/kb.mjs +12 -7
  2. package/dist/chunker.js +48 -2
  3. package/dist/cli.js +48 -16
  4. package/dist/config.d.ts +47 -0
  5. package/dist/config.js +130 -2
  6. package/dist/dox-row.d.ts +9 -0
  7. package/dist/dox-row.js +32 -0
  8. package/dist/dox-triage.d.ts +1 -2
  9. package/dist/dox-triage.js +8 -8
  10. package/dist/dox.js +18 -11
  11. package/dist/git-scope/commits.d.ts +26 -0
  12. package/dist/git-scope/commits.js +243 -0
  13. package/dist/git-scope/deps.d.ts +41 -0
  14. package/dist/git-scope/deps.js +78 -0
  15. package/dist/git-scope/forge/cli.d.ts +16 -0
  16. package/dist/git-scope/forge/cli.js +66 -0
  17. package/dist/git-scope/forge/gitea.d.ts +15 -0
  18. package/dist/git-scope/forge/gitea.js +98 -0
  19. package/dist/git-scope/forge/github.d.ts +8 -0
  20. package/dist/git-scope/forge/github.js +50 -0
  21. package/dist/git-scope/forge/gitlab.d.ts +8 -0
  22. package/dist/git-scope/forge/gitlab.js +49 -0
  23. package/dist/git-scope/forge/index.d.ts +7 -0
  24. package/dist/git-scope/forge/index.js +13 -0
  25. package/dist/git-scope/forge/types.d.ts +70 -0
  26. package/dist/git-scope/forge/types.js +21 -0
  27. package/dist/git-scope/index.d.ts +4 -0
  28. package/dist/git-scope/index.js +2 -0
  29. package/dist/git-scope/lease.d.ts +24 -0
  30. package/dist/git-scope/lease.js +80 -0
  31. package/dist/git-scope/links.d.ts +23 -0
  32. package/dist/git-scope/links.js +61 -0
  33. package/dist/git-scope/repo.d.ts +36 -0
  34. package/dist/git-scope/repo.js +99 -0
  35. package/dist/git-scope/scope.d.ts +78 -0
  36. package/dist/git-scope/scope.js +406 -0
  37. package/dist/git-scope/store.d.ts +16 -0
  38. package/dist/git-scope/store.js +71 -0
  39. package/dist/git-scope/sync.d.ts +44 -0
  40. package/dist/git-scope/sync.js +215 -0
  41. package/dist/gitignore.d.ts +19 -6
  42. package/dist/gitignore.js +99 -37
  43. package/dist/index-gate.d.ts +27 -0
  44. package/dist/index-gate.js +71 -0
  45. package/dist/index-run.d.ts +66 -5
  46. package/dist/index-run.js +317 -60
  47. package/dist/index.d.ts +10 -3
  48. package/dist/index.js +6 -2
  49. package/dist/indexer.d.ts +22 -0
  50. package/dist/indexer.js +70 -14
  51. package/dist/migrate-file-index.js +4 -4
  52. package/dist/migrate-runner.js +7 -5
  53. package/dist/seed.d.ts +59 -0
  54. package/dist/seed.js +235 -0
  55. package/dist/sqlite-store.d.ts +72 -6
  56. package/dist/sqlite-store.js +270 -42
  57. package/dist/types.d.ts +41 -0
  58. package/dist/verdict.d.ts +10 -2
  59. package/dist/verdict.js +19 -10
  60. package/engine-fingerprint.json +3 -3
  61. package/package.json +3 -3
  62. package/src/chunker.ts +46 -2
  63. package/src/cli.ts +46 -15
  64. package/src/config.ts +145 -2
  65. package/src/dox-row.ts +35 -0
  66. package/src/dox-triage.ts +8 -8
  67. package/src/dox.ts +17 -11
  68. package/src/git-scope/commits.ts +267 -0
  69. package/src/git-scope/deps.ts +111 -0
  70. package/src/git-scope/forge/cli.ts +76 -0
  71. package/src/git-scope/forge/gitea.ts +124 -0
  72. package/src/git-scope/forge/github.ts +73 -0
  73. package/src/git-scope/forge/gitlab.ts +71 -0
  74. package/src/git-scope/forge/index.ts +17 -0
  75. package/src/git-scope/forge/types.ts +88 -0
  76. package/src/git-scope/index.ts +6 -0
  77. package/src/git-scope/lease.ts +80 -0
  78. package/src/git-scope/links.ts +73 -0
  79. package/src/git-scope/repo.ts +108 -0
  80. package/src/git-scope/scope.ts +424 -0
  81. package/src/git-scope/store.ts +73 -0
  82. package/src/git-scope/sync.ts +240 -0
  83. package/src/gitignore.ts +106 -39
  84. package/src/index-gate.ts +73 -0
  85. package/src/index-run.ts +362 -58
  86. package/src/index.ts +10 -3
  87. package/src/indexer.ts +84 -14
  88. package/src/migrate-file-index.ts +4 -4
  89. package/src/migrate-runner.ts +6 -4
  90. package/src/node-sqlite.d.ts +9 -0
  91. package/src/seed.ts +249 -0
  92. package/src/sources.ts +4 -1
  93. package/src/sqlite-store.ts +269 -42
  94. package/src/types.ts +43 -1
  95. package/src/verdict.ts +29 -15
@@ -0,0 +1,26 @@
1
+ import type { GitConfig } from "../config.js";
2
+ import type { KbStore } from "../types.js";
3
+ import type { GitScopeDeps } from "./deps.js";
4
+ import type { GitLease } from "./lease.js";
5
+ import { type LinkCtx } from "./links.js";
6
+ export interface Fingerprint {
7
+ fp: string;
8
+ tips: string[];
9
+ }
10
+ /** Hash of `for-each-ref` (heads, remotes, tags) plus every worktree HEAD; one local exec each. */
11
+ export declare function fingerprint(deps: GitScopeDeps, cwd: string): Fingerprint;
12
+ export interface IngestArgs {
13
+ deps: GitScopeDeps;
14
+ cwd: string;
15
+ cfg: GitConfig;
16
+ store: KbStore;
17
+ lease: GitLease;
18
+ link: LinkCtx;
19
+ signal: AbortSignal;
20
+ }
21
+ export interface IngestResult {
22
+ indexed: number;
23
+ reset: boolean;
24
+ }
25
+ /** Bring the commit index up to the repository's current tips. No-op when the fingerprint is unchanged. */
26
+ export declare function ingestCommits(a: IngestArgs): Promise<IngestResult>;
@@ -0,0 +1,243 @@
1
+ // Local commit indexing (design G2): a fingerprint over refs + worktree HEADs, a
2
+ // streamed incremental `git log --stdin` walk (new tips positive, recorded tips
3
+ // `^sha`), applied in bounded pages inside fenced write transactions.
4
+ import { createHash } from "node:crypto";
5
+ import { buildEdges } from "./links.js";
6
+ import { GIT_ROOT, metaDelete, metaGet, metaJson, metaSet, metaSetJson } from "./store.js";
7
+ const PAGE_MAX_COMMITS = 500;
8
+ const PAGE_MAX_MS = 1000;
9
+ /** Hash of `for-each-ref` (heads, remotes, tags) plus every worktree HEAD; one local exec each. */
10
+ export function fingerprint(deps, cwd) {
11
+ const fmt = "%(objecttype) %(objectname) %(*objecttype) %(*objectname) %(refname)";
12
+ const refs = deps.git(["for-each-ref", `--format=${fmt}`, "refs/heads", "refs/remotes", "refs/tags"], cwd);
13
+ const tips = new Set();
14
+ for (const line of refs.split("\n")) {
15
+ const [type, name, ptype, pname] = line.split(" ");
16
+ if (type === "commit" && name)
17
+ tips.add(name);
18
+ else if (type === "tag" && ptype === "commit" && pname)
19
+ tips.add(pname);
20
+ }
21
+ let wt = "";
22
+ try {
23
+ wt = deps.git(["worktree", "list", "--porcelain"], cwd);
24
+ }
25
+ catch { /* old git without worktree list: refs only */ }
26
+ const heads = [];
27
+ for (const line of wt.split("\n")) {
28
+ const m = /^HEAD ([0-9a-f]{40,64})$/.exec(line);
29
+ if (m) {
30
+ tips.add(m[1]);
31
+ heads.push(m[1]);
32
+ }
33
+ }
34
+ const fp = createHash("sha256").update(refs).update("\0").update(heads.sort().join("\n")).digest("hex");
35
+ return { fp, tips: [...tips].sort() };
36
+ }
37
+ /** Streaming parser for `%x00%H%x00%an%x00%aI%x00%s%x00%b%x00` + `--name-only` output:
38
+ * a leading empty token, then groups of 6 NUL-terminated tokens (the 6th, the paths
39
+ * blob, ends at the next record's NUL or at EOF). Invalid UTF-8 → U+FFFD. */
40
+ class CommitStreamParser {
41
+ carry = Buffer.alloc(0);
42
+ tokens = [];
43
+ first = true;
44
+ dec = new TextDecoder("utf-8");
45
+ maxPaths;
46
+ constructor(maxPaths) {
47
+ this.maxPaths = maxPaths;
48
+ }
49
+ push(chunk) {
50
+ const buf = this.carry.length ? Buffer.concat([this.carry, chunk]) : chunk;
51
+ const out = [];
52
+ let start = 0;
53
+ for (let i = buf.indexOf(0, start); i !== -1; i = buf.indexOf(0, start)) {
54
+ this.take(this.dec.decode(buf.subarray(start, i)), out);
55
+ start = i + 1;
56
+ }
57
+ this.carry = Buffer.from(buf.subarray(start));
58
+ return out;
59
+ }
60
+ end() {
61
+ const out = [];
62
+ if (this.carry.length)
63
+ this.take(this.dec.decode(this.carry), out);
64
+ this.carry = Buffer.alloc(0);
65
+ return out;
66
+ }
67
+ take(tok, out) {
68
+ if (this.first) {
69
+ this.first = false; // the empty token before the first record
70
+ return;
71
+ }
72
+ this.tokens.push(tok);
73
+ if (this.tokens.length === 6) {
74
+ const [sha, author, date, subject, body, names] = this.tokens;
75
+ this.tokens = [];
76
+ out.push({ sha, author, date, subject, body, paths: names.split("\n").filter(Boolean).slice(0, this.maxPaths) });
77
+ }
78
+ }
79
+ }
80
+ function commitChunk(c) {
81
+ const path = `commit/${c.sha}`;
82
+ const body = [
83
+ `commit ${c.sha}`,
84
+ `Author: ${c.author}`,
85
+ `Date: ${c.date}`,
86
+ "",
87
+ c.subject,
88
+ ...(c.body.trim() ? ["", c.body.trim()] : []),
89
+ ...(c.paths.length ? ["", `Changed paths (${c.paths.length}):`, ...c.paths] : []),
90
+ ].join("\n");
91
+ return {
92
+ root: GIT_ROOT,
93
+ path,
94
+ chunkId: `${path}#0`,
95
+ headingPath: `commit ${c.sha.slice(0, 7)} · ${c.date.slice(0, 10)} · ${c.author} > ${c.subject}`,
96
+ heading: c.subject,
97
+ level: 0,
98
+ parentChunkId: null,
99
+ docType: "doc",
100
+ body,
101
+ bodyHash: createHash("sha256").update(body).digest("hex"),
102
+ };
103
+ }
104
+ class WalkFailed extends Error {
105
+ stderr;
106
+ constructor(stderr) {
107
+ super(stderr.trim().split("\n").pop() || "git log failed");
108
+ this.stderr = stderr;
109
+ }
110
+ }
111
+ const tick = () => new Promise((r) => setImmediate(r));
112
+ /** Apply records in pages bounded by PAGE_MAX_COMMITS / PAGE_MAX_MS of write time, one fenced tx each. */
113
+ async function applyPage(a, records) {
114
+ let i = 0;
115
+ while (i < records.length) {
116
+ a.lease.fenced((db) => {
117
+ const t0 = Date.now();
118
+ while (i < records.length && Date.now() - t0 < PAGE_MAX_MS) {
119
+ const rec = records[i];
120
+ const chunk = commitChunk(rec);
121
+ a.store.replaceItem(GIT_ROOT, chunk.path, [chunk], buildEdges(db, chunk.path, `${rec.subject}\n${rec.body}`, a.link));
122
+ i++;
123
+ }
124
+ });
125
+ await tick();
126
+ }
127
+ }
128
+ function walk(a, tips, recorded, first) {
129
+ const fmt = "--format=%x00%H%x00%an%x00%aI%x00%s%x00%b%x00";
130
+ const args = ["-c", "core.quotepath=false", "log", "--stdin", "--no-color", "--encoding=UTF-8", "--no-renames", "--name-only", fmt];
131
+ if (first)
132
+ args.push(`--max-count=${a.cfg.commits.maxInitial}`);
133
+ return new Promise((resolve, reject) => {
134
+ const child = a.deps.spawnGit(args, a.cwd);
135
+ let stderr = "";
136
+ child.stderr.on("data", (d) => {
137
+ if (stderr.length < 4096)
138
+ stderr += d.toString("utf8");
139
+ });
140
+ const onAbort = () => child.kill("SIGTERM");
141
+ a.signal.addEventListener("abort", onAbort, { once: true });
142
+ child.stdin.on("error", () => { });
143
+ // positive tips, then `^<recorded tip>` — `--not --stdin` would NOT negate stdin lines
144
+ child.stdin.end(`${[...tips, ...recorded.map((t) => `^${t}`)].join("\n")}\n`);
145
+ const parser = new CommitStreamParser(a.cfg.commits.maxPathsPerCommit);
146
+ let indexed = 0;
147
+ let batch = [];
148
+ let chain = Promise.resolve();
149
+ let failed;
150
+ const enqueue = (records) => {
151
+ batch.push(...records);
152
+ if (batch.length < PAGE_MAX_COMMITS || failed)
153
+ return;
154
+ const page = batch;
155
+ batch = [];
156
+ chain = chain.then(async () => {
157
+ if (failed)
158
+ return;
159
+ try {
160
+ await applyPage(a, page);
161
+ indexed += page.length;
162
+ }
163
+ catch (e) {
164
+ failed = e;
165
+ child.kill("SIGTERM");
166
+ }
167
+ });
168
+ };
169
+ child.stdout.on("data", (d) => {
170
+ enqueue(parser.push(d));
171
+ // backpressure: stop reading while a page is being applied
172
+ child.stdout.pause();
173
+ chain.then(() => child.stdout.resume());
174
+ });
175
+ child.on("error", (e) => {
176
+ // spawn failure (no git): no stream will drain, so settle here
177
+ a.signal.removeEventListener("abort", onAbort);
178
+ reject(e);
179
+ });
180
+ child.on("close", (code) => {
181
+ a.signal.removeEventListener("abort", onAbort);
182
+ chain = chain.then(async () => {
183
+ if (failed)
184
+ return;
185
+ try {
186
+ batch.push(...parser.end());
187
+ if (batch.length) {
188
+ const page = batch;
189
+ batch = [];
190
+ await applyPage(a, page);
191
+ indexed += page.length;
192
+ }
193
+ }
194
+ catch (e) {
195
+ failed = e;
196
+ }
197
+ });
198
+ chain.then(() => {
199
+ if (failed)
200
+ return reject(failed);
201
+ if (a.signal.aborted)
202
+ return reject(new Error("aborted"));
203
+ if (code !== 0)
204
+ return reject(new WalkFailed(stderr));
205
+ resolve(indexed);
206
+ });
207
+ });
208
+ });
209
+ }
210
+ /** Bring the commit index up to the repository's current tips. No-op when the fingerprint is unchanged. */
211
+ export async function ingestCommits(a) {
212
+ const { fp, tips } = fingerprint(a.deps, a.cwd);
213
+ const read = (key) => a.store.read((db) => metaJson(db, key));
214
+ const storedFp = a.store.read((db) => metaGet(db, "commits.fingerprint"));
215
+ if (storedFp === fp)
216
+ return { indexed: 0, reset: false };
217
+ const recorded = read("commits.tips") ?? [];
218
+ let reset = false;
219
+ let indexed = 0;
220
+ try {
221
+ if (tips.length)
222
+ indexed = await walk(a, tips, recorded, recorded.length === 0);
223
+ }
224
+ catch (e) {
225
+ if (!(e instanceof WalkFailed) || recorded.length === 0)
226
+ throw e;
227
+ // a recorded tip no longer exists (gc, rebase): re-walk from the current tips; upserts are idempotent
228
+ reset = true;
229
+ a.lease.fenced((db) => {
230
+ metaDelete(db, "commits.tips");
231
+ metaSet(db, "lastError", `commit walk reset: ${e.message}`);
232
+ });
233
+ indexed = await walk(a, tips, [], true);
234
+ }
235
+ a.lease.fenced((db) => {
236
+ metaSet(db, "commits.fingerprint", fp);
237
+ metaSetJson(db, "commits.tips", tips);
238
+ metaSet(db, "commits.indexedAt", String(a.deps.now()));
239
+ if (!reset)
240
+ metaDelete(db, "lastError");
241
+ });
242
+ return { indexed, reset };
243
+ }
@@ -0,0 +1,41 @@
1
+ import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ export interface CliResult {
3
+ code: number | null;
4
+ stdout: string;
5
+ stderr: string;
6
+ /** Set when the binary could not be started at all (ENOENT/EACCES). */
7
+ spawnError?: string;
8
+ }
9
+ interface CliOpts {
10
+ signal?: AbortSignal;
11
+ timeoutMs?: number;
12
+ env?: NodeJS.ProcessEnv;
13
+ }
14
+ export interface GitScopeDeps {
15
+ /** Synchronous git (rev-parse, for-each-ref, …). Throws {@link GitExecError}. */
16
+ git(args: string[], cwd: string): string;
17
+ /** Streaming git (log). argv only. */
18
+ spawnGit(args: string[], cwd: string): ChildProcessWithoutNullStreams;
19
+ /** Absolute path of a CLI (`gh`, `glab`), or null when not installed. Resolved once per process. */
20
+ resolveBin(name: string): string | null;
21
+ /** Run a forge CLI by absolute path. */
22
+ runCli(bin: string, args: string[], opts?: CliOpts): Promise<CliResult>;
23
+ fetch: typeof fetch;
24
+ now(): number;
25
+ /** Per forge request (CLI or HTTPS), ms. */
26
+ requestTimeoutMs: number;
27
+ env: NodeJS.ProcessEnv;
28
+ /** Directory holding one sub-directory per repoKey. */
29
+ baseDir: string;
30
+ /** Lease owner id (per process). */
31
+ owner: string;
32
+ /** One diagnostic line (never a credential). */
33
+ log(line: string): void;
34
+ }
35
+ export declare class GitExecError extends Error {
36
+ readonly code: string | number | null;
37
+ readonly stderr: string;
38
+ constructor(message: string, code: string | number | null, stderr: string);
39
+ }
40
+ export declare function defaultDeps(): GitScopeDeps;
41
+ export {};
@@ -0,0 +1,78 @@
1
+ // Injectable seams for the git scope (change: add-kb-git-forge-scope). Every
2
+ // process-, clock- and network-touching call goes through `GitScopeDeps` so the
3
+ // scope is testable without a network, a forge login or real time.
4
+ import { execFile, execFileSync, spawn } from "node:child_process"; // ban:child_process-ok (kb package is self-contained; owns the local git walk + forge CLI exec, argv only, never a shell)
5
+ import { accessSync, constants, statSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { delimiter, join } from "node:path";
8
+ export class GitExecError extends Error {
9
+ code;
10
+ stderr;
11
+ constructor(message, code, stderr) {
12
+ super(message);
13
+ this.name = "GitExecError";
14
+ this.code = code;
15
+ this.stderr = stderr;
16
+ }
17
+ }
18
+ const GIT_ENV = { GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" };
19
+ function realGit(args, cwd) {
20
+ try {
21
+ return execFileSync("git", args, { cwd, encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ...GIT_ENV } });
22
+ }
23
+ catch (e) {
24
+ const err = e;
25
+ throw new GitExecError(err.message, err.code ?? err.status ?? null, String(err.stderr ?? ""));
26
+ }
27
+ }
28
+ const binCache = new Map();
29
+ /** Resolve a CLI to an absolute path once per process: PATH plus the usual Homebrew/system dirs. */
30
+ function resolveBinOnPath(name, env = process.env) {
31
+ if (binCache.has(name))
32
+ return binCache.get(name) ?? null;
33
+ const dirs = (env.PATH ?? "").split(delimiter).filter(Boolean);
34
+ for (const extra of ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", join(homedir(), ".local", "bin")])
35
+ if (!dirs.includes(extra))
36
+ dirs.push(extra);
37
+ let found = null;
38
+ for (const d of dirs) {
39
+ const p = join(d, name);
40
+ try {
41
+ if (!statSync(p).isFile())
42
+ continue;
43
+ accessSync(p, constants.X_OK);
44
+ found = p;
45
+ break;
46
+ }
47
+ catch { /* next dir */ }
48
+ }
49
+ binCache.set(name, found);
50
+ return found;
51
+ }
52
+ function realRunCli(bin, args, opts = {}) {
53
+ return new Promise((resolve) => {
54
+ execFile(bin, args, { encoding: "utf8", timeout: opts.timeoutMs ?? 30_000, maxBuffer: 16 * 1024 * 1024, signal: opts.signal, env: opts.env ?? process.env }, (err, stdout, stderr) => {
55
+ if (!err)
56
+ return resolve({ code: 0, stdout, stderr });
57
+ const e = err;
58
+ if (typeof e.code === "string")
59
+ return resolve({ code: null, stdout: stdout ?? "", stderr: stderr ?? "", spawnError: `${e.code}: ${e.message}` });
60
+ resolve({ code: typeof e.code === "number" ? e.code : 1, stdout: stdout ?? "", stderr: stderr ?? "" });
61
+ });
62
+ });
63
+ }
64
+ export function defaultDeps() {
65
+ return {
66
+ git: realGit,
67
+ spawnGit: (args, cwd) => spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...GIT_ENV } }),
68
+ resolveBin: (name) => resolveBinOnPath(name),
69
+ runCli: realRunCli,
70
+ fetch: (...a) => globalThis.fetch(...a),
71
+ now: () => Date.now(),
72
+ requestTimeoutMs: 30_000,
73
+ env: process.env,
74
+ baseDir: join(homedir(), ".pi", "dashboard", "kb", "git"),
75
+ owner: `${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
76
+ log: (line) => console.log(`[kb-git] ${line}`),
77
+ };
78
+ }
@@ -0,0 +1,16 @@
1
+ import type { GitScopeDeps } from "../deps.js";
2
+ import { type RateInfo } from "./types.js";
3
+ export interface HttpResult {
4
+ status: number;
5
+ headers: Record<string, string>;
6
+ body: string;
7
+ }
8
+ export interface CliCall {
9
+ /** `gh` or `glab`. */
10
+ cli: "gh" | "glab";
11
+ args: string[];
12
+ }
13
+ /** Run one CLI request and classify the outcome. Returns the parsed response for 200/304. */
14
+ export declare function cliRequest(deps: GitScopeDeps, call: CliCall, rateFrom: (h: Record<string, string>) => RateInfo | null, signal?: AbortSignal): Promise<HttpResult & {
15
+ rate: RateInfo | null;
16
+ }>;
@@ -0,0 +1,66 @@
1
+ import { ForgeRateLimited, ForgeUnavailable } from "./types.js";
2
+ /** Parse `gh api -i` / `glab api -i` stdout. Null when there is no HTTP head. */
3
+ function parseHttpHead(stdout) {
4
+ const text = stdout.replace(/\r\n/g, "\n");
5
+ const split = text.indexOf("\n\n");
6
+ const headBlock = split === -1 ? text : text.slice(0, split);
7
+ const body = split === -1 ? "" : text.slice(split + 2);
8
+ const [statusLine, ...headLines] = headBlock.split("\n");
9
+ const m = /^HTTP\/[\d.]+\s+(\d{3})/.exec(statusLine ?? "");
10
+ if (!m)
11
+ return null;
12
+ const headers = {};
13
+ for (const line of headLines) {
14
+ const i = line.indexOf(":");
15
+ if (i > 0)
16
+ headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
17
+ }
18
+ return { status: Number(m[1]), headers, body };
19
+ }
20
+ /** Seconds → epoch ms from a `retry-after` (seconds) or reset (epoch seconds) header. */
21
+ function retryAtFrom(headers, now) {
22
+ const ra = Number(headers["retry-after"]);
23
+ if (Number.isFinite(ra) && ra > 0)
24
+ return now + ra * 1000;
25
+ const reset = Number(headers["x-ratelimit-reset"] ?? headers["ratelimit-reset"]);
26
+ if (Number.isFinite(reset) && reset > 0)
27
+ return reset * (reset < 1e12 ? 1000 : 1);
28
+ return null;
29
+ }
30
+ /** No HTTP head on stdout: not logged in, no network, or a CLI-level error. */
31
+ function headlessError(cli, r) {
32
+ const msg = r.stderr.trim().split("\n")[0] ?? "";
33
+ if (/auth|log ?in|token|credential/i.test(msg) || r.code === 4)
34
+ return new ForgeUnavailable(`${cli} is not authenticated`);
35
+ return new ForgeUnavailable(msg ? `${cli}: ${msg.slice(0, 120)}` : `${cli} failed (exit ${r.code})`);
36
+ }
37
+ /** Classify a non-2xx/304 answer. */
38
+ function statusError(cli, http, rate, now) {
39
+ const h = http.headers;
40
+ const exhausted = h["x-ratelimit-remaining"] === "0" || h["ratelimit-remaining"] === "0";
41
+ if (http.status === 429 || (http.status === 403 && (exhausted || h["retry-after"] || /rate limit/i.test(http.body))))
42
+ return new ForgeRateLimited(retryAtFrom(h, now), rate);
43
+ if (http.status === 401)
44
+ return new ForgeUnavailable(`${cli} is not authenticated`);
45
+ if (http.status === 403)
46
+ return new ForgeUnavailable("access forbidden");
47
+ if (http.status === 404)
48
+ return new ForgeUnavailable("repository not found or no access");
49
+ return new ForgeUnavailable(`forge answered HTTP ${http.status}`);
50
+ }
51
+ /** Run one CLI request and classify the outcome. Returns the parsed response for 200/304. */
52
+ export async function cliRequest(deps, call, rateFrom, signal) {
53
+ const bin = deps.resolveBin(call.cli);
54
+ if (!bin)
55
+ throw new ForgeUnavailable(`${call.cli} is not installed`);
56
+ const r = await deps.runCli(bin, call.args, { signal, timeoutMs: deps.requestTimeoutMs });
57
+ if (r.spawnError)
58
+ throw new ForgeUnavailable(`${call.cli} could not be started`);
59
+ const http = parseHttpHead(r.stdout);
60
+ if (!http)
61
+ throw headlessError(call.cli, r);
62
+ const rate = rateFrom(http.headers);
63
+ if (http.status === 200 || http.status === 304)
64
+ return { ...http, rate };
65
+ throw statusError(call.cli, http, rate, deps.now());
66
+ }
@@ -0,0 +1,15 @@
1
+ import type { GitScopeDeps } from "../deps.js";
2
+ import { type ForgeAdapter } from "./types.js";
3
+ export interface GiteaRepoRef {
4
+ /** host[:port] as written in the remote */
5
+ host: string;
6
+ /** `owner/repo` */
7
+ path: string;
8
+ }
9
+ export interface GiteaAuth {
10
+ /** True iff the host is listed in global `git.forge.hosts` as gitea. */
11
+ allowlisted: boolean;
12
+ /** Name of the env var holding the token (global config). */
13
+ tokenEnv: string;
14
+ }
15
+ export declare function createGiteaAdapter(deps: GitScopeDeps, ref: GiteaRepoRef, auth: GiteaAuth): ForgeAdapter;
@@ -0,0 +1,98 @@
1
+ import { ForgeRateLimited, ForgeUnavailable } from "./types.js";
2
+ const GITEA_PAGE = 50;
3
+ /** `RateLimit: "baseline";r=1999;t=600` + `RateLimit-Policy: "baseline";q=2000;w=600` (no x-ratelimit-*). */
4
+ function giteaRate(h, now) {
5
+ const rl = h.get("ratelimit");
6
+ const pol = h.get("ratelimit-policy");
7
+ const r = /;\s*r=(\d+)/.exec(rl ?? "");
8
+ const t = /;\s*t=(\d+)/.exec(rl ?? "");
9
+ const q = /;\s*q=(\d+)/.exec(pol ?? "");
10
+ if (!r || !q)
11
+ return null;
12
+ return { remaining: Number(r[1]), limit: Number(q[1]), resetAt: now + Number(t?.[1] ?? 0) * 1000 };
13
+ }
14
+ /** Normalise a zone-offset timestamp to UTC `Z`. */
15
+ const toUtc = (ts) => (ts && !Number.isNaN(Date.parse(ts)) ? new Date(ts).toISOString().replace(".000Z", "Z") : "");
16
+ function mapGiteaItem(i) {
17
+ const isPr = !!i.pull_request;
18
+ return {
19
+ kind: isPr ? "pr" : "issue",
20
+ number: i.number,
21
+ title: i.title ?? "",
22
+ body: i.body ?? "",
23
+ state: isPr && i.pull_request?.merged ? "merged" : i.state === "closed" ? "closed" : "open",
24
+ author: i.user?.login ?? "ghost",
25
+ labels: (i.labels ?? []).map((l) => l.name ?? "").filter(Boolean),
26
+ createdAt: toUtc(i.created_at),
27
+ updatedAt: toUtc(i.updated_at),
28
+ };
29
+ }
30
+ /** Why a fetch failed, without blaming https for a timeout or a DNS error. */
31
+ function networkReason(e, timedOut) {
32
+ if (timedOut)
33
+ return "request timed out";
34
+ const code = e.cause?.code;
35
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN")
36
+ return "host not found";
37
+ return "https required"; // refused / reset / TLS failure: the https endpoint is not usable
38
+ }
39
+ /** Classify a non-2xx/304 answer. */
40
+ function statusError(res, rate, hasToken, now) {
41
+ const retryAfter = res.headers.get("retry-after");
42
+ if (res.status === 429 || (res.status === 403 && retryAfter)) {
43
+ const ra = Number(retryAfter);
44
+ return new ForgeRateLimited(Number.isFinite(ra) && ra > 0 ? now + ra * 1000 : null, rate);
45
+ }
46
+ if (res.status === 401 || res.status === 403)
47
+ return new ForgeUnavailable(hasToken ? "access forbidden" : "authentication required");
48
+ if (res.status === 404)
49
+ return new ForgeUnavailable("repository not found or no access");
50
+ return new ForgeUnavailable(`forge answered HTTP ${res.status}`);
51
+ }
52
+ export function createGiteaAdapter(deps, ref, auth) {
53
+ const base = `https://${ref.host}/api/v1/repos/${ref.path}`;
54
+ const token = auth.allowlisted ? deps.env[auth.tokenEnv] : undefined;
55
+ const get = async (url, etag, signal) => {
56
+ const headers = { accept: "application/json" };
57
+ if (token)
58
+ headers.authorization = `token ${token}`;
59
+ if (etag)
60
+ headers["if-none-match"] = etag;
61
+ const timeout = AbortSignal.timeout(deps.requestTimeoutMs);
62
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
63
+ let res;
64
+ try {
65
+ res = await deps.fetch(url, { headers, signal: combined, redirect: "error" });
66
+ }
67
+ catch (e) {
68
+ if (signal?.aborted)
69
+ throw e;
70
+ throw new ForgeUnavailable(networkReason(e, timeout.aborted));
71
+ }
72
+ const rate = giteaRate(res.headers, deps.now());
73
+ if (res.status === 200 || res.status === 304)
74
+ return { res, rate };
75
+ throw statusError(res, rate, !!token, deps.now());
76
+ };
77
+ return {
78
+ id: "gitea",
79
+ endpoints: ["issues"],
80
+ sharedNumberSpace: true,
81
+ async list(_ep, a) {
82
+ const q = `state=all&type=all&sort=leastupdate&since=${encodeURIComponent(a.since)}&limit=${GITEA_PAGE}&page=${a.page}`;
83
+ const { res, rate } = await get(`${base}/issues?${q}`, a.etag, a.signal);
84
+ if (res.status === 304)
85
+ return { status: "not_modified", items: [], full: false, etag: a.etag, rate };
86
+ const rows = (await res.json());
87
+ return { status: "ok", items: rows.map(mapGiteaItem), full: rows.length >= GITEA_PAGE, etag: res.headers.get("etag"), rate };
88
+ },
89
+ async comments(_kind, n, etag, signal) {
90
+ const { res, rate } = await get(`${base}/issues/${n}/comments`, etag, signal);
91
+ if (res.status === 304)
92
+ return { status: "not_modified", comments: [], etag, rate };
93
+ const rows = (await res.json());
94
+ const comments = rows.map((c) => ({ author: c.user?.login ?? "ghost", createdAt: toUtc(c.created_at), body: c.body ?? "" }));
95
+ return { status: "ok", comments, etag: res.headers.get("etag"), rate };
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,8 @@
1
+ import type { GitScopeDeps } from "../deps.js";
2
+ import { type ForgeAdapter } from "./types.js";
3
+ export interface GithubRepoRef {
4
+ host: string;
5
+ /** `owner/repo` */
6
+ path: string;
7
+ }
8
+ export declare function createGithubAdapter(deps: GitScopeDeps, ref: GithubRepoRef): ForgeAdapter;
@@ -0,0 +1,50 @@
1
+ import { cliRequest } from "./cli.js";
2
+ import { PAGE_SIZE } from "./types.js";
3
+ function githubRate(h) {
4
+ const remaining = Number(h["x-ratelimit-remaining"]);
5
+ const limit = Number(h["x-ratelimit-limit"]);
6
+ const reset = Number(h["x-ratelimit-reset"]);
7
+ if (![remaining, limit, reset].every(Number.isFinite) || limit <= 0)
8
+ return null;
9
+ return { remaining, limit, resetAt: reset * 1000 };
10
+ }
11
+ function mapGithubItem(i) {
12
+ const isPr = !!i.pull_request;
13
+ return {
14
+ kind: isPr ? "pr" : "issue",
15
+ number: i.number,
16
+ title: i.title ?? "",
17
+ body: i.body ?? "",
18
+ state: isPr && i.pull_request?.merged_at ? "merged" : i.state === "closed" ? "closed" : "open",
19
+ author: i.user?.login ?? "ghost",
20
+ labels: (i.labels ?? []).map((l) => (typeof l === "string" ? l : (l.name ?? ""))).filter(Boolean),
21
+ createdAt: i.created_at ?? "",
22
+ updatedAt: i.updated_at ?? "",
23
+ };
24
+ }
25
+ export function createGithubAdapter(deps, ref) {
26
+ const base = `repos/${ref.path}`;
27
+ const call = (endpoint, etag, signal) => cliRequest(deps, { cli: "gh", args: ["api", "-i", "--hostname", ref.host, "-H", "Accept: application/vnd.github+json", ...(etag ? ["-H", `If-None-Match: ${etag}`] : []), endpoint] }, githubRate, signal);
28
+ return {
29
+ id: "github",
30
+ endpoints: ["issues"],
31
+ sharedNumberSpace: true,
32
+ async list(_ep, a) {
33
+ const q = `state=all&sort=updated&direction=asc&since=${encodeURIComponent(a.since)}&per_page=${PAGE_SIZE}&page=${a.page}`;
34
+ const r = await call(`${base}/issues?${q}`, a.etag, a.signal);
35
+ if (r.status === 304)
36
+ return { status: "not_modified", items: [], full: false, etag: a.etag, rate: r.rate };
37
+ const rows = JSON.parse(r.body || "[]");
38
+ return { status: "ok", items: rows.map(mapGithubItem), full: rows.length >= PAGE_SIZE, etag: r.headers.etag ?? null, rate: r.rate };
39
+ },
40
+ async comments(kind, n, etag, signal) {
41
+ const r = await call(`${base}/issues/${n}/comments?per_page=${PAGE_SIZE}`, etag, signal);
42
+ if (r.status === 304)
43
+ return { status: "not_modified", comments: [], etag, rate: r.rate };
44
+ const rows = JSON.parse(r.body || "[]");
45
+ const comments = rows.map((c) => ({ author: c.user?.login ?? "ghost", createdAt: c.created_at ?? "", body: c.body ?? "" }));
46
+ void kind;
47
+ return { status: "ok", comments, etag: r.headers.etag ?? null, rate: r.rate };
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,8 @@
1
+ import type { GitScopeDeps } from "../deps.js";
2
+ import { type ForgeAdapter } from "./types.js";
3
+ export interface GitlabRepoRef {
4
+ host: string;
5
+ /** `group[/subgroup]/repo` */
6
+ path: string;
7
+ }
8
+ export declare function createGitlabAdapter(deps: GitScopeDeps, ref: GitlabRepoRef): ForgeAdapter;