@aidenhq/sdk 0.3.0 → 0.4.1

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 (70) hide show
  1. package/README.md +15 -7
  2. package/dist/src/agent-paused.d.ts +7 -0
  3. package/dist/src/agent-paused.js +4 -0
  4. package/dist/src/attribution.d.ts +16 -0
  5. package/dist/src/attribution.js +21 -0
  6. package/dist/src/box-bundle.d.ts +9 -0
  7. package/dist/src/box-bundle.js +59 -0
  8. package/dist/src/caller.js +2 -1
  9. package/dist/src/checks.d.ts +101 -0
  10. package/dist/src/checks.js +151 -0
  11. package/dist/src/churn.d.ts +46 -0
  12. package/dist/src/churn.js +177 -0
  13. package/dist/src/closed-event.d.ts +36 -0
  14. package/dist/src/closed-event.js +17 -0
  15. package/dist/src/engine-io.d.ts +2 -0
  16. package/dist/src/engine-io.js +13 -8
  17. package/dist/src/executor.d.ts +46 -3
  18. package/dist/src/executor.js +23 -13
  19. package/dist/src/fence.d.ts +12 -0
  20. package/dist/src/fence.js +24 -1
  21. package/dist/src/for-others.d.ts +3 -0
  22. package/dist/src/for-others.js +7 -0
  23. package/dist/src/instance-details.d.ts +10 -0
  24. package/dist/src/instance-details.js +63 -0
  25. package/dist/src/instance-paths.d.ts +3 -0
  26. package/dist/src/instance-paths.js +7 -0
  27. package/dist/src/judge.d.ts +54 -20
  28. package/dist/src/judge.js +57 -75
  29. package/dist/src/kernel-client.d.ts +45 -0
  30. package/dist/src/kernel-client.js +103 -0
  31. package/dist/src/kit.js +19 -4
  32. package/dist/src/maintained-repos.d.ts +58 -0
  33. package/dist/src/maintained-repos.js +136 -0
  34. package/dist/src/model-text.d.ts +29 -0
  35. package/dist/src/model-text.js +361 -0
  36. package/dist/src/owner-day.d.ts +12 -0
  37. package/dist/src/owner-day.js +39 -0
  38. package/dist/src/paperclip.d.ts +34 -0
  39. package/dist/src/paperclip.js +64 -0
  40. package/dist/src/pass-rule.d.ts +10 -0
  41. package/dist/src/pass-rule.js +24 -0
  42. package/dist/src/pin-owner.d.ts +2 -0
  43. package/dist/src/pin-owner.js +1 -0
  44. package/dist/src/progress.js +7 -2
  45. package/dist/src/provider.d.ts +83 -0
  46. package/dist/src/provider.js +31 -0
  47. package/dist/src/quality.d.ts +74 -0
  48. package/dist/src/quality.js +131 -0
  49. package/dist/src/repeat.d.ts +19 -0
  50. package/dist/src/repeat.js +38 -0
  51. package/dist/src/responses.d.ts +64 -0
  52. package/dist/src/responses.js +198 -0
  53. package/dist/src/reviewer.d.ts +79 -34
  54. package/dist/src/reviewer.js +198 -22
  55. package/dist/src/source-store.d.ts +13 -3
  56. package/dist/src/source-store.js +14 -9
  57. package/dist/src/task-state-types.d.ts +77 -0
  58. package/dist/src/task-state-types.js +4 -0
  59. package/dist/src/tiers.d.ts +88 -0
  60. package/dist/src/tiers.js +156 -0
  61. package/dist/src/tools-client.d.ts +60 -0
  62. package/dist/src/tools-client.js +192 -0
  63. package/dist/src/types.d.ts +28 -2
  64. package/dist/src/vendor/needs.d.ts +35 -0
  65. package/dist/src/vendor/needs.js +43 -0
  66. package/dist/src/vendor/oauth.d.ts +82 -2
  67. package/dist/src/vendor/oauth.js +282 -32
  68. package/dist/src/vendor/proxy.d.ts +31 -6
  69. package/dist/src/vendor/proxy.js +376 -49
  70. package/package.json +11 -10
@@ -1,70 +1,115 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  export interface ReviewCard {
3
3
  action: string;
4
- rule: string;
4
+ rule?: string;
5
5
  target?: string;
6
6
  sentence?: string;
7
7
  reason?: string;
8
- /** The repositories that are one product for scope (the product repo and the official modules repo): code's own. */
9
- product?: string[];
10
8
  }
9
+ /**
10
+ * `list`: each changed file at the reviewed head, plain text whole or code's note (media, binary); `leftOut`: the files it
11
+ * can't read (binary); `changed`: the code host's own numstat of the change, read at filing: the reviewer checks the diff against it.
12
+ */
11
13
  export interface Files {
12
- text: string;
14
+ list: {
15
+ name: string;
16
+ text?: string;
17
+ note?: string;
18
+ }[];
13
19
  leftOut: string[];
14
- oversized: string[];
20
+ changed?: {
21
+ path: string;
22
+ add?: number;
23
+ del?: number;
24
+ }[];
15
25
  }
16
- export interface SourceRecords {
17
- where: string;
18
- records: Record<string, unknown>[];
26
+ /**
27
+ * A connection tool call as the reviewer reads it: the connection, the tool, and the call's own argument object, every key as
28
+ * the tool takes it. Sent by the kernel in place of a diff for a `conn.tool` record; the reviewer renders it as TOOL_CALL.
29
+ */
30
+ export interface ToolCall {
31
+ connection: string;
32
+ tool: string;
33
+ arguments: Record<string, unknown>;
34
+ unreadable?: string[];
19
35
  }
20
- /** One Tier 1 request as the reviewer reads it. Everything but `card.action`, `card.rule` and `panel` is data an agent or a stranger wrote. */
36
+ /** One request as the reviewer reads it. Everything but `card.action` is data an agent or a stranger wrote. */
21
37
  export interface ReviewRequest {
22
38
  card: ReviewCard;
23
39
  diff: string;
24
40
  files?: Files;
25
41
  chain?: string;
26
- siblings?: string;
27
- sources?: SourceRecords;
28
42
  requesterModel?: string;
29
- panel?: boolean;
30
- previous?: string[];
31
- relift?: string;
32
- /** A PR's Evidence section (the author's account of how it verified the change): sent for pr and merge cards only. */
33
- evidence?: string;
34
- /** `decisions`: the instance's decisions.md, read by the requester from the instance repo's default branch. */
35
- decisions?: {
36
- where: string;
37
- text: string;
38
- };
43
+ /**
44
+ * A connection tool call's arguments, structured, as the reviewer reads them instead of a diff: code read them from the
45
+ * record (`args.connection`, `args.tool`, `args.arguments`), never parsed out of the card's prose. `arguments` is the call's
46
+ * own argument object, key for key as the tool takes them. `unreadable` names each argument code could not read (a value
47
+ * that isn't there), so the reviewer is told which field is missing rather than that the whole call is body-only.
48
+ */
49
+ tool_call?: ToolCall;
50
+ /**
51
+ * The task's comments as they stand, oldest first, rendered by the kernel: each under a label line code wrote (the owner's
52
+ * own typed words, or an agent by its place in the request: the delegating agent, the chief of staff, the requesting agent,
53
+ * another agent) with its text quoted line by line. The text is its author's; only the labels are code's.
54
+ */
55
+ comments?: string;
56
+ /**
57
+ * An apply's product-commit roll-up, as code's planner wrote it: commits already merged on the product's main, which the
58
+ * change cannot alter. Shown as PRODUCT_COMMITS, never as part of the diff a finding may quote.
59
+ */
60
+ productCommits?: string;
39
61
  /** The ledger's name for the model calls (the card's review, or an agent's check before filing). */
40
62
  component?: string;
41
63
  }
64
+ /** `same_family`: on a plan the checker is the author's own model family; the review card says so. */
42
65
  export interface Verdict {
43
66
  decision: "approve" | "reject" | "escalate";
44
67
  code?: string;
45
68
  reason: string;
46
69
  model: string;
47
- second?: string;
48
- flag?: boolean;
49
- panel_marked?: boolean;
70
+ same_family?: true;
50
71
  }
51
- /** The model's "I can't tell" (a second reviewer decides; both unsure, the request goes back to the agent). */
52
- export declare const UNSURE = "reviewer_unsure";
72
+ /**
73
+ * Instance details in a GitHub write (a conn.tool card on the github connection: a comment, an issue, a review): a tailnet
74
+ * host (*.ts.net), a home-directory path, or an IPv4 address other than loopback. A GitHub thread is outside the instance and
75
+ * often public, and no issue or review needs these, so code refuses it itself: a model once approved a triage comment that
76
+ * pasted the host, its address and a runner log path as "in scope". (github-mcp's scrub redacts owner data from the
77
+ * comments when they are sent; this is the refusal before that, for every GitHub write.) The kernel runs it before it asks the
78
+ * reviewer (review-loop.ts), so it never fails open; the reviewer runs it too (review.ts).
79
+ */
80
+ export declare function instanceDetails(card: ReviewCard | undefined, diff: string | undefined, toolCall?: ToolCall): string[];
53
81
  /** The request fields a reviewer reads; anything else in a request (a policy, a model) is dropped. */
54
- export declare const REQUEST_FIELDS: readonly ["card", "diff", "files", "chain", "siblings", "sources", "decisions", "requesterModel", "panel", "previous", "relift", "evidence"];
55
- /** The module's reviewer: one request in, one verdict out. `onPanel` records that the change needs a second reviewer. */
82
+ export declare const REQUEST_FIELDS: readonly ["card", "diff", "tool_call", "files", "chain", "requesterModel", "comments", "productCommits"];
83
+ /**
84
+ * The handler POST `<path>/review`, and the `/healthz` beside it: it answers with the service instance that serves now, so the
85
+ * kernel's review loop can fail the reviews a recreated service (an apply) lost instead of waiting out any window.
86
+ */
87
+ export type ReviewerHandler = ((req: IncomingMessage, res: ServerResponse) => Promise<boolean>) & {
88
+ instance: string;
89
+ };
90
+ /**
91
+ * The module's reviewer: one request in, one verdict out. `progress` is called as the review's work advances (each model-call
92
+ * attempt and each answer), so a review that hangs reports none and the kernel's stall window runs out on it.
93
+ */
56
94
  export type Review = (req: ReviewRequest, ctx: {
57
95
  modelToken: string;
58
- onPanel: () => Promise<void>;
96
+ progress: () => void;
59
97
  }) => Promise<Verdict>;
60
98
  /**
61
- * A handler for POST `<path>/review`: answers and returns true, or returns false for any other path. It accepts at once and
62
- * sends the verdict to the kernel with the review's token (retried; a verdict the kernel no longer waits for is dropped).
63
- * A reviewer that throws sends `{ error }`: the requester counts it as a failed review (reviewer_failed) and tries again later.
99
+ * A handler for POST `<path>/review`: answers and returns true, or returns false for any other path. It accepts at once, naming
100
+ * the service instance that took the review (a fresh one each start, so the kernel fails what a recreated service lost; an answer
101
+ * without one is still accepted), and sends the verdict to the kernel with the review's token (retried; a verdict the kernel no
102
+ * longer waits for is dropped). While the review's work advances it keeps the review alive (at most once per BEAT_MS): the kernel
103
+ * bounds a review by progress, not only by its hour, so a call that hangs — and reports nothing — still stalls. GET `<path>/healthz`
104
+ * answers `{ ok: true, instance }`. A reviewer that throws sends `{ error }`: the requester counts it as a failed review
105
+ * (reviewer_failed) and tries again later.
64
106
  */
65
- export declare function serveReviewer(review: Review, { key, kernelUrl, path, log }: {
107
+ export declare function serveReviewer(review: Review, { key, kernelUrl, path, instance, beatMs, log }: {
66
108
  key: string;
67
109
  kernelUrl?: string;
68
110
  path?: string;
111
+ /** This service process's id: a review it took is failed at once when another instance answers /healthz. */
112
+ instance?: string;
113
+ beatMs?: number;
69
114
  log?: (msg: string, f?: Record<string, unknown>) => void;
70
- }): (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
115
+ }): ReviewerHandler;
@@ -1,37 +1,145 @@
1
1
  // reviewer@1 (spec §3.3.3): the AI reviewer is a module the kernel calls; a requester never runs it in its own process.
2
2
  // requester → kernel POST /v1/reviews { request } (the runner's reviewer key) → the verdict, once the module sends it
3
3
  // kernel → module POST <url>/review { id, token, model_token, request } (the module's service key) → { accepted: true }
4
+ // (and, when it names one, `instance`: this service's id; the kernel fails the reviews a service that
5
+ // restarted left behind. Optional in reviewer@1: an answer of `{ accepted: true }` alone is still accepted)
4
6
  // module → kernel POST /v1/reviews/:id <verdict> | { error } (Bearer: that review's token, once: it burns on use)
5
7
  // The module calls models through the gateway with `model_token` (a reviewer token the kernel minted for this review), never a
6
8
  // vendor key. It can't change a tier: the verdict is the requester's input, and the records bind it to their digest.
7
9
  //
8
- // Deviations from the spec's sketch, kept until 3b moves review orchestration into the kernel: one dispatch carries the panel
9
- // (`request.panel`) and the module runs it itself, so the second reviewer is asked only after a first approve, and an unsure
10
- // first hands its note to the second (both as before); the verdict is today's shape (decision, code, reason, model, second,
11
- // flag), and `panel_marked` says the first reviewer called the change authority-expanding, so the requester records that on
12
- // its card before acting on the verdict.
10
+ // The verdict is approve or reject (malice only), or escalate with code reviewer_failed for a review that couldn't finish:
11
+ // the kernel tries once more, then approves (fail open; owner, 2026-11-22).
13
12
  //
14
- // The requester shapes the changed files with `fileContext` (services/shared/review-files.mjs: the contract's budget), so the
15
- // request stays small whatever the files weigh.
13
+ // The requester reads the changed files with `fileContext` (services/shared/review-files.ts) and sends each whole, whatever
14
+ // its size: the reviewer shows what fits inline and reads the rest with read-only tools over the request.
16
15
  //
17
16
  // Canonical copy: kernel/sdk/src/reviewer.ts. The reviewer module holds a byte-identical copy at src/aidenhq-sdk/reviewer.ts:
18
- // edit this one, then run `node scripts/sync-shared.mjs`.
19
- import { timingSafeEqual } from "node:crypto";
20
- /** The model's "I can't tell" (a second reviewer decides; both unsure, the request goes back to the agent). */
21
- export const UNSURE = "reviewer_unsure";
17
+ // edit this one, then run `node scripts/sync-shared.ts`.
18
+ import { randomUUID, timingSafeEqual } from "node:crypto";
19
+ import { instanceDetailsIn } from "./instance-details.js";
20
+ /**
21
+ * The argument names whose value is a version by the tool's schema, and whether a quad could be one at all: a whole-string
22
+ * dotted quad (no room around it for prose) outside the ranges a LAN or tailnet is actually reached on. An address is never
23
+ * excused by what the requester's text says around it, nor by which argument it lands in.
24
+ */
25
+ const VERSION_KEYS = /^(?:versions?|release|build|tag)$/i;
26
+ const versionValue = (v) => {
27
+ const t = v.trim();
28
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(t))
29
+ return undefined;
30
+ const [a = 0, b = 0] = t.split(".").map(Number);
31
+ return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) ? undefined : t;
32
+ };
33
+ /**
34
+ * Instance details in a GitHub write (a conn.tool card on the github connection: a comment, an issue, a review): a tailnet
35
+ * host (*.ts.net), a home-directory path, or an IPv4 address other than loopback. A GitHub thread is outside the instance and
36
+ * often public, and no issue or review needs these, so code refuses it itself: a model once approved a triage comment that
37
+ * pasted the host, its address and a runner log path as "in scope". (github-mcp's scrub redacts owner data from the
38
+ * comments when they are sent; this is the refusal before that, for every GitHub write.) The kernel runs it before it asks the
39
+ * reviewer (review-loop.ts), so it never fails open; the reviewer runs it too (review.ts).
40
+ */
41
+ export function instanceDetails(card, diff, toolCall) {
42
+ if (card?.action !== "conn.tool")
43
+ return [];
44
+ // A tool call's arguments arrive structured (`tool_call`), and the card's details text rides in `diff` for a provider that
45
+ // doesn't read `tool_call` yet. Both are read the same way, decoded: the details' JSON tail is parsed back and walked too, so
46
+ // an argument the schema names (`version`) is recognised in either form — never left to the JSON escaping, which once hid both
47
+ // a newline and the argument a value sat under. A details tail that isn't JSON (a truncated or older shape) is scanned as the
48
+ // text it is, so nothing is dropped.
49
+ const parts = [];
50
+ // The call's own version numbers, by argument name: the only dotted quads the scan may read as versions. A heading in the
51
+ // requester's text is never proof (`Build:` above an address is a copied build server's address, not a build number).
52
+ const versions = new Set();
53
+ if (toolCall && toolCall.connection !== "github")
54
+ return [];
55
+ if (toolCall)
56
+ walkArguments(toolCall.arguments, parts, versions);
57
+ const details = String(diff ?? "");
58
+ if (!toolCall && !/^tool: github\./.test(details))
59
+ return [];
60
+ const tail = /^tool: github\.[^\n]*\narguments \(written by the requesting agent\): ([\s\S]*)$/.exec(details)?.[1];
61
+ let parsed;
62
+ try {
63
+ parsed = tail === undefined ? undefined : JSON.parse(tail.trim());
64
+ }
65
+ catch {
66
+ parsed = undefined;
67
+ }
68
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
69
+ // The same arguments in both forms are read once; details that differ from the structured call are read too, never trusted.
70
+ if (!toolCall || JSON.stringify(parsed) !== JSON.stringify(toolCall.arguments))
71
+ walkArguments(parsed, parts, versions);
72
+ }
73
+ else if (!toolCall)
74
+ parts.push(details);
75
+ return instanceDetailsIn(parts.join("\n"), versions);
76
+ }
77
+ /**
78
+ * One argument object's keys and string values, decoded, pushed into `parts`, and the value of a version-named argument into
79
+ * `versions`. Walked with an explicit stack, not recursion: this runs in the kernel before the reviewer's own depth check, and
80
+ * an argument object is the requester's to shape, so a deep one must not overflow the stack it is scanned on. A value seen
81
+ * twice (a shared reference, or a cycle only a direct caller could build) is read once. Each argument's value is read once, in
82
+ * bounded time: nothing here scans the text accumulated so far.
83
+ */
84
+ function walkArguments(args, parts, versions) {
85
+ const seen = new Set();
86
+ const stack = [];
87
+ const open = (v) => {
88
+ if (!v || typeof v !== "object" || seen.has(v))
89
+ return;
90
+ seen.add(v);
91
+ for (const [k, child] of Object.entries(v)) {
92
+ parts.push(k);
93
+ // The schema, not a line of the requester's prose, says which argument is a version: a dotted quad that is the whole
94
+ // value of `version` (or `versions`) is that report's version, wherever an agent's log quotes it back.
95
+ if (typeof child !== "string")
96
+ stack.push(child);
97
+ else {
98
+ parts.push(child);
99
+ const version = VERSION_KEYS.test(k) ? versionValue(child) : undefined;
100
+ if (version)
101
+ versions.add(version);
102
+ }
103
+ }
104
+ };
105
+ open(args);
106
+ while (stack.length) {
107
+ const v = stack.pop();
108
+ if (typeof v === "string")
109
+ parts.push(v);
110
+ else
111
+ open(v);
112
+ }
113
+ }
22
114
  /** The request fields a reviewer reads; anything else in a request (a policy, a model) is dropped. */
23
- export const REQUEST_FIELDS = ["card", "diff", "files", "chain", "siblings", "sources", "decisions", "requesterModel", "panel", "previous", "relift", "evidence"];
115
+ export const REQUEST_FIELDS = ["card", "diff", "tool_call", "files", "chain", "requesterModel", "comments", "productCommits"];
116
+ /** The longest a working review waits between keepalives to the kernel. */
117
+ const BEAT_MS = 60_000;
118
+ /** A beat the kernel never got is sent again at most this many times, with backoff (1 s, 2 s, 4 s), unless the review is over. */
119
+ const KEEPALIVE_TRIES = 3;
24
120
  /**
25
- * A handler for POST `<path>/review`: answers and returns true, or returns false for any other path. It accepts at once and
26
- * sends the verdict to the kernel with the review's token (retried; a verdict the kernel no longer waits for is dropped).
27
- * A reviewer that throws sends `{ error }`: the requester counts it as a failed review (reviewer_failed) and tries again later.
121
+ * A handler for POST `<path>/review`: answers and returns true, or returns false for any other path. It accepts at once, naming
122
+ * the service instance that took the review (a fresh one each start, so the kernel fails what a recreated service lost; an answer
123
+ * without one is still accepted), and sends the verdict to the kernel with the review's token (retried; a verdict the kernel no
124
+ * longer waits for is dropped). While the review's work advances it keeps the review alive (at most once per BEAT_MS): the kernel
125
+ * bounds a review by progress, not only by its hour, so a call that hangs — and reports nothing — still stalls. GET `<path>/healthz`
126
+ * answers `{ ok: true, instance }`. A reviewer that throws sends `{ error }`: the requester counts it as a failed review
127
+ * (reviewer_failed) and tries again later.
28
128
  */
29
- export function serveReviewer(review, { key, kernelUrl = process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130", path = "/aidenhq/v1/reviewer", log = () => { } }) {
129
+ export function serveReviewer(review, { key, kernelUrl = process.env.AIDENHQ_KERNEL_URL ?? "http://10.231.0.1:3130", path = "/aidenhq/v1/reviewer", instance = randomUUID(), beatMs = BEAT_MS, log = () => { } }) {
30
130
  const send = (res, status, body) => void res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
31
131
  const keyed = (req) => {
32
132
  const a = Buffer.from(String(req.headers.authorization ?? "").replace(/^Bearer\s+/i, "")), b = Buffer.from(key);
33
133
  return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
34
134
  };
135
+ /** A reviewer's failure as the error answer: `null`, `undefined` or a bare string is a failure too, and never a crash. */
136
+ const failed = (e) => {
137
+ // An Error's message, or a rejection that is itself text; anything else (`null`, `undefined`, a bare object) is a failure
138
+ // with nothing to say, and answers the generic reason rather than "[object Object]".
139
+ const m = e?.message;
140
+ const said = typeof m === "string" && m.trim() ? m : typeof e === "string" && e.trim() ? e : "the reviewer failed";
141
+ return { error: said.slice(0, 300) };
142
+ };
35
143
  async function deliver(id, token, v) {
36
144
  for (let i = 0; i < 5; i++) {
37
145
  const r = await fetch(`${kernelUrl}/v1/reviews/${id}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(v), signal: AbortSignal.timeout(15_000) }).catch(() => undefined);
@@ -41,7 +149,65 @@ export function serveReviewer(review, { key, kernelUrl = process.env.AIDENHQ_KER
41
149
  }
42
150
  log("verdict not delivered", { id });
43
151
  }
44
- return async function handle(req, res) {
152
+ /**
153
+ * A review's progress: its work moving (in-process, free) and a keepalive to the kernel at most every BEAT_MS. Progress inside
154
+ * the throttle is not dropped: it schedules one trailing keepalive for when the throttle ends, so the kernel's window counts from
155
+ * the last step that actually happened. A call that hangs reports nothing — it only ever gets that one trailing beat, not a clock.
156
+ */
157
+ const progressOf = (id, token) => {
158
+ // A monotonic clock, like the kernel's own windows: a wall-clock step must not delay or hurry a keepalive.
159
+ const clock = () => performance.now();
160
+ let until = clock();
161
+ let trailing;
162
+ // `stop` runs when the work is over: a beat queued or retried from before must not outlive the review.
163
+ let stopped = false;
164
+ // One more try at this same beat, if the review is still running and the tries are not spent: backoff 1 s, then 2 s, then 4 s.
165
+ const again = (attempt) => {
166
+ if (!stopped && attempt < KEEPALIVE_TRIES)
167
+ setTimeout(() => keepalive(attempt + 1), 1_000 * 2 ** attempt).unref?.();
168
+ };
169
+ const keepalive = (attempt = 0) => {
170
+ if (stopped)
171
+ return;
172
+ fetch(`${kernelUrl}/v1/reviews/${id}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: '{"keepalive":true}', signal: AbortSignal.timeout(10_000) })
173
+ .then((r) => {
174
+ // The kernel no longer waits for this review (it stalled, hit its hour, or was failed by a restart): its token is
175
+ // closed, so there is nothing left to keep alive. 404 is that answer; any other status reached the kernel.
176
+ if (r.status === 404)
177
+ return void (stopped = true);
178
+ // A beat the kernel answered with a transient failure (a gateway in front of it: 502, 503, 504, or a throttle) never
179
+ // registered, and `fetch` resolves on it. Retried like a lost one: two long model rounds apart by a 503 must not fail a
180
+ // review that is working. Any other answer did reach the kernel and counted.
181
+ if (r.status === 429 || r.status >= 500)
182
+ again(attempt);
183
+ })
184
+ // A beat lost to a reset or a timeout is retried the same way: a window with no beat at all would fail a review whose work
185
+ // is fine. Stops when the review is over.
186
+ .catch(() => again(attempt));
187
+ };
188
+ const beat = () => {
189
+ clearTimeout(trailing);
190
+ trailing = undefined;
191
+ until = clock() + beatMs;
192
+ keepalive();
193
+ };
194
+ const progress = () => {
195
+ const now = clock();
196
+ if (now >= until)
197
+ return beat();
198
+ // Suppressed progress: one trailing beat at the end of the throttle, however many steps arrive in it.
199
+ if (!trailing)
200
+ trailing = setTimeout(beat, until - now);
201
+ trailing.unref?.();
202
+ };
203
+ // The work is over (its verdict is on its way): a beat queued for the end of the throttle, or a retry of a lost one, must
204
+ // not outlive it.
205
+ const stop = () => { stopped = true; clearTimeout(trailing); trailing = undefined; };
206
+ return Object.assign(progress, { stop });
207
+ };
208
+ const handle = Object.assign(async (req, res) => {
209
+ if (req.url === `${path}/healthz`)
210
+ return send(res, 200, { ok: true, instance }), true;
45
211
  if (String(req.url ?? "") !== `${path}/review`)
46
212
  return false;
47
213
  if (req.method !== "POST")
@@ -59,6 +225,8 @@ export function serveReviewer(review, { key, kernelUrl = process.env.AIDENHQ_KER
59
225
  chunks.push(c);
60
226
  }
61
227
  body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
228
+ if (!body || typeof body !== "object")
229
+ throw new Error("send {id, token, model_token, request}");
62
230
  }
63
231
  catch (e) {
64
232
  return send(res, 400, { error: e.message }), true;
@@ -68,10 +236,18 @@ export function serveReviewer(review, { key, kernelUrl = process.env.AIDENHQ_KER
68
236
  return send(res, 400, { error: "send {id, token, model_token, request}" }), true;
69
237
  // Only the fields a reviewer reads, each only when the requester sent it: an absent field keeps the reviewer's default.
70
238
  const request = Object.fromEntries(REQUEST_FIELDS.filter((k) => body.request[k] !== undefined).map((k) => [k, body.request[k]]));
71
- send(res, 202, { accepted: true });
72
- let marked = false;
73
- const v = await review(request, { modelToken, onPanel: async () => { marked = true; } }).catch((e) => ({ error: String(e.message ?? e).slice(0, 300) }));
74
- await deliver(id, token, "error" in v ? v : { ...v, ...(marked ? { panel_marked: true } : {}) });
239
+ send(res, 202, { accepted: true, instance });
240
+ // A throw from the reviewer — or a promise rejecting with nothing at all — still sends its error back (a failed review),
241
+ // never a review left waiting on a verdict, and never a rejection of this handler that nobody reads.
242
+ const progress = progressOf(id, token);
243
+ // The error answer is built before `finally` clears the progress, and a failing error handler still leaves it an answer.
244
+ const v = await (async () => review(request, { modelToken, progress }))()
245
+ .catch(failed)
246
+ .then((r) => (r && typeof r === "object" ? r : failed(r)))
247
+ .catch(() => failed("the reviewer failed"))
248
+ .finally(() => progress.stop());
249
+ await deliver(id, token, v);
75
250
  return true;
76
- };
251
+ }, { instance });
252
+ return handle;
77
253
  }
@@ -24,10 +24,17 @@ export type Row = Record<string, unknown>;
24
24
  type Upserted = "new" | "changed" | "same";
25
25
  /** CREATE TABLE for a source table: its columns plus the common ones every source row carries. */
26
26
  export declare function tableDdl(schema: string, t: Table): string;
27
+ /** What a pass reports beyond its row count (SourceStore.run). */
28
+ export type Pass = {
29
+ complete?: {
30
+ total: number;
31
+ fetched: number;
32
+ };
33
+ };
27
34
  export declare class SourceStore {
35
+ private migrated;
28
36
  readonly schema: string;
29
37
  readonly pool: pg.Pool;
30
- private migrated;
31
38
  constructor(schema: string, pool: pg.Pool);
32
39
  /**
33
40
  * The writer's store, or undefined while it can't be (no password file: the warehouse module or its secret is missing).
@@ -58,9 +65,12 @@ export declare class SourceStore {
58
65
  private upsertIn;
59
66
  /**
60
67
  * One ingest pass: records src_meta.ingest_run (rows = rows written with a difference) and rethrows a failure.
61
- * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout.
68
+ * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout. A pass that read a scope to its end and
69
+ * got a reliable count of what the source holds for it (the API's total) says so on `pass.complete`: `total` (the source's count)
70
+ * and `fetched` (distinct records the pass read). The Fleet Steward flags a scope whose completed passes keep fetching fewer.
71
+ * A pass that stopped early, resumed mid-scope or whose API gives no total leaves it unset.
62
72
  */
63
- run(source: string, scope: string, fn: () => Promise<number>, meta?: {
73
+ run(source: string, scope: string, fn: (pass: Pass) => Promise<number>, meta?: {
64
74
  commit?: string | null;
65
75
  }): Promise<number>;
66
76
  }
@@ -1,10 +1,11 @@
1
1
  // Shared sources (docs/design/sources.md): the writer side. Each source writer (slack-live,
2
- // github, jira, ops-mcp for meetings, google-workspace for docs) logs in to the warehouse as src_<source>, owns schema src_<source> (ops/warehouse-sources.sh
3
- // creates both) and writes through this: typed upserts that keep first_seen_at, bump src_meta.seq on any difference and
2
+ // github, jira, ops-mcp for meetings, google-workspace for docs) logs in to the warehouse as src_<source>, owns schema src_<source> (its module's
3
+ // warehouse.sources entry; apps-mcp creates both) and writes through this: typed upserts that keep first_seen_at, bump src_meta.seq on any difference and
4
4
  // log tracked-field changes, a baseline flag for first syncs, per-scope sync state, and one src_meta.ingest_run per pass.
5
5
  // No LLM anywhere: ingest is code.
6
6
  //
7
- // Writers import it as @aidenhq/sdk/source-store (pg is theirs: a peer dependency).
7
+ // Every module imports it from npm (@aidenhq/sdk/source-store) at an exact pin (pg is theirs: a peer dependency): a change here needs a version bump in package.json,
8
+ // which is what publishes it.
8
9
  import { readFileSync } from "node:fs";
9
10
  import pg from "pg";
10
11
  /** Long text is cut to about 4 KB by default; the row keeps a <field>_truncated flag and its url for the rest. */
@@ -66,13 +67,13 @@ CREATE INDEX IF NOT EXISTS change_entity ON ${s}.change (entity, entity_id);`;
66
67
  const asText = (v) => (v == null ? null : typeof v === "string" ? v : v instanceof Date ? v.toISOString() : JSON.stringify(v));
67
68
  const capped = (v) => capText(asText(v)).text;
68
69
  export class SourceStore {
70
+ migrated = false;
69
71
  schema;
70
72
  pool;
71
- migrated = false;
73
+ // Plain fields (no parameter properties): the warehouse search service runs this file directly with Node's type stripping.
72
74
  constructor(schema, pool) {
73
- this.schema = schema;
75
+ this.schema = ident(schema);
74
76
  this.pool = pool;
75
- ident(schema);
76
77
  }
77
78
  /**
78
79
  * The writer's store, or undefined while it can't be (no password file: the warehouse module or its secret is missing).
@@ -194,14 +195,18 @@ export class SourceStore {
194
195
  }
195
196
  /**
196
197
  * One ingest pass: records src_meta.ingest_run (rows = rows written with a difference) and rethrows a failure.
197
- * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout.
198
+ * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout. A pass that read a scope to its end and
199
+ * got a reliable count of what the source holds for it (the API's total) says so on `pass.complete`: `total` (the source's count)
200
+ * and `fetched` (distinct records the pass read). The Fleet Steward flags a scope whose completed passes keep fetching fewer.
201
+ * A pass that stopped early, resumed mid-scope or whose API gives no total leaves it unset.
198
202
  */
199
203
  async run(source, scope, fn, meta = {}) {
200
204
  const started = new Date();
201
205
  let rows = 0;
202
206
  let error = null;
207
+ const pass = {};
203
208
  try {
204
- rows = await fn();
209
+ rows = await fn(pass);
205
210
  return rows;
206
211
  }
207
212
  catch (err) {
@@ -210,7 +215,7 @@ export class SourceStore {
210
215
  }
211
216
  finally {
212
217
  await this.pool
213
- .query(`INSERT INTO src_meta.ingest_run (source, scope, started_at, rows, error, commit) VALUES ($1, $2, $3, $4, $5, $6)`, [source, scope, started, rows, error, meta.commit || null])
218
+ .query(`INSERT INTO src_meta.ingest_run (source, scope, started_at, rows, error, commit, total, fetched) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [source, scope, started, rows, error, meta.commit || null, error ? null : (pass.complete?.total ?? null), error ? null : (pass.complete?.fetched ?? null)])
214
219
  .catch(() => undefined);
215
220
  }
216
221
  }
@@ -0,0 +1,77 @@
1
+ export type Kind = "done" | "working" | "waiting" | "idle";
2
+ export type Reason = "closed" | "cancelled" | "job_running" | "job_queued" | "job_held" | "card_review" | "card_owner" | "owner_wait" | "delegator_wait" | "handback" | "owner_task" | "blocked" | "agent_wait" | "module_wait" | "scheduled" | "chat_turn" | "backlog" | "failed" | "unpolled" | "orphaned" | "unknown" | "history_expired";
3
+ export type Attention = {
4
+ who: "owner" | "agent" | "reviewer";
5
+ why: "card" | "owner_wait" | "delegator_wait" | "handback" | "failed" | "stalled_wait" | "unpolled" | "orphaned" | "unknown" | "history_expired";
6
+ ref: string; /** When what it names began (the board orders asks by it). */
7
+ since: string;
8
+ };
9
+ /** The board's column for a task (its Agent work layout): one per task, from all its obligations (laneOf). */
10
+ export type Lane = "needs_you" | "working" | "waiting" | "blocked" | "idle" | "done";
11
+ export type TaskState = {
12
+ kind: Kind;
13
+ reason: Reason;
14
+ ref?: string;
15
+ since: string;
16
+ holder: string | null;
17
+ attention: Attention[];
18
+ lane: Lane;
19
+ /** An open blocker (`task:<id>`), whatever the representative reason: a queued job or a wait can outrank it. */
20
+ blocker?: string;
21
+ /** A module stage's label, only while working or waiting. */
22
+ stage?: string;
23
+ /** The open owner or delegator wait's question (the ask gate reads it). */
24
+ question?: string;
25
+ /** What the open wait's question is about (notify's `detail`, e.g. the draft to send), beside the question. */
26
+ detail?: string;
27
+ /** When the open owner or delegator wait began, whatever the representative reason (only the owner's has a `question`). */
28
+ wait_since?: string;
29
+ /** The open owner or delegator wait's own deadline (`until`), so a retry of its question reuses the wait instead of re-arming it. */
30
+ wait_until?: string;
31
+ /** The open wait's own words (task_wait's reason). */
32
+ note?: string;
33
+ /** When the earliest open scheduled wake is due, whatever the representative reason. */
34
+ scheduled_for?: string;
35
+ /** The agent (id) an open delegator wait's question went to, when the wait recorded it. */
36
+ waits_on?: string;
37
+ /** An open delegator wait re-asking a question this task already had answered (it settled that episode): the Steward's incident
38
+ * detector does not raise it again while this wait stands, and a genuinely new question carries none. */
39
+ ask_settled?: true;
40
+ /** When the task was last reopened (a status leaving done or cancelled), while it is open: a close needs evidence newer than this. */
41
+ reopened_at?: string;
42
+ };
43
+ /**
44
+ * `origin`: what created the task (`task.created` `data.origin`): a routine's `routine_execution`, a module's `module:<key>`,
45
+ * or null for one a person or an agent made. `holder_name` and `holder_gone` name a holder Paperclip reports terminated (a
46
+ * holder no grant maps stays its raw id).
47
+ */
48
+ export type StateRow = TaskState & {
49
+ task: string;
50
+ identifier: string | null;
51
+ idle_wakes: number;
52
+ origin: string | null;
53
+ holder_name?: string;
54
+ holder_gone?: true;
55
+ };
56
+ export type StateRead = {
57
+ as_of: string;
58
+ tasks: StateRow[];
59
+ counts: {
60
+ needs_you: number;
61
+ failed: number;
62
+ unexplained_idle: number;
63
+ };
64
+ };
65
+ /**
66
+ * What the kernel's issue mirror last recorded of a task from Paperclip (GET /v1/tasks/issues): its identifier, title, status,
67
+ * agent assignee (id), parent (id) and Paperclip's updatedAt. A task the kernel has never seen has no row.
68
+ */
69
+ export type IssueRow = {
70
+ id: string;
71
+ identifier: string | null;
72
+ title: string | null;
73
+ status: string | null;
74
+ assignee: string | null;
75
+ parent: string | null;
76
+ updated_at: string | null;
77
+ };
@@ -0,0 +1,4 @@
1
+ // A task's state as the kernel serves it (GET /v1/tasks/state): the one definition of its shape. The kernel computes it
2
+ // (kernel/src/task-state.ts, task-state-read.ts); the board reads it through its copy (services/board/src/aidenhq-sdk/,
3
+ // kept identical by scripts/sync-shared.ts). Types only: no imports, no code.
4
+ export {};