teamhandbook-orchestrator 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/main.mjs CHANGED
@@ -4084,7 +4084,7 @@ function claudeCodeDecoder(asked = null, work, opened = asked ? CLAUDE_MODE[aske
4084
4084
  if (part?.type === "text" && typeof part.text === "string" && part.text.trim()) return [{ type: "message", text: part.text.trim() }];
4085
4085
  if (part?.type === "tool_use" && typeof part.name === "string") {
4086
4086
  const input2 = part.input && typeof part.input === "object" ? part.input : {};
4087
- const target = [input2.file_path, input2.pattern, input2.path].find((v) => typeof v === "string");
4087
+ const target = part.name === "Skill" ? input2.skill : [input2.file_path, input2.pattern, input2.path].find((v) => typeof v === "string");
4088
4088
  const call = { tool: part.name, target: shownTarget(work, typeof target === "string" ? target : null), ...part.name === "Bash" && typeof input2.command === "string" ? { command: input2.command } : {}, input: input2 };
4089
4089
  const id = typeof part.id === "string" && part.id ? part.id : null;
4090
4090
  if (id) calls.set(id, call);
@@ -4201,7 +4201,7 @@ function taskList(call, output, tasks) {
4201
4201
  var KIND = { Bash: "command", Read: "file-read", Glob: "file-read", Grep: "file-read", Edit: "file-change", Write: "file-change", NotebookEdit: "file-change" };
4202
4202
  var requestKind = (tool) => KIND[tool] ?? (tool.startsWith("mcp__") ? "mcp" : "permission");
4203
4203
  function callSummary(tool, input) {
4204
- const target = ["command", "file_path", "path", "pattern", "url", "query"].map((k) => input[k]).find((v) => typeof v === "string");
4204
+ const target = ["command", "file_path", "path", "pattern", "url", "query", "skill"].map((k) => input[k]).find((v) => typeof v === "string");
4205
4205
  return typeof target === "string" ? target : tool;
4206
4206
  }
4207
4207
  var DECLINED = "The person reviewing this task declined this call.";
@@ -4452,11 +4452,13 @@ var targetOf = (input) => {
4452
4452
  return typeof target === "string" ? target : null;
4453
4453
  };
4454
4454
  var record2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
4455
+ var SKILL_TOOL = "skill";
4455
4456
  var BOOKKEEPING2 = /* @__PURE__ */ new Set(["todowrite", "todoread"]);
4456
4457
  function callEvent2(id, tool, input, status2, work, servers = []) {
4457
4458
  if (BOOKKEEPING2.has(tool)) return [];
4458
4459
  const mcp = opencodeMcp(tool, servers);
4459
- return [{ type: "tool_call", id, tool, target: shownTarget(work, targetOf(input)), ...mcp ? { mcp } : {}, ...tool === "bash" && typeof input.command === "string" ? { command: input.command } : {}, status: status2 }];
4460
+ const target = tool === SKILL_TOOL ? typeof input.name === "string" ? input.name : null : shownTarget(work, targetOf(input));
4461
+ return [{ type: "tool_call", id, tool, target, ...mcp ? { mcp } : {}, ...tool === "bash" && typeof input.command === "string" ? { command: input.command } : {}, status: status2 }];
4460
4462
  }
4461
4463
  function shellLines(id, output, sent, ended4) {
4462
4464
  const from = output.length < sent ? 0 : sent;
@@ -4800,7 +4802,7 @@ function opencode2ServeCodec(sessionID, work, questions = false, servers = []) {
4800
4802
  const tokens = data.tokens ?? {};
4801
4803
  const cache = tokens.cache ?? {};
4802
4804
  const input = tokensOf(tokens.input, cache.read, cache.write);
4803
- return [...context(input), { type: "usage", cost: { usd: null, inputTokens: input, outputTokens: tokensOf(tokens.output, tokens.reasoning) } }];
4805
+ return [...context(input), { type: "usage", cost: { usd: num(data.cost), inputTokens: input, outputTokens: tokensOf(tokens.output, tokens.reasoning) } }];
4804
4806
  }
4805
4807
  case "session.retry.scheduled":
4806
4808
  return [{ type: "error", failure: error2Failure(data.error, "provider_retrying") }];
@@ -5234,2186 +5236,2261 @@ import { execFile as execFile5 } from "node:child_process";
5234
5236
  // server/app.ts
5235
5237
  import { rm as rm6, stat as stat4 } from "node:fs/promises";
5236
5238
 
5237
- // server/store.ts
5238
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
5239
+ // server/vault.ts
5240
+ var NO_VAULT = "this orchestrator keeps no sign-ins, tokens or other secrets until whoever runs it sets ORCHESTRATOR_SECRET_KEY (32 random bytes, as from openssl rand -base64 32) and starts it again";
5241
+ async function storeSecret(store, vault, tenant, name, value, by) {
5242
+ if (!vault) throw new Error(NO_VAULT);
5243
+ await store.putSecret(tenant, name, vault.seal(tenant, name, value), by);
5244
+ }
5245
+ var SEALED_WITHOUT_KEY = "a forge token is stored for this repository, but ORCHESTRATOR_SECRET_KEY is not set; start the orchestrator with the key it was sealed with, or save the token again";
5246
+ async function readSecret(store, vault, tenant, name) {
5247
+ const sealed = await store.getSecret(tenant, name);
5248
+ if (sealed === null) return null;
5249
+ if (!vault) throw new Error(SEALED_WITHOUT_KEY);
5250
+ return vault.open(tenant, name, sealed);
5251
+ }
5252
+ function maskSecrets(text, secrets) {
5253
+ let out = text;
5254
+ for (const secret of secrets) {
5255
+ if (secret && secret.length >= 4) out = out.split(secret).join("***");
5256
+ }
5257
+ return out;
5258
+ }
5239
5259
 
5240
- // server/tasks/log-bus.ts
5241
- import { EventEmitter } from "node:events";
5242
- var bus = new EventEmitter();
5243
- bus.setMaxListeners(0);
5260
+ // server/forge/own-cli.ts
5261
+ import { execFile as execFile3 } from "node:child_process";
5262
+ import { rm as rm3 } from "node:fs/promises";
5263
+ import { tmpdir as tmpdir2 } from "node:os";
5244
5264
 
5245
- // server/runner-auth.ts
5246
- import { createHash as createHash2, createPublicKey, randomBytes as randomBytes2, sign, verify } from "node:crypto";
5247
- var RUNNER_PROTOCOL = 1;
5248
- var SIGNATURE_HEADER = "x-runner-signature";
5249
- function canonical(call) {
5250
- const body = createHash2("sha256").update(call.body).digest("hex");
5251
- return Buffer.from(["v1", call.method.toUpperCase(), call.path, String(call.time), call.nonce, body].join("\n"));
5252
- }
5253
- function signRunnerRequest(privateKey, call) {
5254
- const signed = { ...call, time: call.time ?? Math.floor(Date.now() / 1e3), nonce: call.nonce ?? randomBytes2(16).toString("base64url") };
5255
- return `v1 t=${signed.time} n=${signed.nonce} s=${sign(null, canonical(signed), privateKey).toString("base64url")}`;
5265
+ // shared/forge-def.ts
5266
+ var HOSTED_FORGES = ["gitlab", "github", "gitea"];
5267
+ var segments = (path) => path.split("/").map(encodeURIComponent).join("/");
5268
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
5269
+ var FORGES = {
5270
+ gitlab: {
5271
+ kind: "gitlab",
5272
+ label: "GitLab",
5273
+ capabilities: { term: "merge request", review: "approve-only", checksAlwaysReport: true, templates: [".gitlab/merge_request_templates/Default.md", ".gitlab/merge_request_templates/*.md"] },
5274
+ projectShape: "group/project",
5275
+ homeHosts: ["gitlab.com"],
5276
+ gitUser: "oauth2",
5277
+ allowsHost: () => true,
5278
+ apiUrlFor: (origin) => `${origin.origin}/api/v4`,
5279
+ requestRef: (number) => `refs/merge-requests/${number}/head`,
5280
+ newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/-/merge_requests/new?${new URLSearchParams({ "merge_request[source_branch]": branch, "merge_request[target_branch]": target })}`,
5281
+ // GitLab has no narrower scope that opens merge requests than api.
5282
+ credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/-/user_settings/personal_access_tokens?name=TeamHandbook&scopes=api`, scopes: ["api"] },
5283
+ visibilities: ["private", "internal", "public"],
5284
+ group: { label: "Group (optional)", placeholder: "acme/platform", meaning: "The group or subgroup the repository is made in; left empty, the connected account's own namespace holds it." },
5285
+ emptyListHint: "Give the GitLab account you connected access to the team's repository, then read the list again."
5286
+ },
5287
+ github: {
5288
+ kind: "github",
5289
+ label: "GitHub",
5290
+ capabilities: { term: "pull request", review: "approve-or-request-changes", checksAlwaysReport: false, templates: [".github/pull_request_template.md", "pull_request_template.md", "docs/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE/*.md"] },
5291
+ projectShape: "owner/repository",
5292
+ homeHosts: ["github.com"],
5293
+ gitUser: "x-access-token",
5294
+ allowsHost: (hostname4) => hostname4 === "github.com" || LOOPBACK_HOSTS.has(hostname4),
5295
+ apiUrlFor: (origin) => LOOPBACK_HOSTS.has(origin.hostname) ? `${origin.origin}/api` : "https://api.github.com",
5296
+ requestRef: (number) => `refs/pull/${number}/head`,
5297
+ newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/compare/${segments(target)}...${segments(branch)}?expand=1`,
5298
+ credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/settings/personal-access-tokens/new`, scopes: ["Contents: read and write", "Pull requests: read and write", "Commit statuses: read and write", "Metadata: read"] },
5299
+ visibilities: ["private", "public"],
5300
+ group: null,
5301
+ emptyListHint: "Where the app is installed on chosen repositories only, add the team's repository to its installation on GitHub, then read the list again."
5302
+ },
5303
+ /*
5304
+ * Gitea, and Forgejo, which keeps Gitea's API, from 1.20, where a branch is made at a commit and
5305
+ * files are written to an empty repository. Read from Gitea 1.22's source: git takes the token as
5306
+ * the password beside any user name; a description template is looked for at the root, then under
5307
+ * .gitea/, then .github/.
5308
+ */
5309
+ gitea: {
5310
+ kind: "gitea",
5311
+ label: "Gitea",
5312
+ capabilities: {
5313
+ term: "pull request",
5314
+ review: "approve-or-request-changes",
5315
+ checksAlwaysReport: false,
5316
+ templates: ["PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/pull_request_template.md"]
5317
+ },
5318
+ projectShape: "owner/repository",
5319
+ homeHosts: ["gitea.com", "codeberg.org"],
5320
+ gitUser: "oauth2",
5321
+ allowsHost: () => true,
5322
+ apiUrlFor: (origin) => `${origin.origin}/api/v1`,
5323
+ requestRef: (number) => `refs/pull/${number}/head`,
5324
+ newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/compare/${segments(target)}...${segments(branch)}`,
5325
+ credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/user/settings/applications`, scopes: ["write:repository", "write:issue", "read:user"] },
5326
+ visibilities: ["private", "public"],
5327
+ group: { label: "Organization (optional)", placeholder: "acme", meaning: "The organization the repository is made in; left empty, the account whose token is connected owns it." },
5328
+ emptyListHint: "Give the Gitea account whose token is connected access to the team's repository, then read the list again."
5329
+ }
5330
+ };
5331
+ function isHostedForge(value) {
5332
+ return typeof value === "string" && HOSTED_FORGES.includes(value);
5256
5333
  }
5257
- var ED25519_SPKI = Buffer.from("302a300506032b6570032100", "hex");
5258
5334
 
5259
- // shared/runner-wire.ts
5260
- var PROTOCOL_HEADER = "x-runner-protocol";
5261
- var POLL_WAIT_MAX_MS = 25e3;
5262
- var EVENTS_PER_BATCH = 500;
5263
- var BATCH_BYTES = 512 * 1024;
5264
- var COMMAND_MAX = 300;
5265
- var PLAN_TEXT_MAX = 2e4;
5266
- var TESTS_OUTPUT = "tests";
5267
- var OUTPUT_LINES_MAX = 200;
5268
- var OUTPUT_LINE_MAX = 2e3;
5269
- var PATCH_LINES_MAX = 40;
5270
- var TODOS_MAX = 30;
5271
- var TODO_TEXT_MAX = 200;
5272
- var CALL_BYTES = 1024 * 1024;
5273
- var RUNNER_PATHS = {
5274
- hello: "/api/runner/hello",
5275
- claim: "/api/runner/claim",
5276
- /** The machine disconnects itself: the orchestrator revokes it, so its token works nowhere after. */
5277
- disconnect: "/api/runner/disconnect",
5278
- poll: "/api/runner/poll",
5279
- /** What the machine says of its agents, at start and every few minutes: words only, never an account. */
5280
- status: "/api/runner/status",
5281
- renew: (taskId) => `/api/runner/tasks/${taskId}/renew`,
5282
- events: (taskId) => `/api/runner/tasks/${taskId}/events`,
5283
- agentRequest: (taskId) => `/api/runner/tasks/${taskId}/requests`,
5284
- progress: (taskId) => `/api/runner/tasks/${taskId}/progress`,
5285
- forgeRequest: (taskId) => `/api/runner/tasks/${taskId}/request`,
5286
- finish: (taskId) => `/api/runner/tasks/${taskId}/finish`,
5287
- /** The follow-ups that reached the task's agent. */
5288
- followUpsDelivered: (taskId) => `/api/runner/tasks/${taskId}/follow-ups`,
5289
- /** One of the task's attachments, its bytes, for the machine to put in the task's own folder. */
5290
- attachment: (taskId, attachmentId) => `/api/runner/tasks/${taskId}/attachments/${attachmentId}`,
5291
- /** The machine's answer to one folder list its person's screen asked it for. */
5292
- folders: (nonce) => `/api/runner/folders/${nonce}`,
5293
- /** The machine's answer to one undo of a task's change in one of its folders. */
5294
- undo: (nonce) => `/api/runner/undos/${nonce}`,
5295
- /** The machine's answer to one lesson it was handed for its person's review queue. */
5296
- lessons: (nonce) => `/api/runner/lessons/${nonce}`,
5297
- /** The machine's reading of one folder project's checks. */
5298
- checks: (nonce) => `/api/runner/checks/${nonce}`,
5299
- /** The machine's answer to one read or decision of a lesson its person asked for on a task's page. */
5300
- lessonOps: (nonce) => `/api/runner/lesson-ops/${nonce}`,
5301
- pushes: (nonce) => `/api/runner/pushes/${nonce}`
5335
+ // server/forge/http.ts
5336
+ import { AsyncLocalStorage } from "node:async_hooks";
5337
+ import { createHash as createHash2 } from "node:crypto";
5338
+
5339
+ // server/forge/forge-metrics.ts
5340
+ var OPERATIONS = [
5341
+ [/\/(merge_requests|pulls)(\/|\?|$)/, "request"],
5342
+ [/\/(approvals|reviews)(\/|\?|$)/, "review"],
5343
+ [/\/(statuses|status|check-runs)(\/|\?|$)/, "checks"],
5344
+ [/\/repository\/commits|\/git\/commits/, "commit"],
5345
+ [/\/repository\/files|\/contents\//, "file"],
5346
+ [/\/repository\/(branches|tags)|\/(branches|tags)(\/|\?|$)|\/git\/ref/, "ref"],
5347
+ [/\/git\/trees/, "tree"],
5348
+ [/\/hooks(\/|\?|$)/, "hook"],
5349
+ [/\/users?(\/|\?|$)|\/namespaces\//, "account"],
5350
+ [/\/installation|\/app\//, "installation"],
5351
+ [/^\/(projects|orgs\/[^/]+\/repos|repos\/[^/]+\/[^/]+)(\?|$)/, "repository"]
5352
+ ];
5353
+ function operationOf(method, path) {
5354
+ const verb = /^(GET|POST|PUT|PATCH|DELETE)$/.test(method) ? method.toLowerCase() : "other";
5355
+ return `${verb} ${OPERATIONS.find(([pattern]) => pattern.test(path))?.[1] ?? "other"}`;
5356
+ }
5357
+ function statusClass(status2) {
5358
+ if (status2 === 0) return "unreachable";
5359
+ if (status2 === 429) return "429";
5360
+ return `${Math.floor(status2 / 100)}xx`;
5361
+ }
5362
+ var ForgeMeter = class {
5363
+ calls = /* @__PURE__ */ new Map();
5364
+ quota = /* @__PURE__ */ new Map();
5365
+ called(forge, host, operation, status2) {
5366
+ const key = [forge, host, operation, status2].join("\0");
5367
+ this.calls.set(key, (this.calls.get(key) ?? 0) + 1);
5368
+ }
5369
+ reported(forge, host, remaining, limit) {
5370
+ this.quota.set(`${forge}\0${host}`, { remaining, limit });
5371
+ }
5302
5372
  };
5303
- var FOLDER_TEXT_MAX = 1024;
5373
+ var forgeMeter = new ForgeMeter();
5304
5374
 
5305
- // server/store.ts
5306
- var BASE_TABLES = `
5307
- CREATE TABLE IF NOT EXISTS repos (
5308
- tenant TEXT NOT NULL,
5309
- id TEXT NOT NULL,
5310
- team TEXT NOT NULL,
5311
- name TEXT NOT NULL,
5312
- url TEXT NOT NULL,
5313
- head TEXT,
5314
- synced_at TEXT,
5315
- error TEXT,
5316
- PRIMARY KEY (tenant, id)
5317
- );
5318
- CREATE TABLE IF NOT EXISTS requests (
5319
- tenant TEXT NOT NULL,
5320
- repo_id TEXT NOT NULL,
5321
- number INTEGER NOT NULL,
5322
- provider TEXT NOT NULL,
5323
- url TEXT NOT NULL,
5324
- branch TEXT NOT NULL,
5325
- head_sha TEXT NOT NULL,
5326
- title TEXT NOT NULL,
5327
- status TEXT NOT NULL,
5328
- created_at TEXT NOT NULL,
5329
- created_by TEXT NOT NULL,
5330
- PRIMARY KEY (tenant, repo_id, number)
5331
- );
5332
- CREATE TABLE IF NOT EXISTS request_numbers (
5333
- tenant TEXT NOT NULL,
5334
- repo_id TEXT NOT NULL,
5335
- last INTEGER NOT NULL,
5336
- PRIMARY KEY (tenant, repo_id)
5337
- );
5338
- CREATE TABLE IF NOT EXISTS settings (
5339
- tenant TEXT NOT NULL,
5340
- key TEXT NOT NULL,
5341
- value TEXT NOT NULL,
5342
- PRIMARY KEY (tenant, key)
5343
- );
5344
- CREATE TABLE IF NOT EXISTS ingest_ids (
5345
- id TEXT PRIMARY KEY,
5346
- tenant TEXT NOT NULL,
5347
- repo_id TEXT NOT NULL,
5348
- UNIQUE (tenant, repo_id)
5349
- );
5350
- CREATE TABLE IF NOT EXISTS usage_counts (
5351
- tenant TEXT NOT NULL,
5352
- repo_id TEXT NOT NULL,
5353
- skill TEXT NOT NULL,
5354
- hour TEXT NOT NULL,
5355
- count INTEGER NOT NULL,
5356
- PRIMARY KEY (tenant, repo_id, skill, hour)
5357
- );
5358
- CREATE TABLE IF NOT EXISTS users (
5359
- tenant TEXT NOT NULL,
5360
- id TEXT NOT NULL,
5361
- email TEXT NOT NULL,
5362
- name TEXT NOT NULL,
5363
- role TEXT NOT NULL,
5364
- password_hash TEXT,
5365
- oidc_issuer TEXT,
5366
- oidc_subject TEXT,
5367
- forge_login TEXT,
5368
- created_at TEXT NOT NULL,
5369
- PRIMARY KEY (tenant, id)
5370
- );
5371
- CREATE UNIQUE INDEX IF NOT EXISTS users_email ON users (tenant, email);
5372
- CREATE UNIQUE INDEX IF NOT EXISTS users_oidc ON users (tenant, oidc_issuer, oidc_subject);
5373
- CREATE TABLE IF NOT EXISTS team_owners (
5374
- tenant TEXT NOT NULL,
5375
- user_id TEXT NOT NULL,
5376
- team TEXT NOT NULL,
5377
- PRIMARY KEY (tenant, user_id, team)
5378
- );
5379
- CREATE TABLE IF NOT EXISTS sessions (
5380
- token_hash TEXT PRIMARY KEY,
5381
- tenant TEXT NOT NULL,
5382
- user_id TEXT NOT NULL,
5383
- csrf TEXT NOT NULL,
5384
- expires_at TEXT NOT NULL
5385
- );
5386
- CREATE TABLE IF NOT EXISTS oidc_logins (
5387
- state TEXT PRIMARY KEY,
5388
- tenant TEXT NOT NULL,
5389
- nonce TEXT NOT NULL,
5390
- verifier TEXT NOT NULL,
5391
- expires_at TEXT NOT NULL
5392
- );
5393
- CREATE TABLE IF NOT EXISTS secrets (
5394
- tenant TEXT NOT NULL,
5395
- name TEXT NOT NULL,
5396
- sealed TEXT NOT NULL,
5397
- updated_at TEXT NOT NULL,
5398
- updated_by TEXT NOT NULL,
5399
- PRIMARY KEY (tenant, name)
5400
- );
5401
- CREATE TABLE IF NOT EXISTS forges (
5402
- tenant TEXT NOT NULL,
5403
- repo_id TEXT NOT NULL,
5404
- kind TEXT NOT NULL,
5405
- api_url TEXT NOT NULL,
5406
- project TEXT NOT NULL,
5407
- PRIMARY KEY (tenant, repo_id)
5408
- );
5409
- CREATE TABLE IF NOT EXISTS tasks (
5410
- tenant TEXT NOT NULL,
5411
- id TEXT NOT NULL,
5412
- repo_id TEXT NOT NULL,
5413
- team TEXT NOT NULL,
5414
- title TEXT NOT NULL,
5415
- description TEXT NOT NULL,
5416
- issue_url TEXT,
5417
- issue_key TEXT,
5418
- agent TEXT NOT NULL,
5419
- status TEXT NOT NULL,
5420
- created_by TEXT NOT NULL,
5421
- created_at TEXT NOT NULL,
5422
- started_at TEXT,
5423
- finished_at TEXT,
5424
- base_sha TEXT,
5425
- tests TEXT,
5426
- cost_usd DOUBLE PRECISION,
5427
- input_tokens INTEGER,
5428
- output_tokens INTEGER,
5429
- request_number INTEGER,
5430
- error TEXT,
5431
- log_seq INTEGER NOT NULL DEFAULT 0,
5432
- pgid INTEGER,
5433
- branch TEXT,
5434
- template TEXT,
5435
- PRIMARY KEY (tenant, id)
5436
- );
5437
- CREATE TABLE IF NOT EXISTS task_log (
5438
- tenant TEXT NOT NULL,
5439
- task_id TEXT NOT NULL,
5440
- seq INTEGER NOT NULL,
5441
- at TEXT NOT NULL,
5442
- text TEXT NOT NULL,
5443
- PRIMARY KEY (tenant, task_id, seq)
5444
- );
5445
- `;
5446
- var EVENTS_TABLE = `
5447
- CREATE TABLE IF NOT EXISTS events (
5448
- tenant TEXT NOT NULL,
5449
- id TEXT NOT NULL,
5450
- at TEXT NOT NULL,
5451
- kind TEXT NOT NULL,
5452
- actor_kind TEXT NOT NULL,
5453
- actor_id TEXT,
5454
- actor_email TEXT,
5455
- actor_name TEXT,
5456
- repo_id TEXT,
5457
- subject TEXT,
5458
- detail TEXT NOT NULL,
5459
- PRIMARY KEY (tenant, id)
5460
- );
5461
- CREATE INDEX IF NOT EXISTS events_at ON events (tenant, at, id);
5462
- `;
5463
- var IDENTITY_TABLES = `
5464
- CREATE TABLE IF NOT EXISTS invites (
5465
- tenant TEXT NOT NULL,
5466
- id TEXT NOT NULL,
5467
- email TEXT NOT NULL,
5468
- role TEXT NOT NULL,
5469
- teams TEXT NOT NULL,
5470
- token_hash TEXT NOT NULL,
5471
- invited_by TEXT NOT NULL,
5472
- created_at TEXT NOT NULL,
5473
- expires_at TEXT NOT NULL,
5474
- PRIMARY KEY (tenant, id)
5475
- );
5476
- CREATE UNIQUE INDEX IF NOT EXISTS invites_email ON invites (tenant, email);
5477
- CREATE UNIQUE INDEX IF NOT EXISTS invites_token ON invites (token_hash);
5478
- CREATE TABLE IF NOT EXISTS service_accounts (
5479
- tenant TEXT NOT NULL,
5480
- id TEXT NOT NULL,
5481
- name TEXT NOT NULL,
5482
- created_by TEXT NOT NULL,
5483
- created_at TEXT NOT NULL,
5484
- PRIMARY KEY (tenant, id)
5485
- );
5486
- CREATE TABLE IF NOT EXISTS api_keys (
5487
- tenant TEXT NOT NULL,
5488
- id TEXT NOT NULL,
5489
- prefix TEXT NOT NULL,
5490
- secret_hash TEXT NOT NULL,
5491
- name TEXT NOT NULL,
5492
- owner_kind TEXT NOT NULL,
5493
- owner_id TEXT NOT NULL,
5494
- scopes TEXT NOT NULL,
5495
- created_by TEXT NOT NULL,
5496
- created_at TEXT NOT NULL,
5497
- expires_at TEXT,
5498
- last_used_at TEXT,
5499
- revoked_at TEXT,
5500
- PRIMARY KEY (tenant, id)
5501
- );
5502
- CREATE UNIQUE INDEX IF NOT EXISTS api_keys_prefix ON api_keys (prefix);
5503
- CREATE INDEX IF NOT EXISTS api_keys_owner ON api_keys (tenant, owner_kind, owner_id);
5504
- CREATE TABLE IF NOT EXISTS member_groups (
5505
- tenant TEXT NOT NULL,
5506
- user_id TEXT NOT NULL,
5507
- grp TEXT NOT NULL,
5508
- PRIMARY KEY (tenant, user_id, grp)
5509
- );
5510
- CREATE TABLE IF NOT EXISTS group_tags (
5511
- tenant TEXT NOT NULL,
5512
- grp TEXT NOT NULL,
5513
- tag TEXT NOT NULL,
5514
- PRIMARY KEY (tenant, grp)
5515
- );
5516
- CREATE TABLE IF NOT EXISTS member_tags (
5517
- tenant TEXT NOT NULL,
5518
- user_id TEXT NOT NULL,
5519
- tag TEXT NOT NULL,
5520
- PRIMARY KEY (tenant, user_id, tag)
5521
- );
5522
- `;
5523
- var DOMAINS_TABLE = `
5524
- CREATE TABLE IF NOT EXISTS sso_domains (
5525
- tenant TEXT NOT NULL,
5526
- domain TEXT NOT NULL,
5527
- token TEXT NOT NULL,
5528
- added_by TEXT NOT NULL,
5529
- added_at TEXT NOT NULL,
5530
- verified_at TEXT,
5531
- PRIMARY KEY (tenant, domain)
5532
- );
5533
- `;
5534
- var CLOUD_IDENTITY_TABLES = `
5535
- CREATE TABLE IF NOT EXISTS identities (
5536
- id TEXT PRIMARY KEY,
5537
- email TEXT NOT NULL,
5538
- name TEXT NOT NULL,
5539
- email_verified_at TEXT NOT NULL,
5540
- terms_url TEXT,
5541
- terms_accepted_at TEXT,
5542
- created_at TEXT NOT NULL
5543
- );
5544
- CREATE UNIQUE INDEX IF NOT EXISTS identities_email ON identities (email);
5545
- CREATE TABLE IF NOT EXISTS identity_logins (
5546
- provider TEXT NOT NULL,
5547
- subject TEXT NOT NULL,
5548
- identity_id TEXT NOT NULL,
5549
- email TEXT NOT NULL,
5550
- added_at TEXT NOT NULL,
5551
- PRIMARY KEY (provider, subject)
5552
- );
5553
- CREATE INDEX IF NOT EXISTS identity_logins_identity ON identity_logins (identity_id);
5554
- CREATE TABLE IF NOT EXISTS identity_sessions (
5555
- token_hash TEXT PRIMARY KEY,
5556
- identity_id TEXT NOT NULL,
5557
- csrf TEXT NOT NULL,
5558
- method TEXT NOT NULL,
5559
- domain TEXT,
5560
- authenticated_at TEXT NOT NULL,
5561
- expires_at TEXT NOT NULL
5562
- );
5563
- CREATE TABLE IF NOT EXISTS identity_sign_ins (
5564
- state TEXT PRIMARY KEY,
5565
- provider TEXT NOT NULL,
5566
- purpose TEXT NOT NULL,
5567
- nonce TEXT NOT NULL,
5568
- verifier TEXT NOT NULL,
5569
- identity_id TEXT,
5570
- invite_id TEXT,
5571
- expires_at TEXT NOT NULL
5572
- );
5573
- CREATE TABLE IF NOT EXISTS orgs (
5574
- tenant TEXT PRIMARY KEY,
5575
- name TEXT NOT NULL,
5576
- created_by TEXT NOT NULL,
5577
- created_at TEXT NOT NULL,
5578
- quotas TEXT NOT NULL,
5579
- deleted_at TEXT
5580
- );
5581
- CREATE INDEX IF NOT EXISTS orgs_created_by ON orgs (created_by, created_at);
5582
- `;
5583
- var POLICIES_TABLE = `
5584
- CREATE TABLE IF NOT EXISTS policies (
5585
- tenant TEXT NOT NULL,
5586
- id TEXT NOT NULL,
5587
- name TEXT NOT NULL,
5588
- audience TEXT NOT NULL,
5589
- rules TEXT NOT NULL,
5590
- updated_at TEXT NOT NULL,
5591
- updated_by TEXT NOT NULL,
5592
- PRIMARY KEY (tenant, id)
5593
- );
5594
- `;
5595
- var EVENT_FLOOR_DAYS = 30;
5596
- var SQLITE_EVENT_GUARDS = `
5597
- CREATE TRIGGER IF NOT EXISTS events_append_only BEFORE UPDATE ON events
5598
- BEGIN SELECT RAISE(ABORT, 'the event log is append-only'); END;
5599
- CREATE TRIGGER IF NOT EXISTS events_kept BEFORE DELETE ON events
5600
- WHEN OLD.at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${EVENT_FLOOR_DAYS} days')
5601
- BEGIN SELECT RAISE(ABORT, 'an event younger than ${EVENT_FLOOR_DAYS} days is kept'); END;
5602
- `;
5603
- var POSTGRES_EVENT_GUARDS = `
5604
- CREATE OR REPLACE FUNCTION console_events_guard() RETURNS trigger LANGUAGE plpgsql AS $guard$
5605
- BEGIN
5606
- IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'the event log is append-only'; END IF;
5607
- IF OLD.at > to_char((now() AT TIME ZONE 'UTC') - interval '${EVENT_FLOOR_DAYS} days', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') THEN
5608
- RAISE EXCEPTION 'an event younger than ${EVENT_FLOOR_DAYS} days is kept';
5609
- END IF;
5610
- RETURN OLD;
5611
- END
5612
- $guard$;
5613
- CREATE OR REPLACE TRIGGER events_guard BEFORE UPDATE OR DELETE ON events FOR EACH ROW EXECUTE FUNCTION console_events_guard();
5614
- `;
5615
- var REQUEST_CHECK_COLUMNS = ["checked_head", "held_head", "held_reason"];
5616
- var TASK_SHARES_TABLE = `CREATE TABLE IF NOT EXISTS task_shares (
5617
- tenant TEXT NOT NULL,
5618
- task_id TEXT NOT NULL,
5619
- user_id TEXT NOT NULL,
5620
- shared_by TEXT NOT NULL,
5621
- at TEXT NOT NULL,
5622
- PRIMARY KEY (tenant, task_id, user_id)
5623
- )`;
5624
- var TASK_COLUMNS = [
5625
- { column: "log_seq", type: "INTEGER NOT NULL DEFAULT 0" },
5626
- { column: "issue_url", type: "TEXT" },
5627
- { column: "issue_key", type: "TEXT" },
5628
- { column: "pgid", type: "INTEGER" },
5629
- { column: "branch", type: "TEXT" },
5630
- { column: "template", type: "TEXT" }
5631
- ];
5632
- var ROLE_REWRITE = ["UPDATE users SET role = 'member' WHERE role = 'owner'", "UPDATE users SET role = 'owner' WHERE role = 'admin'"];
5633
- var TASK_INDEXES = `
5634
- CREATE INDEX IF NOT EXISTS tasks_newest ON tasks (tenant, created_at, id);
5635
- CREATE INDEX IF NOT EXISTS tasks_creator ON tasks (tenant, created_by, created_at);
5636
- CREATE INDEX IF NOT EXISTS tasks_request ON tasks (tenant, repo_id, request_number);
5637
- `;
5638
- var EFFECT_TABLES = `
5639
- CREATE TABLE IF NOT EXISTS task_effects (
5640
- tenant TEXT NOT NULL,
5641
- id TEXT NOT NULL,
5642
- task_id TEXT NOT NULL,
5643
- seq INTEGER NOT NULL,
5644
- kind TEXT NOT NULL,
5645
- payload TEXT NOT NULL,
5646
- replay TEXT NOT NULL,
5647
- status TEXT NOT NULL,
5648
- attempts INTEGER NOT NULL,
5649
- claimed_by TEXT,
5650
- lease_until TEXT,
5651
- due_at TEXT NOT NULL,
5652
- last_error TEXT,
5653
- result TEXT,
5654
- created_at TEXT NOT NULL,
5655
- settled_at TEXT,
5656
- PRIMARY KEY (tenant, id)
5657
- );
5658
- CREATE UNIQUE INDEX IF NOT EXISTS task_effects_order ON task_effects (tenant, task_id, seq);
5659
- CREATE INDEX IF NOT EXISTS task_effects_due ON task_effects (status, due_at);
5660
- CREATE TABLE IF NOT EXISTS command_receipts (
5661
- tenant TEXT NOT NULL,
5662
- actor_id TEXT NOT NULL,
5663
- command_id TEXT NOT NULL,
5664
- kind TEXT NOT NULL,
5665
- task_id TEXT NOT NULL,
5666
- result TEXT NOT NULL,
5667
- created_at TEXT NOT NULL,
5668
- PRIMARY KEY (tenant, actor_id, command_id)
5669
- );
5670
- `;
5671
- var SESSION_LISTING_SQLITE = ["sessions", "identity_sessions"].map((table) => `UPDATE ${table} SET id = 'ses_' || lower(hex(randomblob(13))) WHERE id IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS ${table}_id ON ${table} (id);`).join("\n");
5672
- var SESSION_LISTING_POSTGRES = ["sessions", "identity_sessions"].map((table) => `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS id TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS created_at TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS last_seen_at TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS user_agent TEXT;
5673
- UPDATE ${table} SET id = 'ses_' || substr(md5(random()::text || token_hash), 1, 26) WHERE id IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS ${table}_id ON ${table} (id);`).join("\n");
5674
- var IDENTITY_EVENTS_TABLE = `
5675
- CREATE TABLE IF NOT EXISTS identity_events (
5676
- id TEXT PRIMARY KEY,
5677
- identity_id TEXT NOT NULL,
5678
- at TEXT NOT NULL,
5679
- kind TEXT NOT NULL,
5680
- provider TEXT NOT NULL,
5681
- email_domain TEXT NOT NULL,
5682
- org TEXT
5683
- );
5684
- CREATE INDEX IF NOT EXISTS identity_events_at ON identity_events (at, id);
5685
- `;
5686
- var ATTACHMENTS_TABLE = `
5687
- CREATE TABLE IF NOT EXISTS task_attachments (
5688
- tenant TEXT NOT NULL,
5689
- id TEXT NOT NULL,
5690
- task_id TEXT NOT NULL,
5691
- name TEXT NOT NULL,
5692
- mime TEXT NOT NULL,
5693
- size INTEGER NOT NULL,
5694
- sha256 TEXT NOT NULL,
5695
- created_by TEXT NOT NULL,
5696
- created_at TEXT NOT NULL,
5697
- PRIMARY KEY (tenant, id)
5698
- );
5699
- CREATE INDEX IF NOT EXISTS task_attachments_task ON task_attachments (tenant, task_id);
5700
- `;
5701
- var RUNNER_TABLES = `
5702
- CREATE TABLE IF NOT EXISTS machines (
5703
- tenant TEXT NOT NULL,
5704
- id TEXT NOT NULL,
5705
- user_id TEXT NOT NULL,
5706
- name TEXT NOT NULL,
5707
- platform TEXT NOT NULL,
5708
- public_key TEXT NOT NULL,
5709
- token_hash TEXT NOT NULL,
5710
- agents TEXT NOT NULL,
5711
- created_at TEXT NOT NULL,
5712
- last_seen_at TEXT,
5713
- revoked_at TEXT,
5714
- PRIMARY KEY (tenant, id)
5715
- );
5716
- CREATE UNIQUE INDEX IF NOT EXISTS machines_token ON machines (token_hash);
5717
- CREATE INDEX IF NOT EXISTS machines_user ON machines (tenant, user_id);
5718
- CREATE TABLE IF NOT EXISTS machine_pairings (
5719
- tenant TEXT NOT NULL,
5720
- code_hash TEXT NOT NULL,
5721
- user_id TEXT NOT NULL,
5722
- expires_at TEXT NOT NULL,
5723
- used_at TEXT,
5724
- PRIMARY KEY (tenant, code_hash)
5725
- );
5726
- CREATE TABLE IF NOT EXISTS runner_nonces (
5727
- tenant TEXT NOT NULL,
5728
- machine_id TEXT NOT NULL,
5729
- nonce TEXT NOT NULL,
5730
- expires_at TEXT NOT NULL,
5731
- PRIMARY KEY (tenant, machine_id, nonce)
5732
- );
5733
- CREATE INDEX IF NOT EXISTS runner_nonces_expiry ON runner_nonces (expires_at);
5734
- `;
5735
- var RUNNER_INDEXES = `
5736
- CREATE INDEX IF NOT EXISTS tasks_claim ON tasks (tenant, status, runner, created_by, created_at);
5737
- CREATE INDEX IF NOT EXISTS tasks_lease ON tasks (status, lease_until);
5738
- CREATE UNIQUE INDEX IF NOT EXISTS task_log_source ON task_log (tenant, task_id, source_n);
5739
- `;
5740
- var RUNNER_TASK_COLUMNS = [
5741
- ["tasks", "runner", "TEXT NOT NULL DEFAULT 'server'"],
5742
- ["tasks", "claimed_by", "TEXT"],
5743
- ["tasks", "lease_id", "TEXT"],
5744
- ["tasks", "lease_until", "TEXT"],
5745
- ["tasks", "native_session", "TEXT"],
5746
- ["task_log", "kind", "TEXT NOT NULL DEFAULT 'log'"],
5747
- ["task_log", "data", "TEXT"],
5748
- ["task_log", "source_n", "INTEGER"]
5749
- ];
5750
- var FOLLOW_UPS_TABLE = `
5751
- CREATE TABLE IF NOT EXISTS task_followups (
5752
- tenant TEXT NOT NULL,
5753
- id TEXT NOT NULL,
5754
- task_id TEXT NOT NULL,
5755
- source TEXT NOT NULL,
5756
- key TEXT NOT NULL,
5757
- text TEXT NOT NULL,
5758
- quotes TEXT,
5759
- status TEXT NOT NULL,
5760
- created_at TEXT NOT NULL,
5761
- delivered_at TEXT,
5762
- created_by TEXT NOT NULL,
5763
- PRIMARY KEY (tenant, id)
5764
- );
5765
- CREATE UNIQUE INDEX IF NOT EXISTS task_followups_key ON task_followups (tenant, task_id, key);
5766
- `;
5767
- var PROJECT_LOCKS_TABLE = `
5768
- CREATE TABLE IF NOT EXISTS project_locks (
5769
- tenant TEXT NOT NULL,
5770
- project_id TEXT NOT NULL,
5771
- task_id TEXT NOT NULL,
5772
- taken_at TEXT NOT NULL,
5773
- PRIMARY KEY (tenant, project_id)
5774
- );
5775
- `;
5776
- var SETTINGS_BY_KEY = "CREATE INDEX IF NOT EXISTS settings_key ON settings (key);";
5777
- var TASK_PARENT_INDEX = "CREATE INDEX IF NOT EXISTS tasks_parent ON tasks (tenant, parent_id);";
5778
- var TASK_REQUESTS_TABLE = `
5779
- CREATE TABLE IF NOT EXISTS task_requests (
5780
- tenant TEXT NOT NULL,
5781
- id TEXT NOT NULL,
5782
- task_id TEXT NOT NULL,
5783
- target_position INTEGER,
5784
- source_key TEXT NOT NULL,
5785
- kind TEXT NOT NULL,
5786
- payload TEXT NOT NULL,
5787
- status TEXT NOT NULL,
5788
- response_capability TEXT NOT NULL,
5789
- answer TEXT,
5790
- answered_by TEXT,
5791
- answered_via TEXT,
5792
- created_at TEXT NOT NULL,
5793
- answered_at TEXT,
5794
- expires_at TEXT NOT NULL,
5795
- PRIMARY KEY (tenant, id)
5796
- );
5797
- CREATE UNIQUE INDEX IF NOT EXISTS task_requests_source ON task_requests (tenant, task_id, source_key);
5798
- CREATE INDEX IF NOT EXISTS task_requests_pending ON task_requests (status, expires_at);
5799
- `;
5800
- var EVENTS_BY_KIND = "CREATE INDEX IF NOT EXISTS events_first ON events (tenant, kind, at, id);";
5801
- var EXTRA_SPEND_TABLE = `
5802
- CREATE TABLE IF NOT EXISTS task_extra_spend (
5803
- tenant TEXT NOT NULL,
5804
- id TEXT NOT NULL,
5805
- created_by TEXT NOT NULL,
5806
- repo_id TEXT NOT NULL,
5807
- team TEXT NOT NULL,
5808
- at TEXT NOT NULL,
5809
- kind TEXT NOT NULL,
5810
- usd DOUBLE PRECISION,
5811
- input_tokens INTEGER,
5812
- output_tokens INTEGER,
5813
- PRIMARY KEY (tenant, id)
5814
- );
5815
- CREATE INDEX IF NOT EXISTS task_extra_spend_at ON task_extra_spend (tenant, at);
5816
- CREATE INDEX IF NOT EXISTS invites_address ON invites (email);
5817
- `;
5818
- var TASK_TARGETS_TABLE = `
5819
- CREATE TABLE IF NOT EXISTS task_targets (
5820
- tenant TEXT NOT NULL,
5821
- task_id TEXT NOT NULL,
5822
- position INTEGER NOT NULL,
5823
- repo_id TEXT NOT NULL,
5824
- status TEXT NOT NULL,
5825
- reason TEXT NOT NULL,
5826
- base_sha TEXT,
5827
- branch TEXT,
5828
- tests TEXT,
5829
- request_number INTEGER,
5830
- error TEXT,
5831
- cost_usd DOUBLE PRECISION,
5832
- input_tokens INTEGER,
5833
- output_tokens INTEGER,
5834
- PRIMARY KEY (tenant, task_id, position)
5835
- );
5836
- CREATE INDEX IF NOT EXISTS task_targets_request ON task_targets (tenant, repo_id, request_number);
5837
- `;
5838
- var MIGRATIONS = [
5839
- { version: 1, kind: "contract", name: "the first tables", sqlite: (db) => db.exec(BASE_TABLES), postgres: (db) => db.exec(BASE_TABLES) },
5840
- {
5841
- version: 2,
5842
- kind: "expand",
5843
- name: "task columns added after the first shape",
5844
- sqlite(db) {
5845
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
5846
- for (const { column, type } of TASK_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} ${type}`);
5847
- },
5848
- async postgres(db) {
5849
- for (const { column, type } of TASK_COLUMNS) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} ${type}`);
5850
- }
5851
- },
5852
- {
5853
- version: 3,
5854
- kind: "expand",
5855
- name: "the append-only event log",
5856
- sqlite: (db) => db.exec(EVENTS_TABLE + SQLITE_EVENT_GUARDS),
5857
- postgres: async (db) => {
5858
- await db.exec(EVENTS_TABLE);
5859
- await db.exec(POSTGRES_EVENT_GUARDS);
5860
- }
5861
- },
5862
- {
5863
- // Also parts the role from owning a team: until then "owner" meant a team's owner and "admin"
5864
- // ran the organization. A team owner becomes a member who keeps their teams, and an admin
5865
- // becomes an owner, so nobody loses a right they had and every organization that had an
5866
- // admin keeps someone who can change every role.
5867
- version: 4,
5868
- kind: "contract",
5869
- name: "invitations, service accounts, keys, directory groups, and the owner role",
5870
- sqlite: (db) => db.exec(IDENTITY_TABLES + ROLE_REWRITE.map((sql) => `${sql};`).join("\n")),
5871
- postgres: async (db) => {
5872
- await db.exec(IDENTITY_TABLES);
5873
- for (const sql of ROLE_REWRITE) await db.run(sql);
5874
- }
5875
- },
5876
- { version: 5, kind: "expand", name: "policies the orchestrator applies itself", sqlite: (db) => db.exec(POLICIES_TABLE), postgres: (db) => db.exec(POLICIES_TABLE) },
5877
- {
5878
- // Revoking a key revokes every key it minted, which needs each key to name the one that made it.
5879
- version: 6,
5880
- kind: "expand",
5881
- name: "keys remember the key that minted them",
5882
- sqlite(db) {
5883
- const have = new Set(db.prepare("PRAGMA table_info(api_keys)").all().map((c) => c.name));
5884
- if (!have.has("minted_by")) db.exec("ALTER TABLE api_keys ADD COLUMN minted_by TEXT");
5885
- },
5886
- postgres: (db) => db.exec("ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS minted_by TEXT")
5887
- },
5888
- {
5889
- // How long a request waited to merge is the analytics' measure, and the status alone does not say when.
5890
- version: 7,
5891
- kind: "expand",
5892
- name: "requests remember when they were merged",
5893
- sqlite(db) {
5894
- const have = new Set(db.prepare("PRAGMA table_info(requests)").all().map((c) => c.name));
5895
- if (!have.has("merged_at")) db.exec("ALTER TABLE requests ADD COLUMN merged_at TEXT");
5896
- },
5897
- postgres: (db) => db.exec("ALTER TABLE requests ADD COLUMN IF NOT EXISTS merged_at TEXT")
5898
- },
5899
- { version: 8, kind: "expand", name: "email domains verified for single sign-on", sqlite: (db) => db.exec(DOMAINS_TABLE), postgres: (db) => db.exec(DOMAINS_TABLE) },
5900
- // The task list is read a page at a time, newest first, and a budget sums one window of it;
5901
- // without these each read walks every task the organization ever ran.
5902
- { version: 9, kind: "expand", name: "tasks read newest first and by who started them", sqlite: (db) => db.exec(TASK_INDEXES), postgres: (db) => db.exec(TASK_INDEXES) },
5903
- {
5904
- // A task over several repositories keeps each one's run beside the task, and says how they were chosen.
5905
- version: 10,
5906
- kind: "expand",
5907
- name: "tasks over several repositories",
5908
- sqlite(db) {
5909
- db.exec(TASK_TARGETS_TABLE);
5910
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
5911
- if (!have.has("target_mode")) db.exec("ALTER TABLE tasks ADD COLUMN target_mode TEXT");
5912
- },
5913
- postgres: async (db) => {
5914
- await db.exec(TASK_TARGETS_TABLE);
5915
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS target_mode TEXT");
5916
- }
5917
- },
5918
- {
5919
- // The sprint board shows where a running task is, and Run again starts it with the same skills.
5920
- version: 11,
5921
- kind: "expand",
5922
- name: "tasks remember their stage and skills",
5923
- sqlite(db) {
5924
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
5925
- if (!have.has("stage")) db.exec("ALTER TABLE tasks ADD COLUMN stage TEXT");
5926
- if (!have.has("skills")) db.exec("ALTER TABLE tasks ADD COLUMN skills TEXT");
5927
- },
5928
- postgres: async (db) => {
5929
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS stage TEXT");
5930
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS skills TEXT");
5931
- }
5932
- },
5933
- {
5934
- // A cloud orchestrator's people: one identity across organizations, each membership an organization's account.
5935
- version: 12,
5936
- kind: "expand",
5937
- name: "identities and the organizations they create",
5938
- sqlite(db) {
5939
- db.exec(CLOUD_IDENTITY_TABLES);
5940
- const have = new Set(db.prepare("PRAGMA table_info(users)").all().map((c) => c.name));
5941
- if (!have.has("identity_id")) db.exec("ALTER TABLE users ADD COLUMN identity_id TEXT");
5942
- if (!have.has("sessions_revoked_at")) db.exec("ALTER TABLE users ADD COLUMN sessions_revoked_at TEXT");
5943
- db.exec("CREATE UNIQUE INDEX IF NOT EXISTS users_identity ON users (tenant, identity_id)");
5944
- },
5945
- postgres: async (db) => {
5946
- await db.exec(CLOUD_IDENTITY_TABLES);
5947
- await db.exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS identity_id TEXT");
5948
- await db.exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS sessions_revoked_at TEXT");
5949
- await db.exec("CREATE UNIQUE INDEX IF NOT EXISTS users_identity ON users (tenant, identity_id)");
5950
- }
5951
- },
5952
- {
5953
- // A skill suggestion spends on the model outside any task, and the budgets count it beside
5954
- // tasks; an identity's invitations are read by address across organizations.
5955
- version: 13,
5956
- kind: "expand",
5957
- name: "model spend outside tasks, and invitations by address",
5958
- sqlite: (db) => db.exec(EXTRA_SPEND_TABLE),
5959
- postgres: (db) => db.exec(EXTRA_SPEND_TABLE)
5960
- },
5961
- {
5962
- // Who has reached which step of an organization's setup is read from the first event of each kind.
5963
- version: 14,
5964
- kind: "expand",
5965
- name: "events read by kind",
5966
- sqlite: (db) => db.exec(EVENTS_BY_KIND),
5967
- postgres: (db) => db.exec(EVENTS_BY_KIND)
5968
- },
5969
- {
5970
- // A cloud organization's plan decides which features open for it; every one starts on Free.
5971
- version: 15,
5972
- kind: "expand",
5973
- name: "organizations carry a plan",
5974
- sqlite(db) {
5975
- const have = new Set(db.prepare("PRAGMA table_info(orgs)").all().map((c) => c.name));
5976
- if (!have.has("plan")) db.exec("ALTER TABLE orgs ADD COLUMN plan TEXT NOT NULL DEFAULT 'free'");
5977
- },
5978
- postgres: (db) => db.exec("ALTER TABLE orgs ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'free'")
5979
- },
5980
- {
5981
- // A task's side effects are written with the command that asks for them and carried out after,
5982
- // and a command sent twice is answered once.
5983
- version: 16,
5984
- kind: "expand",
5985
- name: "task effects and command receipts",
5986
- sqlite: (db) => db.exec(EFFECT_TABLES),
5987
- postgres: (db) => db.exec(EFFECT_TABLES)
5988
- },
5989
- {
5990
- // A task says how far its agent goes without asking, under the organization's ceiling.
5991
- version: 17,
5992
- kind: "expand",
5993
- name: "tasks carry a permission mode",
5994
- sqlite(db) {
5995
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
5996
- if (!have.has("mode")) db.exec("ALTER TABLE tasks ADD COLUMN mode TEXT");
5997
- },
5998
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS mode TEXT")
5999
- },
6000
- {
6001
- // What an agent asks while it works is kept before anyone answers it, so any browser answers it once.
6002
- version: 18,
6003
- kind: "expand",
6004
- name: "questions agents ask while they work",
6005
- sqlite: (db) => db.exec(TASK_REQUESTS_TABLE),
6006
- postgres: (db) => db.exec(TASK_REQUESTS_TABLE)
6007
- },
6008
- {
6009
- // A person lists the browsers they are signed in from and ends one by its id, not by its token.
6010
- version: 19,
6011
- kind: "expand",
6012
- name: "sessions listed by id",
6013
- sqlite(db) {
6014
- for (const table of ["sessions", "identity_sessions"]) {
6015
- const have = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name));
6016
- for (const column of ["id", "created_at", "last_seen_at", "user_agent"]) if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`);
6017
- }
6018
- db.exec(SESSION_LISTING_SQLITE);
6019
- },
6020
- postgres: (db) => db.exec(SESSION_LISTING_POSTGRES)
6021
- },
6022
- {
6023
- // A task an agent delegates records the task that asked for it and how deep it sits.
6024
- version: 20,
6025
- kind: "expand",
6026
- name: "tasks delegated by tasks",
6027
- sqlite(db) {
6028
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6029
- if (!have.has("parent_id")) db.exec("ALTER TABLE tasks ADD COLUMN parent_id TEXT");
6030
- if (!have.has("depth")) db.exec("ALTER TABLE tasks ADD COLUMN depth INTEGER NOT NULL DEFAULT 0");
6031
- db.exec(TASK_PARENT_INDEX);
6032
- },
6033
- postgres: async (db) => {
6034
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS parent_id TEXT");
6035
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS depth INTEGER NOT NULL DEFAULT 0");
6036
- await db.exec(TASK_PARENT_INDEX);
6037
- }
6038
- },
6039
- {
6040
- // Who signed up and how far their organization got, kept for the operator apart from every organization.
6041
- version: 21,
6042
- kind: "expand",
6043
- name: "signup steps",
6044
- sqlite: (db) => db.exec(IDENTITY_EVENTS_TABLE),
6045
- postgres: (db) => db.exec(IDENTITY_EVENTS_TABLE)
6046
- },
6047
- {
6048
- // An organization that lets people join by their directory is found by its setting's key.
6049
- version: 22,
6050
- kind: "expand",
6051
- name: "settings read by key",
6052
- sqlite: (db) => db.exec(SETTINGS_BY_KEY),
6053
- postgres: (db) => db.exec(SETTINGS_BY_KEY)
6054
- },
6055
- {
6056
- // A file a person attaches to a task is recorded beside it; its bytes stay in the data directory.
6057
- version: 23,
6058
- kind: "expand",
6059
- name: "task attachments",
6060
- sqlite: (db) => db.exec(ATTACHMENTS_TABLE),
6061
- postgres: (db) => db.exec(ATTACHMENTS_TABLE)
6062
- },
6063
- {
6064
- // A person's machine runs their tasks under a lease it renews; a task it held when the lease
6065
- // ran out waits for Continue there, and its events are numbered by the machine, written once.
6066
- version: 24,
6067
- kind: "expand",
6068
- name: "machines and the tasks they lease",
6069
- sqlite(db) {
6070
- db.exec(RUNNER_TABLES);
6071
- for (const [table, column, type] of RUNNER_TASK_COLUMNS) {
6072
- const have = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name));
6073
- if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
6074
- }
6075
- db.exec(RUNNER_INDEXES);
6076
- },
6077
- postgres: async (db) => {
6078
- await db.exec(RUNNER_TABLES);
6079
- for (const [table, column, type] of RUNNER_TASK_COLUMNS) await db.exec(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${column} ${type}`);
6080
- await db.exec(RUNNER_INDEXES);
6081
- }
6082
- },
6083
- {
6084
- // A task keeps the agent options it ran with, so Run again sends the same.
6085
- version: 25,
6086
- kind: "expand",
6087
- name: "tasks carry their agent's options",
6088
- sqlite(db) {
6089
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6090
- if (!have.has("choices")) db.exec("ALTER TABLE tasks ADD COLUMN choices TEXT");
6091
- },
6092
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS choices TEXT")
6093
- },
6094
- {
6095
- // A question from an agent on a person's machine has no deadline of its own: it waits as long
6096
- // as the machine holds the task. SQLite drops a NOT NULL only by copying the table.
6097
- version: 26,
6098
- kind: "expand",
6099
- name: "questions that wait without a deadline",
6100
- sqlite(db) {
6101
- const column = db.prepare("PRAGMA table_info(task_requests)").all().find((c) => c.name === "expires_at");
6102
- if (!column?.notnull) return;
6103
- db.exec(`${TASK_REQUESTS_TABLE.replace("task_requests (", "task_requests_next (").replace("expires_at TEXT NOT NULL", "expires_at TEXT").replace(/CREATE (UNIQUE )?INDEX[^;]*;/g, "")}
6104
- INSERT INTO task_requests_next SELECT * FROM task_requests;
6105
- DROP TABLE task_requests;
6106
- ALTER TABLE task_requests_next RENAME TO task_requests;
6107
- ${TASK_REQUESTS_TABLE.replace(/CREATE TABLE[^;]*;/, "")}`);
6108
- },
6109
- postgres: (db) => db.exec("ALTER TABLE task_requests ALTER COLUMN expires_at DROP NOT NULL")
6110
- },
6111
- {
6112
- // A link whose provider email is not the identity's waits for the person to confirm it, with
6113
- // the provider's account kept beside its state until then.
6114
- version: 27,
6115
- kind: "expand",
6116
- name: "pending links keep the account they wait to confirm",
6117
- sqlite(db) {
6118
- const have = new Set(db.prepare("PRAGMA table_info(identity_sign_ins)").all().map((c) => c.name));
6119
- if (!have.has("account")) db.exec("ALTER TABLE identity_sign_ins ADD COLUMN account TEXT");
6120
- },
6121
- postgres: (db) => db.exec("ALTER TABLE identity_sign_ins ADD COLUMN IF NOT EXISTS account TEXT")
6122
- },
6123
- {
6124
- // A Stop for a task a machine runs is kept on the task until the run ends, so it reaches the
6125
- // runner through any instance and across a restart.
6126
- version: 28,
6127
- kind: "expand",
6128
- name: "stops asked for tasks a machine runs",
6129
- sqlite(db) {
6130
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6131
- if (!have.has("stop_requested_at")) db.exec("ALTER TABLE tasks ADD COLUMN stop_requested_at TEXT");
6132
- },
6133
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS stop_requested_at TEXT")
6134
- },
6135
- {
6136
- // What reaches a running task after it started is kept before it is delivered, once per key,
6137
- // so a second web node or a restarted sweep writes it once.
6138
- version: 29,
6139
- kind: "expand",
6140
- name: "follow-ups waiting for a running task",
6141
- sqlite: (db) => db.exec(FOLLOW_UPS_TABLE),
6142
- postgres: (db) => db.exec(FOLLOW_UPS_TABLE)
6143
- },
6144
- {
6145
- // A task in a folder without git works there in place, one at a time, and leaves changes
6146
- // rather than a request, read between two snapshots of the folder's shadow.
6147
- version: 30,
6148
- kind: "expand",
6149
- name: "tasks working in a folder in place",
6150
- sqlite(db) {
6151
- db.exec(PROJECT_LOCKS_TABLE);
6152
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6153
- for (const column of ["result", "changes"]) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} TEXT`);
6154
- },
6155
- postgres: async (db) => {
6156
- await db.exec(PROJECT_LOCKS_TABLE);
6157
- for (const column of ["result", "changes"]) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6158
- }
6159
- },
6160
- {
6161
- // A task's request is checked again each time its head moves: the last head that passed, and
6162
- // the head that failed with why, which holds the request until a later head passes.
6163
- version: 31,
6164
- kind: "expand",
6165
- name: "the check of a request's head",
6166
- sqlite(db) {
6167
- const have = new Set(db.prepare("PRAGMA table_info(requests)").all().map((c) => c.name));
6168
- for (const column of REQUEST_CHECK_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE requests ADD COLUMN ${column} TEXT`);
6169
- },
6170
- postgres: async (db) => {
6171
- for (const column of REQUEST_CHECK_COLUMNS) await db.exec(`ALTER TABLE requests ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6172
- }
6173
- },
6174
- {
6175
- // A task keeps what its starter picked of the project's own skill sources and MCP servers.
6176
- version: 32,
6177
- kind: "expand",
6178
- name: "a task's pick of its project's skills and MCP servers",
6179
- sqlite(db) {
6180
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6181
- if (!have.has("tools")) db.exec("ALTER TABLE tasks ADD COLUMN tools TEXT");
6182
- },
6183
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS tools TEXT")
6184
- },
6185
- {
6186
- // A task shared with a member of its organization to read; nobody outside it.
6187
- version: 33,
6188
- kind: "expand",
6189
- name: "tasks shared with a member to read",
6190
- sqlite: (db) => db.exec(TASK_SHARES_TABLE),
6191
- postgres: (db) => db.exec(TASK_SHARES_TABLE)
6192
- },
6193
- {
6194
- // What the person's own Claude Code loaded into a task's run, by count; and where in the task's folder each of its
6195
- // repositories is, so a change kept on a person's machine is named by its place there.
6196
- version: 34,
6197
- kind: "expand",
6198
- name: "what a person's own setup loaded into a task's run, and each target's place in its folder",
6199
- sqlite(db) {
6200
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6201
- if (!have.has("loaded")) db.exec("ALTER TABLE tasks ADD COLUMN loaded TEXT");
6202
- const targets = new Set(db.prepare("PRAGMA table_info(task_targets)").all().map((c) => c.name));
6203
- if (!targets.has("path")) db.exec("ALTER TABLE task_targets ADD COLUMN path TEXT");
6204
- },
6205
- async postgres(db) {
6206
- await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS loaded TEXT");
6207
- await db.exec("ALTER TABLE task_targets ADD COLUMN IF NOT EXISTS path TEXT");
6208
- }
6209
- },
6210
- {
6211
- // How many tokens a task's first agent request carried: the context a cost line names.
6212
- version: 35,
6213
- kind: "expand",
6214
- name: "the context a task's run started from",
6215
- sqlite(db) {
6216
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6217
- if (!have.has("context_tokens")) db.exec("ALTER TABLE tasks ADD COLUMN context_tokens INTEGER");
6218
- },
6219
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS context_tokens INTEGER")
6220
- },
6221
- {
6222
- // What a change kept on a person's machine needs for a later push and request: its head, its remote and that
6223
- // remote's default branch, and the request's words.
6224
- version: 36,
6225
- kind: "expand",
6226
- name: "a kept change's head, remote and request words",
6227
- sqlite(db) {
6228
- const have = new Set(db.prepare("PRAGMA table_info(task_targets)").all().map((c) => c.name));
6229
- for (const column of ["head", "origin", "target_branch", "description"]) if (!have.has(column)) db.exec(`ALTER TABLE task_targets ADD COLUMN ${column} TEXT`);
6230
- },
6231
- async postgres(db) {
6232
- for (const column of ["head", "origin", "target_branch", "description"]) await db.exec(`ALTER TABLE task_targets ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6233
- }
6234
- },
6235
- {
6236
- // Why a task was asked to stop when the orchestrator asked it (a limit), and when its current run started.
6237
- version: 37,
6238
- kind: "expand",
6239
- name: "a stop's reason and the run's start",
6240
- sqlite(db) {
6241
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6242
- for (const column of ["stop_reason", "run_started_at"]) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} TEXT`);
6243
- },
6244
- async postgres(db) {
6245
- for (const column of ["stop_reason", "run_started_at"]) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6246
- }
6247
- },
6248
- {
6249
- // Where the orchestrator sent a task started with no project named, and why.
6250
- version: 38,
6251
- kind: "expand",
6252
- name: "where a task was sent",
6253
- sqlite(db) {
6254
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6255
- if (!have.has("routing")) db.exec("ALTER TABLE tasks ADD COLUMN routing TEXT");
6256
- },
6257
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS routing TEXT")
6258
- },
6259
- {
6260
- // What a stopped run asked its starter, and the answer the next run takes.
6261
- version: 39,
6262
- kind: "expand",
6263
- name: "a task's question to its starter",
6264
- sqlite(db) {
6265
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6266
- if (!have.has("question")) db.exec("ALTER TABLE tasks ADD COLUMN question TEXT");
6267
- },
6268
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS question TEXT")
6269
- },
6270
- {
6271
- // The person's own MCP servers a task's agent found waiting for a sign-in.
6272
- version: 40,
6273
- kind: "expand",
6274
- name: "the servers a task found waiting for a sign-in",
6275
- sqlite(db) {
6276
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6277
- if (!have.has("mcp_needs_sign_in")) db.exec("ALTER TABLE tasks ADD COLUMN mcp_needs_sign_in TEXT");
6278
- },
6279
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS mcp_needs_sign_in TEXT")
6280
- },
6281
- {
6282
- // A task started to plan first: its agent changes nothing until its starter approves the plan.
6283
- version: 41,
6284
- kind: "expand",
6285
- name: "a task that plans first",
6286
- sqlite(db) {
6287
- const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6288
- if (!have.has("plan_first")) db.exec("ALTER TABLE tasks ADD COLUMN plan_first INTEGER");
6289
- },
6290
- postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS plan_first INTEGER")
5375
+ // server/forge/http.ts
5376
+ var ForgeHttpError = class extends Error {
5377
+ constructor(message, status2, retryAt = null) {
5378
+ super(message);
5379
+ this.status = status2;
5380
+ this.retryAt = retryAt;
6291
5381
  }
6292
- ];
6293
- var SCHEMA_VERSION = MIGRATIONS.length;
6294
-
6295
- // server/events.ts
6296
- var ORCHESTRATOR_ACTOR = { kind: "orchestrator", id: null, email: null, name: "TeamHandbook Orchestrator" };
6297
- function actorOf(user) {
6298
- return { kind: user.id.startsWith("service:") ? "service" : "user", id: user.id, email: user.email, name: user.name };
5382
+ };
5383
+ function rateLimitedUntil(res, now = Date.now()) {
5384
+ const spent = res.headers.get("x-ratelimit-remaining") === "0" || res.headers.get("ratelimit-remaining") === "0";
5385
+ if (res.status !== 429 && !(res.status === 403 && spent)) return null;
5386
+ const after = res.headers.get("retry-after");
5387
+ if (after && /^[0-9]+$/.test(after)) return new Date(now + Number(after) * 1e3).toISOString();
5388
+ if (after && Number.isFinite(Date.parse(after))) return new Date(Date.parse(after)).toISOString();
5389
+ const reset = res.headers.get("x-ratelimit-reset") ?? res.headers.get("ratelimit-reset");
5390
+ if (reset && /^[0-9]+$/.test(reset)) return new Date(Number(reset) * 1e3).toISOString();
5391
+ return new Date(now + 6e4).toISOString();
6299
5392
  }
6300
- var TEXT_MAX3 = 500;
6301
- function loggedText(text) {
6302
- const flat = maskUrl(text).replace(/\p{C}+/gu, " ").trim().slice(0, TEXT_MAX3);
6303
- const secret = detectSecret(flat);
6304
- return secret ? `[withheld: it looks like a ${secret}]` : flat;
5393
+ var MESSAGE_MAX = 300;
5394
+ var priority = new AsyncLocalStorage();
5395
+ var INTERACTIVE_RESERVE = 0.1;
5396
+ var BACKOFF_MIN_MS = 3e4;
5397
+ var BACKOFF_MAX_MS = 15 * 6e4;
5398
+ var KEPT_ANSWERS = 500;
5399
+ var quotas = /* @__PURE__ */ new Map();
5400
+ var kept = /* @__PURE__ */ new Map();
5401
+ function readQuota(res, now, previous) {
5402
+ const header = (...names) => names.map((n) => res.headers.get(n)).find((v) => v !== null && /^[0-9]+$/.test(v));
5403
+ const remaining = header("x-ratelimit-remaining", "ratelimit-remaining");
5404
+ const limit = header("x-ratelimit-limit", "ratelimit-limit");
5405
+ const reset = header("x-ratelimit-reset", "ratelimit-reset");
5406
+ const retry = rateLimitedUntil(res, now);
5407
+ return {
5408
+ until: retry ? Math.min(Math.max(Date.parse(retry), now + BACKOFF_MIN_MS), now + BACKOFF_MAX_MS) : null,
5409
+ remaining: remaining !== void 0 ? Number(remaining) : previous?.remaining ?? null,
5410
+ limit: limit !== void 0 ? Number(limit) : previous?.limit ?? null,
5411
+ resetAt: reset !== void 0 ? Number(reset) * 1e3 : previous?.resetAt ?? null
5412
+ };
6305
5413
  }
6306
- async function recordEvent(ctx, actor, kind, fields, now = /* @__PURE__ */ new Date()) {
6307
- const by = "role" in actor ? actorOf(actor) : actor;
6308
- await ctx.store.appendEvent({
6309
- tenant: ctx.tenant,
6310
- id: newId("evt", now.getTime()),
6311
- at: now.toISOString(),
6312
- kind,
6313
- actor: { ...by, email: by.email && loggedText(by.email), name: by.name && loggedText(by.name) },
6314
- repoId: fields.repoId ?? null,
6315
- subject: fields.subject ? loggedText(fields.subject) : null,
6316
- detail: loggedText(fields.detail)
6317
- });
5414
+ function messageOf(payload) {
5415
+ if (!payload || typeof payload !== "object") return "";
5416
+ const { message, error } = payload;
5417
+ const value = message ?? error;
5418
+ if (typeof value === "string") return value;
5419
+ return value === void 0 ? "" : JSON.stringify(value);
6318
5420
  }
6319
-
6320
- // server/scim.ts
6321
- var USERS = "/Users";
6322
- var ONE_USER = `/api/scim/v2${USERS}/:id`;
6323
-
6324
- // server/directory.ts
6325
- function tagsUnder(mapping, groups, manual) {
6326
- const byGroup = new Map(mapping.map((m) => [m.group, m.tag]));
6327
- const tags = /* @__PURE__ */ new Map();
6328
- const add = (userId, tag, source) => {
6329
- const mine = tags.get(userId) ?? /* @__PURE__ */ new Map();
6330
- if (!mine.has(tag) || source === "manual") mine.set(tag, source);
6331
- tags.set(userId, mine);
5421
+ function forgeHttp(forge, baseUrl, token2, headers, fetchImpl) {
5422
+ const root2 = baseUrl.replace(/\/+$/, "");
5423
+ const host = new URL(root2).host;
5424
+ const scope = `${forge}\0${host}\0${createHash2("sha256").update(token2).digest("hex").slice(0, 16)}`;
5425
+ return {
5426
+ async request(method, path, body) {
5427
+ const operation = operationOf(method, path);
5428
+ const now = Date.now();
5429
+ const quota = quotas.get(scope);
5430
+ const lowOnQuota = quota !== void 0 && quota.remaining !== null && quota.limit !== null && quota.remaining < quota.limit * INTERACTIVE_RESERVE && (quota.resetAt ?? 0) > now;
5431
+ const waitUntil = quota?.until && quota.until > now ? quota.until : lowOnQuota && priority.getStore() === "background" ? quota.resetAt : null;
5432
+ if (waitUntil) {
5433
+ forgeMeter.called(forge, host, operation, "held");
5434
+ const until = new Date(waitUntil).toISOString();
5435
+ throw new ForgeHttpError(`${forge} asked the orchestrator to wait until ${until}; ${method} ${path} was not sent, try again after that`, 429, until);
5436
+ }
5437
+ const cacheKey = method === "GET" ? `${scope}\0${path}` : null;
5438
+ const before = cacheKey ? kept.get(cacheKey) : void 0;
5439
+ let res;
5440
+ try {
5441
+ res = await fetchImpl(`${root2}${path}`, {
5442
+ method,
5443
+ headers: { ...headers, ...before ? { "if-none-match": before.etag } : {}, ...body === void 0 ? {} : { "content-type": "application/json" } },
5444
+ body: body === void 0 ? void 0 : JSON.stringify(body),
5445
+ // Not followed: the token goes to the address an admin entered and nowhere it points.
5446
+ redirect: "manual",
5447
+ signal: AbortSignal.timeout(3e4)
5448
+ });
5449
+ } catch (err) {
5450
+ forgeMeter.called(forge, host, operation, statusClass(0));
5451
+ throw new ForgeHttpError(maskSecrets(`${forge} is unreachable on ${method} ${path}; try again, and if it repeats, whoever runs the orchestrator checks its network (${err.message})`, [token2]).slice(0, MESSAGE_MAX), 0);
5452
+ }
5453
+ forgeMeter.called(forge, host, operation, statusClass(res.status));
5454
+ const seen2 = readQuota(res, now, quota);
5455
+ quotas.set(scope, seen2);
5456
+ if (seen2.remaining !== null) forgeMeter.reported(forge, host, seen2.remaining, seen2.limit);
5457
+ if (res.status === 304 && before) {
5458
+ return before.text ? JSON.parse(before.text) : null;
5459
+ }
5460
+ if (res.status >= 300 && res.status < 400) {
5461
+ throw new ForgeHttpError(`${forge} answered ${res.status} on ${method} ${path}, a redirect the orchestrator does not follow; an owner or an admin checks the repository's API address`, res.status);
5462
+ }
5463
+ const text = await res.text();
5464
+ const etag = res.headers.get("etag");
5465
+ if (cacheKey && res.ok && etag) {
5466
+ kept.delete(cacheKey);
5467
+ kept.set(cacheKey, { etag, text });
5468
+ if (kept.size > KEPT_ANSWERS) kept.delete(kept.keys().next().value);
5469
+ }
5470
+ let payload = null;
5471
+ try {
5472
+ payload = text ? JSON.parse(text) : null;
5473
+ } catch {
5474
+ payload = null;
5475
+ }
5476
+ if (!res.ok) {
5477
+ const detail = messageOf(payload);
5478
+ const message = `${forge} answered ${res.status} on ${method} ${path}${detail ? `: ${detail}` : ""}`;
5479
+ throw new ForgeHttpError(maskSecrets(message, [token2]).slice(0, MESSAGE_MAX), res.status, rateLimitedUntil(res));
5480
+ }
5481
+ return payload;
5482
+ }
6332
5483
  };
6333
- for (const { userId, group } of groups) {
6334
- const tag = byGroup.get(group);
6335
- if (tag) add(userId, tag, "directory");
6336
- }
6337
- for (const { userId, tag } of manual) add(userId, tag, "manual");
6338
- return new Map([...tags].map(([userId, mine]) => [userId, [...mine].map(([tag, source]) => ({ tag, source })).sort((a, b) => a.tag.localeCompare(b.tag))]));
6339
5484
  }
6340
- async function memberTags(store, tenant) {
6341
- return tagsUnder(await store.groupTags(tenant), await store.memberGroups(tenant), await store.manualTags(tenant));
5485
+ var BRANCH2 = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
5486
+ function checkBranch(branch) {
5487
+ if (!BRANCH2.test(branch) || branch.includes("..")) throw new Error(`invalid branch name ${JSON.stringify(branch)}`);
6342
5488
  }
6343
5489
 
6344
- // server/limits.ts
6345
- var WINDOW_MS = 6e4;
6346
- function windowLimiter(perMinute, now = Date.now, maxKeys = 1e4) {
6347
- const hits = /* @__PURE__ */ new Map();
6348
- return (key, count = 1) => {
6349
- const t = now();
6350
- const recent = (hits.get(key) ?? []).filter((at2) => t - at2 < WINDOW_MS);
6351
- hits.delete(key);
6352
- for (const idle of hits.keys()) {
6353
- if (hits.size < maxKeys) break;
6354
- hits.delete(idle);
6355
- }
6356
- if (recent.length + count > perMinute) {
6357
- hits.set(key, recent);
6358
- return { ok: false, retryAfter: Math.max(1, Math.ceil(((recent[recent.length + count - perMinute - 1] ?? t) + WINDOW_MS - t) / 1e3)) };
5490
+ // server/forge/own-cli.ts
5491
+ function cliEnv() {
5492
+ return Object.fromEntries(Object.entries(nonInteractiveEnv(process.env)).filter(([name]) => !name.startsWith("ORCHESTRATOR_") && name !== "GITEA_TOKEN" && name !== "GITEA_INSTANCE_URL"));
5493
+ }
5494
+ var runOwnCli = (tool, args, input) => new Promise((resolve11) => {
5495
+ const child = execFile3(tool, args, { cwd: tmpdir2(), env: cliEnv(), timeout: 6e4, maxBuffer: 1024 * 1024, encoding: "utf8" }, (err, stdout, stderr) => {
5496
+ const failure2 = err;
5497
+ resolve11({ code: failure2 ? typeof failure2.code === "number" ? failure2.code : 1 : 0, stdout: String(stdout), stderr: String(stderr), missing: failure2?.code === "ENOENT" });
5498
+ });
5499
+ child.stdin?.end(input ?? "");
5500
+ });
5501
+ var hostname2 = (host) => host.replace(/:\d+$/, "");
5502
+ var ownRequest = (body) => {
5503
+ const b = body;
5504
+ return b && { number: b.number ?? b.iid, url: b.url ?? b.web_url };
5505
+ };
5506
+ var authStatus = (tool) => async (host, run2) => {
5507
+ const status2 = await run2(tool, ["auth", "status", "--hostname", hostname2(host)]);
5508
+ return { installed: !status2.missing, signedIn: !status2.missing && status2.code === 0, as: ["--hostname", hostname2(host)] };
5509
+ };
5510
+ var helpsGit = (tool) => async (run2) => (await run2(tool, ["auth", "git-credential", "--help"])).code === 0;
5511
+ var userField = (tool, field) => async (_host, signIn, run2) => {
5512
+ const read = await run2(tool, ["api", ...signIn.as, "user"]);
5513
+ if (read.code !== 0) return null;
5514
+ const login = String(parsed(read.stdout)?.[field] ?? "");
5515
+ return LOGIN.test(login) ? login : null;
5516
+ };
5517
+ var stderrFirst = (read) => read.stderr || read.stdout;
5518
+ var exitFailed = (read) => read.code === 0 ? null : Number(/HTTP (\d{3})/.exec(read.stderr)?.[1] ?? 502);
5519
+ var assignmentFlags = (a) => [...a.reviewers.flatMap((r) => ["--reviewer", r]), ...a.labels.flatMap((l) => ["--label", l]), ...a.assignee ? ["--assignee", a.assignee] : []];
5520
+ var TEA_SINCE = "0.15.0";
5521
+ var TEA_STATUS = /^HTTP\/\S+ (\d{3})\b/m;
5522
+ var teaLogins = (text) => {
5523
+ try {
5524
+ const rows = JSON.parse(text);
5525
+ if (!Array.isArray(rows)) return [];
5526
+ const field = (row, key) => String(Object.entries(row).find(([k]) => k.toLowerCase() === key)?.[1] ?? "");
5527
+ return rows.filter((r) => Boolean(r) && typeof r === "object").map((r) => ({ name: field(r, "name"), url: field(r, "url"), user: field(r, "user") }));
5528
+ } catch {
5529
+ return [];
5530
+ }
5531
+ };
5532
+ var TOOLS = {
5533
+ github: {
5534
+ tool: "gh",
5535
+ name: "GitHub's gh",
5536
+ helper: "!gh auth git-credential",
5537
+ install: "https://cli.github.com",
5538
+ login: (host) => `gh auth login --hostname ${hostname2(host)}`,
5539
+ signIn: authStatus("gh"),
5540
+ helps: helpsGit("gh"),
5541
+ account: userField("gh", "login"),
5542
+ api: (as, path) => ["api", ...as, path],
5543
+ failed: exitFailed,
5544
+ told: stderrFirst,
5545
+ answerNames: true,
5546
+ view: (project, branch) => ["pr", "view", branch, "--repo", project, "--json", "number,url"],
5547
+ pick: ownRequest,
5548
+ state: (project, number) => ["pr", "view", String(number), "--repo", project, "--json", "state,mergedAt,headRefOid"],
5549
+ create: (project, branch, target, title, body, assignment) => ({ args: ["pr", "create", "--repo", project, "--head", branch, "--base", target, "--title", title, "--body-file", "-", ...assignmentFlags(assignment)], input: body }),
5550
+ // GitHub's own API is on api.github.com; an Enterprise server's is beside it.
5551
+ hostOf: (apiUrl) => new URL(apiUrl).host === "api.github.com" ? "github.com" : new URL(apiUrl).host,
5552
+ writeStatus: (project, sha, check, as) => ({ args: ["api", ...as, "-X", "POST", "-f", `state=${check.state}`, "-f", `context=${check.context}`, "-f", `description=${check.description}`, `repos/${project}/statuses/${sha}`] })
5553
+ },
5554
+ gitlab: {
5555
+ tool: "glab",
5556
+ name: "GitLab's glab",
5557
+ helper: "!glab auth git-credential",
5558
+ install: "https://gitlab.com/gitlab-org/cli",
5559
+ login: (host) => `glab auth login --hostname ${hostname2(host)}`,
5560
+ signIn: authStatus("glab"),
5561
+ helps: helpsGit("glab"),
5562
+ account: userField("glab", "username"),
5563
+ api: (as, path) => ["api", ...as, path],
5564
+ failed: exitFailed,
5565
+ told: stderrFirst,
5566
+ answerNames: true,
5567
+ view: (project, branch) => ["mr", "view", branch, "--repo", project, "--output", "json"],
5568
+ pick: ownRequest,
5569
+ state: (project, number) => ["mr", "view", String(number), "--repo", project, "--output", "json"],
5570
+ create: (project, branch, target, title, body, assignment) => ({ args: ["mr", "create", "--repo", project, "--source-branch", branch, "--target-branch", target, "--title", title, "--description", body, "--remove-source-branch", "--yes", ...assignmentFlags(assignment)] }),
5571
+ hostOf: (apiUrl) => new URL(apiUrl).host,
5572
+ // GitLab names a failed check "failed", and a check with no verdict is one too, as its driver writes it.
5573
+ writeStatus: (project, sha, check, as) => ({
5574
+ args: ["api", ...as, "-X", "POST", "-f", `state=${check.state === "failure" || check.state === "error" ? "failed" : check.state}`, "-f", `name=${check.context}`, "-f", `description=${check.description}`, `projects/${encodeURIComponent(project)}/statuses/${sha}`]
5575
+ })
5576
+ },
5577
+ gitea: {
5578
+ tool: "tea",
5579
+ name: "Gitea's tea",
5580
+ helper: "!tea login helper",
5581
+ install: "https://gitea.com/gitea/tea",
5582
+ login: (host) => `tea login add --url https://${host}`,
5583
+ async signIn(host, run2) {
5584
+ const listed = await run2("tea", ["login", "list", "--output", "json"]);
5585
+ if (listed.missing) return { installed: false, signedIn: false, as: [] };
5586
+ const version3 = await versionOf("tea", run2);
5587
+ if (!version3 || !atLeast(version3, TEA_SINCE)) return { installed: true, signedIn: false, as: [], problem: `your tea is ${version3 ?? "of a version it does not say"}; the orchestrator needs ${TEA_SINCE} or later, update it (https://gitea.com/gitea/tea)` };
5588
+ const here = listed.code === 0 ? teaLogins(listed.stdout).filter((l) => URL.canParse(l.url) && new URL(l.url).host === host) : [];
5589
+ if (here.length > 1) return { installed: true, signedIn: false, as: [], problem: `tea holds ${here.length} logins for ${host} (${here.map((l) => l.name).join(", ")}); keep one with \`tea login delete <name>\`, then try again` };
5590
+ const one = here[0];
5591
+ return one ? { installed: true, signedIn: true, as: [`--login=${one.name}`], account: LOGIN.test(one.user) ? one.user : null } : { installed: true, signedIn: false, as: [] };
5592
+ },
5593
+ helps: async (_run, version3) => {
5594
+ const v = await version3;
5595
+ return v !== null && atLeast(v, "0.10.1");
5596
+ },
5597
+ account: async (_host, signIn) => signIn.account ?? null,
5598
+ api: (as, path) => ["api", "-i", ...as, path],
5599
+ failed(read) {
5600
+ const status2 = Number(TEA_STATUS.exec(read.stderr)?.[1] ?? 0);
5601
+ if (read.code === 0 && status2 >= 200 && status2 < 300) return null;
5602
+ return status2 >= 400 ? status2 : 502;
5603
+ },
5604
+ // With -i tea writes every response header to stderr; only the status line and the forge's answer are said.
5605
+ told: (read) => [TEA_STATUS.exec(read.stderr)?.[0], read.stdout].filter(Boolean).join(" ") || read.stderr,
5606
+ answerNames: false,
5607
+ view: (project, _branch, as) => ["api", "-i", ...as, `repos/${project}/pulls?state=open&limit=50`],
5608
+ pick(body, branch) {
5609
+ const pulls = Array.isArray(body) ? body : [];
5610
+ const pull = pulls.find((p) => p?.head?.ref === branch);
5611
+ return pull ? { number: pull.number, url: pull.html_url } : null;
5612
+ },
5613
+ state: (project, number, as) => ["api", "-i", ...as, `repos/${project}/pulls/${number}`],
5614
+ create: (project, branch, target, title, body, assignment, as) => ({
5615
+ args: ["pulls", "create", ...as, "--repo", project, "--head", branch, "--base", target, "--title", title, "--description-file", "-", ...assignment.labels.length ? ["--labels", assignment.labels.join(",")] : [], ...assignment.assignee ? ["--assignees", assignment.assignee] : []],
5616
+ input: body
5617
+ }),
5618
+ hostOf: (apiUrl) => new URL(apiUrl).host,
5619
+ writeStatus: (project, sha, check, as) => ({ args: ["api", "-i", ...as, "-X", "POST", "-d", "@-", `repos/${project}/statuses/${sha}`], input: JSON.stringify({ state: check.state, context: check.context, description: check.description }) }),
5620
+ // tea opens a pull request with no reviewers, so they are asked for after, as the person.
5621
+ async assign(project, number, assignment, as, run2) {
5622
+ if (!assignment.reviewers.length) return [];
5623
+ const asked = await run2("tea", ["api", "-i", ...as, "-X", "POST", "-d", "@-", `repos/${project}/pulls/${number}/requested_reviewers`], JSON.stringify({ reviewers: assignment.reviewers }));
5624
+ return TOOLS.gitea.failed(asked) === null ? [] : [`reviewers were not added: ${said(asked.stdout || asked.stderr)}`];
6359
5625
  }
6360
- for (let i = 0; i < count; i++) recent.push(t);
6361
- hits.set(key, recent);
6362
- return { ok: true, retryAfter: 0 };
6363
- };
6364
- }
6365
- var PER_KEY_PER_MINUTE = 120;
6366
- var PER_ACCOUNT_PER_MINUTE = 300;
6367
- function keyGate(now = Date.now) {
6368
- const perKey = windowLimiter(PER_KEY_PER_MINUTE, now);
6369
- const perAccount = windowLimiter(PER_ACCOUNT_PER_MINUTE, now);
6370
- return (caller) => {
6371
- const key = perKey(`${caller.tenant}\0${caller.keyId}`);
6372
- if (!key.ok) return { ...key, limit: "key" };
6373
- const account = perAccount(`${caller.tenant}\0${caller.owner.kind}:${caller.owner.id}`);
6374
- return account.ok ? account : { ...account, limit: "account" };
6375
- };
6376
- }
6377
- var limitKeyCall = keyGate();
6378
- var LIMITED_EVENT_MS = 10 * 6e4;
6379
- function limitedNotes(now = Date.now) {
6380
- const last2 = /* @__PURE__ */ new Map();
6381
- return async (ctx, actor, keyId, limit) => {
6382
- const at2 = now();
6383
- const mark = `${ctx.tenant}\0${keyId}`;
6384
- if ((last2.get(mark) ?? -Infinity) > at2 - LIMITED_EVENT_MS) return;
6385
- last2.set(mark, at2);
6386
- if (last2.size > 1e4) last2.delete(last2.keys().next().value);
6387
- await recordEvent(ctx, actor, "key.rate-limited", { subject: `key:${keyId}`, detail: `held back past ${limit === "account" ? `${PER_ACCOUNT_PER_MINUTE} calls a minute for the account` : `${PER_KEY_PER_MINUTE} calls a minute for the key`}; further refusals in the next ten minutes are not written` });
6388
- };
6389
- }
6390
- var noteLimited = limitedNotes();
6391
-
6392
- // server/keys.ts
6393
- var MOST = { repositories: "write", requests: "write", tasks: "write", usage: "read", members: "read", settings: "read", keys: "write" };
6394
- var ROLE_SCOPES = {
6395
- owner: MOST,
6396
- admin: MOST,
6397
- member: { ...MOST, settings: "none" },
6398
- viewer: { repositories: "read", requests: "read", tasks: "read", usage: "read", members: "read", settings: "none", keys: "read" }
5626
+ }
6399
5627
  };
6400
- function serviceId(id) {
6401
- return `service:${id}`;
6402
- }
6403
-
6404
- // server/passwords.ts
6405
- var N = 1 << 15;
6406
- var R = 8;
6407
- var MAX_MEMORY = 128 * N * R * 2;
6408
-
6409
- // server/forge/http.ts
6410
- import { AsyncLocalStorage } from "node:async_hooks";
6411
- import { createHash as createHash3 } from "node:crypto";
6412
-
6413
- // server/vault.ts
6414
- var NO_VAULT = "this orchestrator keeps no sign-ins, tokens or other secrets until whoever runs it sets ORCHESTRATOR_SECRET_KEY (32 random bytes, as from openssl rand -base64 32) and starts it again";
6415
- async function storeSecret(store, vault, tenant, name, value, by) {
6416
- if (!vault) throw new Error(NO_VAULT);
6417
- await store.putSecret(tenant, name, vault.seal(tenant, name, value), by);
5628
+ function hasOwnCli(kind) {
5629
+ return typeof kind === "string" && Object.hasOwn(TOOLS, kind);
6418
5630
  }
6419
- var SEALED_WITHOUT_KEY = "a forge token is stored for this repository, but ORCHESTRATOR_SECRET_KEY is not set; start the orchestrator with the key it was sealed with, or save the token again";
6420
- async function readSecret(store, vault, tenant, name) {
6421
- const sealed = await store.getSecret(tenant, name);
6422
- if (sealed === null) return null;
6423
- if (!vault) throw new Error(SEALED_WITHOUT_KEY);
6424
- return vault.open(tenant, name, sealed);
5631
+ function cliConfig(config) {
5632
+ return config && hasOwnCli(config.kind) ? { ...config, kind: config.kind } : null;
6425
5633
  }
6426
- function maskSecrets(text, secrets) {
6427
- let out = text;
6428
- for (const secret of secrets) {
6429
- if (secret && secret.length >= 4) out = out.split(secret).join("***");
6430
- }
6431
- return out;
5634
+ var VERSION = /\b(\d+\.\d+\.\d+)\b/;
5635
+ async function versionOf(tool, run2) {
5636
+ const ran = await run2(tool, ["--version"]);
5637
+ return ran.code === 0 ? VERSION.exec(ran.stdout.replace(/\x1b\[[0-9;]*m/g, ""))?.[1] ?? null : null;
6432
5638
  }
6433
-
6434
- // server/forge/forge-metrics.ts
6435
- var OPERATIONS = [
6436
- [/\/(merge_requests|pulls)(\/|\?|$)/, "request"],
6437
- [/\/(approvals|reviews)(\/|\?|$)/, "review"],
6438
- [/\/(statuses|status|check-runs)(\/|\?|$)/, "checks"],
6439
- [/\/repository\/commits|\/git\/commits/, "commit"],
6440
- [/\/repository\/files|\/contents\//, "file"],
6441
- [/\/repository\/(branches|tags)|\/(branches|tags)(\/|\?|$)|\/git\/ref/, "ref"],
6442
- [/\/git\/trees/, "tree"],
6443
- [/\/hooks(\/|\?|$)/, "hook"],
6444
- [/\/users?(\/|\?|$)|\/namespaces\//, "account"],
6445
- [/\/installation|\/app\//, "installation"],
6446
- [/^\/(projects|orgs\/[^/]+\/repos|repos\/[^/]+\/[^/]+)(\?|$)/, "repository"]
6447
- ];
6448
- function operationOf(method, path) {
6449
- const verb = /^(GET|POST|PUT|PATCH|DELETE)$/.test(method) ? method.toLowerCase() : "other";
6450
- return `${verb} ${OPERATIONS.find(([pattern]) => pattern.test(path))?.[1] ?? "other"}`;
5639
+ function atLeast(version3, since) {
5640
+ const [a, b] = [version3, since].map((v) => v.split(".").map(Number));
5641
+ for (let n = 0; n < 3; n++) if (a[n] !== b[n]) return a[n] > b[n];
5642
+ return true;
6451
5643
  }
6452
- function statusClass(status2) {
6453
- if (status2 === 0) return "unreachable";
6454
- if (status2 === 429) return "429";
6455
- return `${Math.floor(status2 / 100)}xx`;
5644
+ var TOO_OLD = /unknown (flag|command|shorthand flag)|flag provided but not defined|unknown json field|accepts at most/i;
5645
+ function cliSaid(t, ran) {
5646
+ const told = t.told(ran);
5647
+ return TOO_OLD.test(told) ? `your ${t.tool} does not know what the orchestrator asks of it; update it (${t.install}), then try again` : said(told);
6456
5648
  }
6457
- var ForgeMeter = class {
6458
- calls = /* @__PURE__ */ new Map();
6459
- quota = /* @__PURE__ */ new Map();
6460
- called(forge, host, operation, status2) {
6461
- const key = [forge, host, operation, status2].join("\0");
6462
- this.calls.set(key, (this.calls.get(key) ?? 0) + 1);
6463
- }
6464
- reported(forge, host, remaining, limit) {
6465
- this.quota.set(`${forge}\0${host}`, { remaining, limit });
6466
- }
6467
- };
6468
- var forgeMeter = new ForgeMeter();
6469
-
6470
- // server/forge/http.ts
6471
- var ForgeHttpError = class extends Error {
6472
- constructor(message, status2, retryAt = null) {
6473
- super(message);
6474
- this.status = status2;
6475
- this.retryAt = retryAt;
5649
+ var LOGIN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
5650
+ var OwnCliRefused = class extends OrchestratorError {
5651
+ constructor(message) {
5652
+ super("own-cli", message, 409);
6476
5653
  }
6477
5654
  };
6478
- function rateLimitedUntil(res, now = Date.now()) {
6479
- const spent = res.headers.get("x-ratelimit-remaining") === "0" || res.headers.get("ratelimit-remaining") === "0";
6480
- if (res.status !== 429 && !(res.status === 403 && spent)) return null;
6481
- const after = res.headers.get("retry-after");
6482
- if (after && /^[0-9]+$/.test(after)) return new Date(now + Number(after) * 1e3).toISOString();
6483
- if (after && Number.isFinite(Date.parse(after))) return new Date(Date.parse(after)).toISOString();
6484
- const reset = res.headers.get("x-ratelimit-reset") ?? res.headers.get("ratelimit-reset");
6485
- if (reset && /^[0-9]+$/.test(reset)) return new Date(Number(reset) * 1e3).toISOString();
6486
- return new Date(now + 6e4).toISOString();
5655
+ async function signedIn(kind, host, run2) {
5656
+ const t = TOOLS[kind];
5657
+ const signIn = await t.signIn(host, run2);
5658
+ if (!signIn.installed) throw new OwnCliRefused(`${t.name} is not installed on this machine; install it (${t.install}), then sign in with \`${t.login(host)}\``);
5659
+ if (signIn.problem) throw new OwnCliRefused(signIn.problem);
5660
+ if (!signIn.signedIn) throw new OwnCliRefused(`${t.name} is not signed in to ${host}; sign in with \`${t.login(host)}\`, then try again`);
5661
+ return signIn;
6487
5662
  }
6488
- var MESSAGE_MAX = 300;
6489
- var priority = new AsyncLocalStorage();
6490
- var INTERACTIVE_RESERVE = 0.1;
6491
- var BACKOFF_MIN_MS = 3e4;
6492
- var BACKOFF_MAX_MS = 15 * 6e4;
6493
- var KEPT_ANSWERS = 500;
6494
- var quotas = /* @__PURE__ */ new Map();
6495
- var kept = /* @__PURE__ */ new Map();
6496
- function readQuota(res, now, previous) {
6497
- const header = (...names) => names.map((n) => res.headers.get(n)).find((v) => v !== null && /^[0-9]+$/.test(v));
6498
- const remaining = header("x-ratelimit-remaining", "ratelimit-remaining");
6499
- const limit = header("x-ratelimit-limit", "ratelimit-limit");
6500
- const reset = header("x-ratelimit-reset", "ratelimit-reset");
6501
- const retry = rateLimitedUntil(res, now);
6502
- return {
6503
- until: retry ? Math.min(Math.max(Date.parse(retry), now + BACKOFF_MIN_MS), now + BACKOFF_MAX_MS) : null,
6504
- remaining: remaining !== void 0 ? Number(remaining) : previous?.remaining ?? null,
6505
- limit: limit !== void 0 ? Number(limit) : previous?.limit ?? null,
6506
- resetAt: reset !== void 0 ? Number(reset) * 1e3 : previous?.resetAt ?? null
5663
+ async function ownCliReady(kind, host, run2 = runOwnCli) {
5664
+ await signedIn(kind, host, run2);
5665
+ }
5666
+ var said = (text) => redactLine(text.replace(/\p{C}+/gu, " ").trim().slice(0, 300));
5667
+ function ownCredentialConfig(kind) {
5668
+ return [["credential.helper", ""], ["credential.helper", TOOLS[kind].helper]];
5669
+ }
5670
+ function createOwnCliForge(config, workRoot, mirror, gitEnv2, run2 = runOwnCli) {
5671
+ const kind = config.kind;
5672
+ const t = TOOLS[kind];
5673
+ const REQUEST_URL = /https?:\/\/\S+\/(?:pull|-\/merge_requests)\/(\d+)/;
5674
+ const NO_ASSIGNMENT = { reviewers: [], labels: [] };
5675
+ const OWN_CHECK = /^teamhandbook\/[a-z][a-z-]{0,39}$/;
5676
+ const openedFor = async (branch, as) => {
5677
+ const read = await run2(t.tool, t.view(config.project, branch, as));
5678
+ if (t.failed(read) !== null) return null;
5679
+ const found = t.pick(parsed(read.stdout), branch);
5680
+ const number = Number(found?.number);
5681
+ const url = String(found?.url ?? "");
5682
+ return Number.isInteger(number) && number > 0 && /^https?:\/\//.test(url) ? { number, url } : null;
6507
5683
  };
6508
- }
6509
- function messageOf(payload) {
6510
- if (!payload || typeof payload !== "object") return "";
6511
- const { message, error } = payload;
6512
- const value = message ?? error;
6513
- if (typeof value === "string") return value;
6514
- return value === void 0 ? "" : JSON.stringify(value);
6515
- }
6516
- function forgeHttp(forge, baseUrl, token2, headers, fetchImpl) {
6517
- const root2 = baseUrl.replace(/\/+$/, "");
6518
- const host = new URL(root2).host;
6519
- const scope = `${forge}\0${host}\0${createHash3("sha256").update(token2).digest("hex").slice(0, 16)}`;
5684
+ const createRequest = (branch, target, title, body, assignment, as) => {
5685
+ const { args, input } = t.create(config.project, branch, target, title, body, assignment, as);
5686
+ return run2(t.tool, args, input);
5687
+ };
5688
+ const opened = async (repo, answer, branch, assignment, as) => {
5689
+ const url = t.answerNames ? REQUEST_URL.exec(answer.stdout) ?? REQUEST_URL.exec(answer.stderr) : null;
5690
+ const found = url ? { number: Number(url[1]), url: url[0] } : await openedFor(branch, as);
5691
+ if (!found) throw new OwnCliRefused(`${t.tool} opened a request for ${branch} in ${repo.name}, but its number was not read; find it among ${repo.name}'s requests on ${FORGES[kind].label}`);
5692
+ const notes = t.assign ? await t.assign(config.project, found.number, assignment, as, run2) : [];
5693
+ return { ...found, ...notes.length ? { notes } : {} };
5694
+ };
5695
+ const targetOf3 = async (repo) => (await gitAsyncMaybe(["symbolic-ref", "--short", "HEAD"], mirror(repo)) ?? "").trim() || "main";
6520
5696
  return {
6521
- async request(method, path, body) {
6522
- const operation = operationOf(method, path);
6523
- const now = Date.now();
6524
- const quota = quotas.get(scope);
6525
- const lowOnQuota = quota !== void 0 && quota.remaining !== null && quota.limit !== null && quota.remaining < quota.limit * INTERACTIVE_RESERVE && (quota.resetAt ?? 0) > now;
6526
- const waitUntil = quota?.until && quota.until > now ? quota.until : lowOnQuota && priority.getStore() === "background" ? quota.resetAt : null;
6527
- if (waitUntil) {
6528
- forgeMeter.called(forge, host, operation, "held");
6529
- const until = new Date(waitUntil).toISOString();
6530
- throw new ForgeHttpError(`${forge} asked the orchestrator to wait until ${until}; ${method} ${path} was not sent, try again after that`, 429, until);
6531
- }
6532
- const cacheKey = method === "GET" ? `${scope}\0${path}` : null;
6533
- const before = cacheKey ? kept.get(cacheKey) : void 0;
6534
- let res;
5697
+ kind,
5698
+ async open(repo, change2) {
5699
+ checkBranch(change2.branch);
5700
+ const { as } = await signedIn(kind, new URL(repo.url).host, run2);
5701
+ const target = await targetOf3(repo);
5702
+ const work = await scratch(workRoot, "own-cli-");
6535
5703
  try {
6536
- res = await fetchImpl(`${root2}${path}`, {
6537
- method,
6538
- headers: { ...headers, ...before ? { "if-none-match": before.etag } : {}, ...body === void 0 ? {} : { "content-type": "application/json" } },
6539
- body: body === void 0 ? void 0 : JSON.stringify(body),
6540
- // Not followed: the token goes to the address an admin entered and nowhere it points.
6541
- redirect: "manual",
6542
- signal: AbortSignal.timeout(3e4)
5704
+ const headSha = await changeCommit(mirror(repo), work, change2, repo.name);
5705
+ const env2 = await gitEnv2(repo);
5706
+ if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
5707
+ const taken = await gitAsyncMaybe(["ls-remote", "--heads", repo.url, change2.branch], work, { env: env2 });
5708
+ if (taken === null) throw new OwnCliRefused(`git did not reach ${repo.name} with your ${t.tool} sign-in; check it with \`${t.tool} auth status\``);
5709
+ if (taken.trim()) throw new ForgeRefusal(`branch ${change2.branch} already exists in ${repo.name}; remove it on ${FORGES[kind].label}, then try again`);
5710
+ await gitAsync(["push", "--porcelain", repo.url, `${headSha}:refs/heads/${change2.branch}`], work, void 0, void 0, { env: env2 }).catch((err) => {
5711
+ throw new OwnCliRefused(`git did not push ${change2.branch} to ${repo.name} with your ${t.tool} sign-in: ${said(err.stderr || err.message)}; check it with \`${t.tool} auth status\`, then try again`);
6543
5712
  });
6544
- } catch (err) {
6545
- forgeMeter.called(forge, host, operation, statusClass(0));
6546
- throw new ForgeHttpError(maskSecrets(`${forge} is unreachable on ${method} ${path}; try again, and if it repeats, whoever runs the orchestrator checks its network (${err.message})`, [token2]).slice(0, MESSAGE_MAX), 0);
6547
- }
6548
- forgeMeter.called(forge, host, operation, statusClass(res.status));
6549
- const seen2 = readQuota(res, now, quota);
6550
- quotas.set(scope, seen2);
6551
- if (seen2.remaining !== null) forgeMeter.reported(forge, host, seen2.remaining, seen2.limit);
6552
- if (res.status === 304 && before) {
6553
- return before.text ? JSON.parse(before.text) : null;
6554
- }
6555
- if (res.status >= 300 && res.status < 400) {
6556
- throw new ForgeHttpError(`${forge} answered ${res.status} on ${method} ${path}, a redirect the orchestrator does not follow; an owner or an admin checks the repository's API address`, res.status);
6557
- }
6558
- const text = await res.text();
6559
- const etag = res.headers.get("etag");
6560
- if (cacheKey && res.ok && etag) {
6561
- kept.delete(cacheKey);
6562
- kept.set(cacheKey, { etag, text });
6563
- if (kept.size > KEPT_ANSWERS) kept.delete(kept.keys().next().value);
5713
+ const assignment = change2.assignment ?? NO_ASSIGNMENT;
5714
+ const answer = await createRequest(change2.branch, target, change2.title, change2.body, assignment, as);
5715
+ if (answer.code !== 0) {
5716
+ const left = await gitAsync(["push", "--porcelain", repo.url, `:refs/heads/${change2.branch}`], work, void 0, void 0, { env: env2 }).then(
5717
+ () => "the branch was removed again",
5718
+ () => `the branch stayed: ${change2.branch}`
5719
+ );
5720
+ throw new OwnCliRefused(`${t.tool} did not open the request: ${cliSaid(t, answer)}; ${left}; check it with \`${t.tool} auth status\`, then try again`);
5721
+ }
5722
+ return { ...await opened(repo, answer, change2.branch, assignment, as), branch: change2.branch, headSha };
5723
+ } finally {
5724
+ await rm3(work, { recursive: true, force: true });
6564
5725
  }
6565
- let payload = null;
5726
+ },
5727
+ // The branch as the forge holds it now, read with the person's sign-in; the push goes without
5728
+ // force, so a branch someone moved meanwhile makes git refuse rather than lose their commit.
5729
+ async updateBranch(repo, branch, update) {
5730
+ checkBranch(branch);
5731
+ await ownCliReady(kind, new URL(repo.url).host, run2);
5732
+ const env2 = await gitEnv2(repo);
5733
+ if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
5734
+ const work = await scratch(workRoot, "own-cli-update-");
6566
5735
  try {
6567
- payload = text ? JSON.parse(text) : null;
6568
- } catch {
6569
- payload = null;
6570
- }
6571
- if (!res.ok) {
6572
- const detail = messageOf(payload);
6573
- const message = `${forge} answered ${res.status} on ${method} ${path}${detail ? `: ${detail}` : ""}`;
6574
- throw new ForgeHttpError(maskSecrets(message, [token2]).slice(0, MESSAGE_MAX), res.status, rateLimitedUntil(res));
5736
+ if (await gitAsyncMaybe(["fetch", "--quiet", repo.url, `refs/heads/${branch}:refs/orchestrator/branch`], work, { env: env2 }) === null) {
5737
+ throw new ForgeRefusal(`branch ${branch} was not read from ${repo.name}; check it is on ${FORGES[kind].label}, then check your sign-in with \`${t.tool} auth status\``);
5738
+ }
5739
+ const head = (await gitAsync(["rev-parse", "refs/orchestrator/branch"], work)).trim();
5740
+ if (head !== update.expectedHead) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
5741
+ const headSha = await changeCommit(work, work, { title: update.title, body: "", commitBody: update.commitBody ?? "", branch, baseSha: head, files: update.files, author: update.author }, repo.name);
5742
+ await gitAsync(["push", "--porcelain", repo.url, `${headSha}:refs/heads/${branch}`], work, void 0, void 0, { env: env2 }).catch((err) => {
5743
+ const told = err.stderr || err.message;
5744
+ if (/non-fast-forward|fetch first|\[rejected\]/.test(told)) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
5745
+ throw new OwnCliRefused(`git did not push ${branch} to ${repo.name} with your ${t.tool} sign-in: ${said(told)}; check it with \`${t.tool} auth status\`, then try again`);
5746
+ });
5747
+ return { headSha };
5748
+ } finally {
5749
+ await rm3(work, { recursive: true, force: true });
6575
5750
  }
6576
- return payload;
6577
- }
6578
- };
6579
- }
6580
- var BRANCH2 = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
6581
- function checkBranch(branch) {
6582
- if (!BRANCH2.test(branch) || branch.includes("..")) throw new Error(`invalid branch name ${JSON.stringify(branch)}`);
6583
- }
6584
-
6585
- // server/integrations/health.ts
6586
- var FAILURES_BEFORE_ALERT = 3;
6587
- var REALERT_MS = 6 * 60 * 6e4;
6588
- var WHAT = {
6589
- sync: "Reading the repository",
6590
- forge: "Reaching the repository's forge",
6591
- tasks: "Running tasks"
6592
- };
6593
- var states = /* @__PURE__ */ new Map();
6594
- var keyOf = (tenant, check) => `${tenant}\0${check.kind}\0${"repoId" in check ? check.repoId : ""}`;
6595
- async function noteHealth(ctx, check, outcome, now = Date.now()) {
6596
- const key = keyOf(ctx.tenant, check);
6597
- const state = states.get(key) ?? { failures: 0, alertedAt: null, broken: false, told: false };
6598
- states.set(key, state);
6599
- const repoId = "repoId" in check ? check.repoId : null;
6600
- const record3 = (kind, detail) => recordEvent(ctx, ORCHESTRATOR_ACTOR, kind, { repoId, subject: `health:${check.kind}`, detail }).catch((err) => console.error(`health: the event log did not take ${kind}: ${err.message}`));
6601
- if (outcome.ok) {
6602
- const wasTold = state.broken && state.told;
6603
- Object.assign(state, { failures: 0, broken: false, told: false });
6604
- if (wasTold) await record3("health.recovered", `${WHAT[check.kind]} works again`);
6605
- return;
6606
- }
6607
- state.failures++;
6608
- if (state.broken || state.failures < FAILURES_BEFORE_ALERT) return;
6609
- state.broken = true;
6610
- if (state.alertedAt !== null && now - state.alertedAt < REALERT_MS) return;
6611
- state.alertedAt = now;
6612
- state.told = true;
6613
- await record3("health.degraded", `${WHAT[check.kind]} failed ${state.failures} times in a row; the last: ${outcome.detail}`);
6614
- }
6615
- function forgeBroken(err) {
6616
- return err instanceof ForgeHttpError && (err.status === 0 || err.status === 401 || err.status === 403 || err.status >= 500);
6617
- }
6618
- function watchedForge(ctx, repo, provider) {
6619
- if (provider.kind === "local") return provider;
6620
- const check = { kind: "forge", repoId: repo.id };
6621
- const watch = (call) => call.then(
6622
- async (value) => {
6623
- await noteHealth(ctx, check, { ok: true });
6624
- return value;
6625
5751
  },
6626
- async (err) => {
6627
- if (forgeBroken(err)) await noteHealth(ctx, check, { ok: false, detail: err.message });
6628
- throw err;
6629
- }
6630
- );
6631
- return {
6632
- kind: provider.kind,
6633
- open: (r, change2) => watch(provider.open(r, change2)),
6634
- ...provider.openForBranch ? { openForBranch: (r, pushed) => watch(provider.openForBranch(r, pushed)) } : {},
6635
- ...provider.updateBranch ? { updateBranch: (r, branch, update) => watch(provider.updateBranch(r, branch, update)) } : {},
6636
- ...provider.status ? { status: (r, n) => watch(provider.status(r, n)) } : {},
6637
- ...provider.list ? { list: (r) => watch(provider.list(r)) } : {},
6638
- ...provider.setCommitStatus ? { setCommitStatus: (sha, c) => watch(provider.setCommitStatus(sha, c)) } : {}
6639
- };
6640
- }
6641
-
6642
- // server/forge/oauth-github.ts
6643
- import { createHash as createHash4, createHmac, createSign, timingSafeEqual } from "node:crypto";
6644
-
6645
- // server/forge/oauth.ts
6646
- import { randomBytes as randomBytes4 } from "node:crypto";
6647
-
6648
- // server/connect.ts
6649
- import { isIP as isIP3 } from "node:net";
6650
-
6651
- // server/versions.ts
6652
- async function claimsAbove(mirror, head, current) {
6653
- const branches = (await gitAsync(["for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/"], mirror)).split("\n").filter(Boolean).map((line) => ({ sha: line.slice(0, line.indexOf(" ")), branch: line.slice(line.indexOf(" ") + 1 + "refs/heads/".length) })).filter((b) => b.sha !== head);
6654
- if (!branches.length) return [];
6655
- const out = await gitAsyncBytes(["cat-file", "--batch"], mirror, branches.map((b) => `${b.sha}:${PLUGIN_MANIFEST}`).join("\n") + "\n");
6656
- const claims = [];
6657
- let at2 = 0;
6658
- for (const { branch } of branches) {
6659
- const end = out.indexOf(10, at2);
6660
- const header = out.subarray(at2, end).toString("utf8");
6661
- at2 = end + 1;
6662
- const size = / blob (\d+)$/.exec(header)?.[1];
6663
- if (size === void 0) continue;
6664
- const text = out.subarray(at2, at2 + Number(size)).toString("utf8");
6665
- at2 += Number(size) + 1;
6666
- try {
6667
- const version3 = JSON.parse(text).version;
6668
- if (typeof version3 === "string" && (compareVersions(version3, current) ?? 0) > 0) claims.push({ branch, version: version3 });
6669
- } catch {
6670
- continue;
5752
+ // The branch is the person's own work, pushed by their runner: it is read, never written or taken back.
5753
+ async openForBranch(repo, pushed) {
5754
+ checkBranch(pushed.branch);
5755
+ const { as } = await signedIn(kind, new URL(repo.url).host, run2);
5756
+ const env2 = await gitEnv2(repo);
5757
+ if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
5758
+ const heads = await gitAsyncMaybe(["ls-remote", "--heads", repo.url, `refs/heads/${pushed.branch}`], tmpdir2(), { env: env2 });
5759
+ if (heads === null) throw new OwnCliRefused(`git did not reach ${repo.name} with your ${t.tool} sign-in; check it with \`${t.tool} auth status\``);
5760
+ const headSha = /^([0-9a-f]{40})\s/.exec(heads)?.[1];
5761
+ if (!headSha) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
5762
+ const assignment = pushed.assignment ?? NO_ASSIGNMENT;
5763
+ const answer = await createRequest(pushed.branch, pushed.target ?? await targetOf3(repo), pushed.title, pushed.body, assignment, as);
5764
+ if (answer.code !== 0) throw new OwnCliRefused(`${t.tool} did not open the request: ${cliSaid(t, answer)}; the branch stays as it was pushed, so open it again once \`${t.tool} auth status\` says you are signed in`);
5765
+ return { ...await opened(repo, answer, pushed.branch, assignment, as), branch: pushed.branch, headSha };
5766
+ },
5767
+ // A commit status alone, in the orchestrator's own checks: a comment, a label or a merge is never written with the person's sign-in.
5768
+ async setCommitStatus(sha, check) {
5769
+ if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error("a commit status is set on a full commit id");
5770
+ if (!OWN_CHECK.test(check.context)) throw new Error(`${check.context} is not one of the orchestrator's own checks`);
5771
+ const { as } = await signedIn(kind, t.hostOf(config.apiUrl), run2);
5772
+ const { args, input } = t.writeStatus(config.project, sha, { ...check, description: check.description.slice(0, 140) }, as);
5773
+ const wrote = await run2(t.tool, args, input);
5774
+ if (t.failed(wrote) !== null) throw new OwnCliRefused(`${t.tool} did not write the ${check.context} check on ${sha.slice(0, 7)}: ${cliSaid(t, wrote)}`);
5775
+ },
5776
+ async status(repo, number) {
5777
+ const { as } = await signedIn(kind, new URL(repo.url).host, run2);
5778
+ const read = await run2(t.tool, t.state(config.project, number, as));
5779
+ if (t.failed(read) !== null) throw new OwnCliRefused(`${t.tool} did not read request ${number}: ${cliSaid(t, read)}`);
5780
+ const body = parsed(read.stdout);
5781
+ if (!body) throw new OwnCliRefused(`${t.tool} answered request ${number}'s state with something other than JSON; update it (${t.install}), then try again`);
5782
+ const state = String(body.state ?? "").toLowerCase();
5783
+ const head = body.headRefOid ?? body.sha ?? body.head?.sha;
5784
+ if (state === "merged" || body.merged === true) return forgeState("merged", forgeTime(body.mergedAt ?? body.merged_at), head);
5785
+ return forgeState(state === "open" || state === "opened" ? "open" : "closed", null, head);
6671
5786
  }
6672
- }
6673
- return claims.sort((a, b) => a.branch.localeCompare(b.branch));
5787
+ };
6674
5788
  }
6675
- async function versionRaise(mirror, head) {
6676
- const text = await gitAsyncMaybe(["show", `${head}:${PLUGIN_MANIFEST}`], mirror);
6677
- if (text === null) return null;
6678
- let plugin;
5789
+ function parsed(text) {
6679
5790
  try {
6680
- plugin = JSON.parse(text);
5791
+ const value = JSON.parse(text);
5792
+ return value && typeof value === "object" ? value : null;
6681
5793
  } catch {
6682
5794
  return null;
6683
5795
  }
6684
- const current = plugin.version;
6685
- if (typeof current !== "string" || compareVersions(current, current) === null) return null;
6686
- const past = await claimsAbove(mirror, head, current);
6687
- const version3 = versionPast(current, past);
6688
- const target = (await gitAsyncMaybe(["symbolic-ref", "--short", "HEAD"], mirror))?.trim() || null;
6689
- return { file: { path: PLUGIN_MANIFEST, content: JSON.stringify({ ...plugin, version: version3 }, null, 2) + "\n" }, version: version3, past, target };
6690
- }
6691
- function versionRaiseNote(raise) {
6692
- const merged = raise.past.filter((c) => c.branch === raise.target);
6693
- const open = raise.past.filter((c) => c.branch !== raise.target);
6694
- const parts = [
6695
- ...merged.length ? [`past ${merged[0].version}, which ${raise.target} reached since this change was prepared`] : [],
6696
- ...open.length ? [`past ${open.map((c) => `${c.version} on ${c.branch}`).join(" and ")}, which ${open.length === 1 ? "is" : "are"} not merged yet`] : []
6697
- ];
6698
- return `Raises the plugin to version ${raise.version}${parts.length ? `, ${parts.join(", and ")}` : ""}, so teammates fetch it once this is merged.`;
6699
- }
6700
- var LINE_BACK_COMMITS = 100;
6701
- async function versionLineBack(mirror, head) {
6702
- const log = await gitAsyncMaybe(["log", "--first-parent", `-n${LINE_BACK_COMMITS}`, "-G", '"version"', "--format=%H%x00%an%x00%aI", head, "--", PLUGIN_MANIFEST], mirror);
6703
- const commits = (log ?? "").split("\n").filter(Boolean).map((line) => {
6704
- const [sha, author, date] = line.split("\0");
6705
- return { sha, author: (author ?? "").replace(/\p{C}+/gu, " ").trim().slice(0, 200), date: date ?? "" };
6706
- });
6707
- if (!commits.length) return null;
6708
- const out = await gitAsyncBytes(["cat-file", "--batch"], mirror, commits.flatMap((c) => [`${c.sha}:${PLUGIN_MANIFEST}`, `${c.sha}^:${PLUGIN_MANIFEST}`]).join("\n") + "\n");
6709
- const versions = [];
6710
- let at2 = 0;
6711
- while (at2 < out.length) {
6712
- const end = out.indexOf(10, at2);
6713
- const header = out.subarray(at2, end).toString("utf8");
6714
- at2 = end + 1;
6715
- const size = / blob (\d+)$/.exec(header)?.[1];
6716
- if (size === void 0) {
6717
- versions.push(void 0);
6718
- continue;
6719
- }
6720
- const text = out.subarray(at2, at2 + Number(size)).toString("utf8");
6721
- at2 += Number(size) + 1;
6722
- let version3;
6723
- try {
6724
- version3 = JSON.parse(text).version;
6725
- } catch {
6726
- version3 = void 0;
6727
- }
6728
- versions.push(typeof version3 === "string" ? version3 : null);
6729
- }
6730
- for (const [i, commit] of commits.entries()) {
6731
- const [now, before] = [versions[2 * i], versions[2 * i + 1]];
6732
- if (typeof now === "string" && before === null) return { ...commit, version: now.replace(/\p{C}+/gu, " ").trim().slice(0, 40) };
6733
- if (before === void 0) return null;
6734
- }
6735
- return null;
6736
5796
  }
6737
5797
 
6738
- // server/branches.ts
6739
- import { randomBytes as randomBytes3 } from "node:crypto";
6740
- var ORCHESTRATOR_BRANCH_PREFIX = `${DEFAULT_BRANCH_PREFIX}orchestrator-`;
6741
- var TICKET_PLACEHOLDER = "<TICKET>";
6742
- var BRANCH_MAX = 200;
6743
- function recordedCommitPrefix(value) {
6744
- if (typeof value !== "string") return {};
6745
- const prefix = value.trim();
6746
- const problem = commitPrefixProblem(prefix);
6747
- return problem ? { problem } : { prefix };
6748
- }
6749
- async function teamNaming(mirror, head) {
6750
- const text = await gitAsyncMaybe(["show", `${head}:${TEAM_PREFIX_FILE}`], mirror);
6751
- let json = {};
6752
- try {
6753
- json = text ? JSON.parse(text) : {};
6754
- } catch {
6755
- return {};
6756
- }
6757
- const example = typeof json.branchExample === "string" ? json.branchExample.trim() : "";
6758
- const { prefix } = recordedCommitPrefix(json.commitPrefix);
6759
- return {
6760
- ...prefix !== void 0 ? { commitPrefix: prefix } : {},
6761
- ...example && !branchExampleProblem(example) ? { branchExample: example } : {}
6762
- };
6763
- }
6764
- function proposedBranch(topic, naming) {
6765
- const slug = `${topic}-${randomBytes3(3).toString("hex")}`;
6766
- const proposal = proposeBranch(slug, { repoUrl: "", marketplaceName: "", ...naming.commitPrefix !== void 0 ? { commitPrefix: naming.commitPrefix } : {} }, naming.branchExample, {}, /* @__PURE__ */ new Set());
6767
- if (!("branch" in proposal)) return proposal.template.replace("<TICKET>", TICKET_PLACEHOLDER);
6768
- return proposal.branch === slug ? `${ORCHESTRATOR_BRANCH_PREFIX}${slug}` : proposal.branch;
5798
+ // server/store.ts
5799
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
5800
+
5801
+ // server/tasks/log-bus.ts
5802
+ import { EventEmitter } from "node:events";
5803
+ var bus = new EventEmitter();
5804
+ bus.setMaxListeners(0);
5805
+
5806
+ // server/tasks/types.ts
5807
+ var ORCHESTRATOR_AGENT = "orchestrator";
5808
+
5809
+ // server/runner-auth.ts
5810
+ import { createHash as createHash3, createPublicKey, randomBytes as randomBytes2, sign, verify } from "node:crypto";
5811
+ var RUNNER_PROTOCOL = 1;
5812
+ var SIGNATURE_HEADER = "x-runner-signature";
5813
+ function canonical(call) {
5814
+ const body = createHash3("sha256").update(call.body).digest("hex");
5815
+ return Buffer.from(["v1", call.method.toUpperCase(), call.path, String(call.time), call.nonce, body].join("\n"));
6769
5816
  }
6770
- async function branchProblem(name) {
6771
- if (!name.trim() || name !== name.trim()) return "the branch name is empty or starts or ends with a space";
6772
- if (name.includes(TICKET_PLACEHOLDER)) return `put the ticket in place of ${TICKET_PLACEHOLDER} in the branch name`;
6773
- if (name.length > BRANCH_MAX) return `the branch name is longer than ${BRANCH_MAX} characters`;
6774
- if (/\p{C}/u.test(name)) return "the branch name carries a control character";
6775
- const trace = branchTrace(name);
6776
- if (trace) return `that branch name cannot be used: ${trace}`;
6777
- if (name.startsWith("-") || name.includes("@{") || await gitAsyncMaybe(["check-ref-format", "--branch", name], process.cwd()) === null) {
6778
- return "git does not accept that as a branch name";
6779
- }
6780
- return null;
5817
+ function signRunnerRequest(privateKey, call) {
5818
+ const signed = { ...call, time: call.time ?? Math.floor(Date.now() / 1e3), nonce: call.nonce ?? randomBytes2(16).toString("base64url") };
5819
+ return `v1 t=${signed.time} n=${signed.nonce} s=${sign(null, canonical(signed), privateKey).toString("base64url")}`;
6781
5820
  }
5821
+ var ED25519_SPKI = Buffer.from("302a300506032b6570032100", "hex");
6782
5822
 
6783
- // server/changes.ts
6784
- var ChangeRefused = class extends OrchestratorError {
6785
- constructor(message) {
6786
- super("change-refused", message, 400);
6787
- }
5823
+ // shared/runner-wire.ts
5824
+ var PROTOCOL_HEADER = "x-runner-protocol";
5825
+ var POLL_WAIT_MAX_MS = 25e3;
5826
+ var EVENTS_PER_BATCH = 500;
5827
+ var BATCH_BYTES = 512 * 1024;
5828
+ var COMMAND_MAX = 300;
5829
+ var PLAN_TEXT_MAX = 2e4;
5830
+ var TESTS_OUTPUT = "tests";
5831
+ var OUTPUT_LINES_MAX = 200;
5832
+ var OUTPUT_LINE_MAX = 2e3;
5833
+ var PATCH_LINES_MAX = 40;
5834
+ var TODOS_MAX = 30;
5835
+ var TODO_TEXT_MAX = 200;
5836
+ var CALL_BYTES = 1024 * 1024;
5837
+ var RUNNER_PATHS = {
5838
+ hello: "/api/runner/hello",
5839
+ claim: "/api/runner/claim",
5840
+ /** The machine disconnects itself: the orchestrator revokes it, so its token works nowhere after. */
5841
+ disconnect: "/api/runner/disconnect",
5842
+ poll: "/api/runner/poll",
5843
+ /** What the machine says of its agents, at start and every few minutes: words only, never an account. */
5844
+ status: "/api/runner/status",
5845
+ renew: (taskId) => `/api/runner/tasks/${taskId}/renew`,
5846
+ events: (taskId) => `/api/runner/tasks/${taskId}/events`,
5847
+ agentRequest: (taskId) => `/api/runner/tasks/${taskId}/requests`,
5848
+ progress: (taskId) => `/api/runner/tasks/${taskId}/progress`,
5849
+ forgeRequest: (taskId) => `/api/runner/tasks/${taskId}/request`,
5850
+ finish: (taskId) => `/api/runner/tasks/${taskId}/finish`,
5851
+ /** The follow-ups that reached the task's agent. */
5852
+ followUpsDelivered: (taskId) => `/api/runner/tasks/${taskId}/follow-ups`,
5853
+ /** One of the task's attachments, its bytes, for the machine to put in the task's own folder. */
5854
+ attachment: (taskId, attachmentId) => `/api/runner/tasks/${taskId}/attachments/${attachmentId}`,
5855
+ /** The machine's answer to one folder list its person's screen asked it for. */
5856
+ folders: (nonce) => `/api/runner/folders/${nonce}`,
5857
+ /** The machine's answer to one undo of a task's change in one of its folders. */
5858
+ undo: (nonce) => `/api/runner/undos/${nonce}`,
5859
+ /** The machine's answer to one lesson it was handed for its person's review queue. */
5860
+ lessons: (nonce) => `/api/runner/lessons/${nonce}`,
5861
+ /** The machine's reading of one folder project's checks. */
5862
+ checks: (nonce) => `/api/runner/checks/${nonce}`,
5863
+ /** The machine's answer to one read or decision of a lesson its person asked for on a task's page. */
5864
+ lessonOps: (nonce) => `/api/runner/lesson-ops/${nonce}`,
5865
+ pushes: (nonce) => `/api/runner/pushes/${nonce}`
6788
5866
  };
6789
- var MCP_FILE = ".mcp.json";
6790
- var CI_BUMP_SCRIPT = "scripts/bump-version.mjs";
6791
- function show(mirror, head, path) {
6792
- return gitAsyncMaybe(["show", `${head}:${path}`], mirror);
6793
- }
6794
- async function filesUnder(mirror, head, dir) {
6795
- const out = await gitAsyncMaybe(["ls-tree", "-r", "--name-only", head, "--", dir], mirror);
6796
- return out ? out.split("\n").filter(Boolean) : [];
6797
- }
6798
- async function skillFiles(input, exists2, mirror, head) {
6799
- if (typeof input.content !== "string") throw new ChangeRefused("SKILL.md is empty");
6800
- const problem = skillProblem(input.slug, input.content);
6801
- if (problem) throw new ChangeRefused(problem);
6802
- const content = input.content.replace(/\r\n/g, "\n");
6803
- const path = `skills/${input.slug}/SKILL.md`;
6804
- if (exists2 && await show(mirror, head, path) === content) throw new ChangeRefused("SKILL.md is unchanged");
6805
- return [{ path, content: content.endsWith("\n") ? content : `${content}
6806
- ` }];
6807
- }
6808
- function cleanList(values, what) {
6809
- if (!Array.isArray(values) || !values.every((v) => typeof v === "string")) throw new ChangeRefused(`${what} is a list of names`);
6810
- return [...new Set(values.map((v) => v.trim()).filter(Boolean))];
6811
- }
6812
- function describeServer(name, config, requiresEnv) {
6813
- const lines = ["", `- server: \`${name}\``];
6814
- if (typeof config.url === "string") lines.push(`- endpoint: \`${config.url}\``);
6815
- if (typeof config.command === "string") {
6816
- const args = Array.isArray(config.args) ? config.args.map(String) : [];
6817
- lines.push(`- command: \`${[config.command, ...args].join(" ")}\``);
6818
- lines.push("", "Enabling the plugin runs that command on every teammate's machine, with their privileges. Review it the way you would review a dependency.");
6819
- }
6820
- if (requiresEnv.length) lines.push("", `Each teammate sets ${requiresEnv.map((v) => `\`${v}\``).join(", ")} before it starts.`);
6821
- return lines;
6822
- }
6823
- function commandRefusal(name, audit) {
6824
- if (audit.reason === "unsafe-name") return "a command name is lower-case letters, digits and dashes, with a colon between a folder and the name, at most four deep, and not a device name Windows keeps, such as con or nul";
6825
- const line = audit.secret?.line ?? (audit.identity?.where === "name" ? void 0 : audit.identity?.line);
6826
- const where = audit.identity?.where === "name" ? "its name" : `commands/${commandFile(name)}${line ? ` line ${line}` : ""}`;
6827
- if (audit.reason === "secret") return `/${name} is not shareable as written: ${where} looks like it contains a secret (${audit.detail}); move the value into an environment variable and refer to it by name`;
6828
- return `/${name} is not shareable as written: ${where} carries a trace of one machine (${audit.detail}); the teammate who types it has no such account or directory, so take it out`;
6829
- }
6830
- function serverName(value) {
6831
- const name = String(value ?? "");
6832
- if (!SERVER_NAME.test(name)) throw new ChangeRefused("a server name is letters, digits, dot, dash or underscore");
6833
- return name;
6834
- }
6835
- function withoutServer(existing, name) {
6836
- let parsed2 = null;
6837
- try {
6838
- parsed2 = existing === null ? null : JSON.parse(existing);
6839
- } catch {
6840
- throw new ChangeRefused(`${MCP_FILE} is not valid JSON; fix it in the repository first, the orchestrator will not overwrite a file it cannot read`);
6841
- }
6842
- const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
6843
- if (existing !== null && !isObject(parsed2)) throw new ChangeRefused(`${MCP_FILE} is not a JSON object`);
6844
- const servers = isObject(parsed2) ? isObject(parsed2.mcpServers) ? parsed2.mcpServers : parsed2 : {};
6845
- if (!Object.hasOwn(servers, name)) throw new ChangeRefused(`${MCP_FILE} declares no server ${name} to remove`);
6846
- delete servers[name];
6847
- return JSON.stringify(parsed2, null, 2) + "\n";
6848
- }
6849
- async function buildChange(mirror, head, raw) {
6850
- const input = raw ?? {};
6851
- switch (input.kind) {
6852
- case "skill.add":
6853
- case "skill.edit": {
6854
- const slug = String(input.slug ?? "");
6855
- if (!SKILL_SLUG.test(slug)) throw new ChangeRefused("a skill name is lower-case letters, digits and dashes");
6856
- const exists2 = (await filesUnder(mirror, head, `skills/${slug}`)).length > 0;
6857
- if (input.kind === "skill.add" && exists2) throw new ChangeRefused(`${slug} already exists; edit it instead`);
6858
- if (input.kind === "skill.edit" && !exists2) throw new ChangeRefused(`there is no skill ${slug} to edit`);
6859
- return {
6860
- files: await skillFiles({ slug, content: input.content }, exists2, mirror, head),
6861
- proposal: `feat(skill): ${exists2 ? "update" : "add"} ${slug}`,
6862
- body: [`${exists2 ? "Updates" : "Adds"} the skill \`${slug}\`.`],
6863
- topic: `skill-${slug}`
6864
- };
5867
+ var FOLDER_TEXT_MAX = 1024;
5868
+
5869
+ // server/store.ts
5870
+ var BASE_TABLES = `
5871
+ CREATE TABLE IF NOT EXISTS repos (
5872
+ tenant TEXT NOT NULL,
5873
+ id TEXT NOT NULL,
5874
+ team TEXT NOT NULL,
5875
+ name TEXT NOT NULL,
5876
+ url TEXT NOT NULL,
5877
+ head TEXT,
5878
+ synced_at TEXT,
5879
+ error TEXT,
5880
+ PRIMARY KEY (tenant, id)
5881
+ );
5882
+ CREATE TABLE IF NOT EXISTS requests (
5883
+ tenant TEXT NOT NULL,
5884
+ repo_id TEXT NOT NULL,
5885
+ number INTEGER NOT NULL,
5886
+ provider TEXT NOT NULL,
5887
+ url TEXT NOT NULL,
5888
+ branch TEXT NOT NULL,
5889
+ head_sha TEXT NOT NULL,
5890
+ title TEXT NOT NULL,
5891
+ status TEXT NOT NULL,
5892
+ created_at TEXT NOT NULL,
5893
+ created_by TEXT NOT NULL,
5894
+ PRIMARY KEY (tenant, repo_id, number)
5895
+ );
5896
+ CREATE TABLE IF NOT EXISTS request_numbers (
5897
+ tenant TEXT NOT NULL,
5898
+ repo_id TEXT NOT NULL,
5899
+ last INTEGER NOT NULL,
5900
+ PRIMARY KEY (tenant, repo_id)
5901
+ );
5902
+ CREATE TABLE IF NOT EXISTS settings (
5903
+ tenant TEXT NOT NULL,
5904
+ key TEXT NOT NULL,
5905
+ value TEXT NOT NULL,
5906
+ PRIMARY KEY (tenant, key)
5907
+ );
5908
+ CREATE TABLE IF NOT EXISTS ingest_ids (
5909
+ id TEXT PRIMARY KEY,
5910
+ tenant TEXT NOT NULL,
5911
+ repo_id TEXT NOT NULL,
5912
+ UNIQUE (tenant, repo_id)
5913
+ );
5914
+ CREATE TABLE IF NOT EXISTS usage_counts (
5915
+ tenant TEXT NOT NULL,
5916
+ repo_id TEXT NOT NULL,
5917
+ skill TEXT NOT NULL,
5918
+ hour TEXT NOT NULL,
5919
+ count INTEGER NOT NULL,
5920
+ PRIMARY KEY (tenant, repo_id, skill, hour)
5921
+ );
5922
+ CREATE TABLE IF NOT EXISTS users (
5923
+ tenant TEXT NOT NULL,
5924
+ id TEXT NOT NULL,
5925
+ email TEXT NOT NULL,
5926
+ name TEXT NOT NULL,
5927
+ role TEXT NOT NULL,
5928
+ password_hash TEXT,
5929
+ oidc_issuer TEXT,
5930
+ oidc_subject TEXT,
5931
+ forge_login TEXT,
5932
+ created_at TEXT NOT NULL,
5933
+ PRIMARY KEY (tenant, id)
5934
+ );
5935
+ CREATE UNIQUE INDEX IF NOT EXISTS users_email ON users (tenant, email);
5936
+ CREATE UNIQUE INDEX IF NOT EXISTS users_oidc ON users (tenant, oidc_issuer, oidc_subject);
5937
+ CREATE TABLE IF NOT EXISTS team_owners (
5938
+ tenant TEXT NOT NULL,
5939
+ user_id TEXT NOT NULL,
5940
+ team TEXT NOT NULL,
5941
+ PRIMARY KEY (tenant, user_id, team)
5942
+ );
5943
+ CREATE TABLE IF NOT EXISTS sessions (
5944
+ token_hash TEXT PRIMARY KEY,
5945
+ tenant TEXT NOT NULL,
5946
+ user_id TEXT NOT NULL,
5947
+ csrf TEXT NOT NULL,
5948
+ expires_at TEXT NOT NULL
5949
+ );
5950
+ CREATE TABLE IF NOT EXISTS oidc_logins (
5951
+ state TEXT PRIMARY KEY,
5952
+ tenant TEXT NOT NULL,
5953
+ nonce TEXT NOT NULL,
5954
+ verifier TEXT NOT NULL,
5955
+ expires_at TEXT NOT NULL
5956
+ );
5957
+ CREATE TABLE IF NOT EXISTS secrets (
5958
+ tenant TEXT NOT NULL,
5959
+ name TEXT NOT NULL,
5960
+ sealed TEXT NOT NULL,
5961
+ updated_at TEXT NOT NULL,
5962
+ updated_by TEXT NOT NULL,
5963
+ PRIMARY KEY (tenant, name)
5964
+ );
5965
+ CREATE TABLE IF NOT EXISTS forges (
5966
+ tenant TEXT NOT NULL,
5967
+ repo_id TEXT NOT NULL,
5968
+ kind TEXT NOT NULL,
5969
+ api_url TEXT NOT NULL,
5970
+ project TEXT NOT NULL,
5971
+ PRIMARY KEY (tenant, repo_id)
5972
+ );
5973
+ CREATE TABLE IF NOT EXISTS tasks (
5974
+ tenant TEXT NOT NULL,
5975
+ id TEXT NOT NULL,
5976
+ repo_id TEXT NOT NULL,
5977
+ team TEXT NOT NULL,
5978
+ title TEXT NOT NULL,
5979
+ description TEXT NOT NULL,
5980
+ issue_url TEXT,
5981
+ issue_key TEXT,
5982
+ agent TEXT NOT NULL,
5983
+ status TEXT NOT NULL,
5984
+ created_by TEXT NOT NULL,
5985
+ created_at TEXT NOT NULL,
5986
+ started_at TEXT,
5987
+ finished_at TEXT,
5988
+ base_sha TEXT,
5989
+ tests TEXT,
5990
+ cost_usd DOUBLE PRECISION,
5991
+ input_tokens INTEGER,
5992
+ output_tokens INTEGER,
5993
+ request_number INTEGER,
5994
+ error TEXT,
5995
+ log_seq INTEGER NOT NULL DEFAULT 0,
5996
+ pgid INTEGER,
5997
+ branch TEXT,
5998
+ template TEXT,
5999
+ PRIMARY KEY (tenant, id)
6000
+ );
6001
+ CREATE TABLE IF NOT EXISTS task_log (
6002
+ tenant TEXT NOT NULL,
6003
+ task_id TEXT NOT NULL,
6004
+ seq INTEGER NOT NULL,
6005
+ at TEXT NOT NULL,
6006
+ text TEXT NOT NULL,
6007
+ PRIMARY KEY (tenant, task_id, seq)
6008
+ );
6009
+ `;
6010
+ var EVENTS_TABLE = `
6011
+ CREATE TABLE IF NOT EXISTS events (
6012
+ tenant TEXT NOT NULL,
6013
+ id TEXT NOT NULL,
6014
+ at TEXT NOT NULL,
6015
+ kind TEXT NOT NULL,
6016
+ actor_kind TEXT NOT NULL,
6017
+ actor_id TEXT,
6018
+ actor_email TEXT,
6019
+ actor_name TEXT,
6020
+ repo_id TEXT,
6021
+ subject TEXT,
6022
+ detail TEXT NOT NULL,
6023
+ PRIMARY KEY (tenant, id)
6024
+ );
6025
+ CREATE INDEX IF NOT EXISTS events_at ON events (tenant, at, id);
6026
+ `;
6027
+ var IDENTITY_TABLES = `
6028
+ CREATE TABLE IF NOT EXISTS invites (
6029
+ tenant TEXT NOT NULL,
6030
+ id TEXT NOT NULL,
6031
+ email TEXT NOT NULL,
6032
+ role TEXT NOT NULL,
6033
+ teams TEXT NOT NULL,
6034
+ token_hash TEXT NOT NULL,
6035
+ invited_by TEXT NOT NULL,
6036
+ created_at TEXT NOT NULL,
6037
+ expires_at TEXT NOT NULL,
6038
+ PRIMARY KEY (tenant, id)
6039
+ );
6040
+ CREATE UNIQUE INDEX IF NOT EXISTS invites_email ON invites (tenant, email);
6041
+ CREATE UNIQUE INDEX IF NOT EXISTS invites_token ON invites (token_hash);
6042
+ CREATE TABLE IF NOT EXISTS service_accounts (
6043
+ tenant TEXT NOT NULL,
6044
+ id TEXT NOT NULL,
6045
+ name TEXT NOT NULL,
6046
+ created_by TEXT NOT NULL,
6047
+ created_at TEXT NOT NULL,
6048
+ PRIMARY KEY (tenant, id)
6049
+ );
6050
+ CREATE TABLE IF NOT EXISTS api_keys (
6051
+ tenant TEXT NOT NULL,
6052
+ id TEXT NOT NULL,
6053
+ prefix TEXT NOT NULL,
6054
+ secret_hash TEXT NOT NULL,
6055
+ name TEXT NOT NULL,
6056
+ owner_kind TEXT NOT NULL,
6057
+ owner_id TEXT NOT NULL,
6058
+ scopes TEXT NOT NULL,
6059
+ created_by TEXT NOT NULL,
6060
+ created_at TEXT NOT NULL,
6061
+ expires_at TEXT,
6062
+ last_used_at TEXT,
6063
+ revoked_at TEXT,
6064
+ PRIMARY KEY (tenant, id)
6065
+ );
6066
+ CREATE UNIQUE INDEX IF NOT EXISTS api_keys_prefix ON api_keys (prefix);
6067
+ CREATE INDEX IF NOT EXISTS api_keys_owner ON api_keys (tenant, owner_kind, owner_id);
6068
+ CREATE TABLE IF NOT EXISTS member_groups (
6069
+ tenant TEXT NOT NULL,
6070
+ user_id TEXT NOT NULL,
6071
+ grp TEXT NOT NULL,
6072
+ PRIMARY KEY (tenant, user_id, grp)
6073
+ );
6074
+ CREATE TABLE IF NOT EXISTS group_tags (
6075
+ tenant TEXT NOT NULL,
6076
+ grp TEXT NOT NULL,
6077
+ tag TEXT NOT NULL,
6078
+ PRIMARY KEY (tenant, grp)
6079
+ );
6080
+ CREATE TABLE IF NOT EXISTS member_tags (
6081
+ tenant TEXT NOT NULL,
6082
+ user_id TEXT NOT NULL,
6083
+ tag TEXT NOT NULL,
6084
+ PRIMARY KEY (tenant, user_id, tag)
6085
+ );
6086
+ `;
6087
+ var DOMAINS_TABLE = `
6088
+ CREATE TABLE IF NOT EXISTS sso_domains (
6089
+ tenant TEXT NOT NULL,
6090
+ domain TEXT NOT NULL,
6091
+ token TEXT NOT NULL,
6092
+ added_by TEXT NOT NULL,
6093
+ added_at TEXT NOT NULL,
6094
+ verified_at TEXT,
6095
+ PRIMARY KEY (tenant, domain)
6096
+ );
6097
+ `;
6098
+ var CLOUD_IDENTITY_TABLES = `
6099
+ CREATE TABLE IF NOT EXISTS identities (
6100
+ id TEXT PRIMARY KEY,
6101
+ email TEXT NOT NULL,
6102
+ name TEXT NOT NULL,
6103
+ email_verified_at TEXT NOT NULL,
6104
+ terms_url TEXT,
6105
+ terms_accepted_at TEXT,
6106
+ created_at TEXT NOT NULL
6107
+ );
6108
+ CREATE UNIQUE INDEX IF NOT EXISTS identities_email ON identities (email);
6109
+ CREATE TABLE IF NOT EXISTS identity_logins (
6110
+ provider TEXT NOT NULL,
6111
+ subject TEXT NOT NULL,
6112
+ identity_id TEXT NOT NULL,
6113
+ email TEXT NOT NULL,
6114
+ added_at TEXT NOT NULL,
6115
+ PRIMARY KEY (provider, subject)
6116
+ );
6117
+ CREATE INDEX IF NOT EXISTS identity_logins_identity ON identity_logins (identity_id);
6118
+ CREATE TABLE IF NOT EXISTS identity_sessions (
6119
+ token_hash TEXT PRIMARY KEY,
6120
+ identity_id TEXT NOT NULL,
6121
+ csrf TEXT NOT NULL,
6122
+ method TEXT NOT NULL,
6123
+ domain TEXT,
6124
+ authenticated_at TEXT NOT NULL,
6125
+ expires_at TEXT NOT NULL
6126
+ );
6127
+ CREATE TABLE IF NOT EXISTS identity_sign_ins (
6128
+ state TEXT PRIMARY KEY,
6129
+ provider TEXT NOT NULL,
6130
+ purpose TEXT NOT NULL,
6131
+ nonce TEXT NOT NULL,
6132
+ verifier TEXT NOT NULL,
6133
+ identity_id TEXT,
6134
+ invite_id TEXT,
6135
+ expires_at TEXT NOT NULL
6136
+ );
6137
+ CREATE TABLE IF NOT EXISTS orgs (
6138
+ tenant TEXT PRIMARY KEY,
6139
+ name TEXT NOT NULL,
6140
+ created_by TEXT NOT NULL,
6141
+ created_at TEXT NOT NULL,
6142
+ quotas TEXT NOT NULL,
6143
+ deleted_at TEXT
6144
+ );
6145
+ CREATE INDEX IF NOT EXISTS orgs_created_by ON orgs (created_by, created_at);
6146
+ `;
6147
+ var POLICIES_TABLE = `
6148
+ CREATE TABLE IF NOT EXISTS policies (
6149
+ tenant TEXT NOT NULL,
6150
+ id TEXT NOT NULL,
6151
+ name TEXT NOT NULL,
6152
+ audience TEXT NOT NULL,
6153
+ rules TEXT NOT NULL,
6154
+ updated_at TEXT NOT NULL,
6155
+ updated_by TEXT NOT NULL,
6156
+ PRIMARY KEY (tenant, id)
6157
+ );
6158
+ `;
6159
+ var EVENT_FLOOR_DAYS = 30;
6160
+ var SQLITE_EVENT_GUARDS = `
6161
+ CREATE TRIGGER IF NOT EXISTS events_append_only BEFORE UPDATE ON events
6162
+ BEGIN SELECT RAISE(ABORT, 'the event log is append-only'); END;
6163
+ CREATE TRIGGER IF NOT EXISTS events_kept BEFORE DELETE ON events
6164
+ WHEN OLD.at > strftime('%Y-%m-%dT%H:%M:%fZ', 'now', '-${EVENT_FLOOR_DAYS} days')
6165
+ BEGIN SELECT RAISE(ABORT, 'an event younger than ${EVENT_FLOOR_DAYS} days is kept'); END;
6166
+ `;
6167
+ var POSTGRES_EVENT_GUARDS = `
6168
+ CREATE OR REPLACE FUNCTION console_events_guard() RETURNS trigger LANGUAGE plpgsql AS $guard$
6169
+ BEGIN
6170
+ IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'the event log is append-only'; END IF;
6171
+ IF OLD.at > to_char((now() AT TIME ZONE 'UTC') - interval '${EVENT_FLOOR_DAYS} days', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') THEN
6172
+ RAISE EXCEPTION 'an event younger than ${EVENT_FLOOR_DAYS} days is kept';
6173
+ END IF;
6174
+ RETURN OLD;
6175
+ END
6176
+ $guard$;
6177
+ CREATE OR REPLACE TRIGGER events_guard BEFORE UPDATE OR DELETE ON events FOR EACH ROW EXECUTE FUNCTION console_events_guard();
6178
+ `;
6179
+ var REQUEST_CHECK_COLUMNS = ["checked_head", "held_head", "held_reason"];
6180
+ var TASK_SHARES_TABLE = `CREATE TABLE IF NOT EXISTS task_shares (
6181
+ tenant TEXT NOT NULL,
6182
+ task_id TEXT NOT NULL,
6183
+ user_id TEXT NOT NULL,
6184
+ shared_by TEXT NOT NULL,
6185
+ at TEXT NOT NULL,
6186
+ PRIMARY KEY (tenant, task_id, user_id)
6187
+ )`;
6188
+ var TASK_COLUMNS = [
6189
+ { column: "log_seq", type: "INTEGER NOT NULL DEFAULT 0" },
6190
+ { column: "issue_url", type: "TEXT" },
6191
+ { column: "issue_key", type: "TEXT" },
6192
+ { column: "pgid", type: "INTEGER" },
6193
+ { column: "branch", type: "TEXT" },
6194
+ { column: "template", type: "TEXT" }
6195
+ ];
6196
+ var ROLE_REWRITE = ["UPDATE users SET role = 'member' WHERE role = 'owner'", "UPDATE users SET role = 'owner' WHERE role = 'admin'"];
6197
+ var TASK_INDEXES = `
6198
+ CREATE INDEX IF NOT EXISTS tasks_newest ON tasks (tenant, created_at, id);
6199
+ CREATE INDEX IF NOT EXISTS tasks_creator ON tasks (tenant, created_by, created_at);
6200
+ CREATE INDEX IF NOT EXISTS tasks_request ON tasks (tenant, repo_id, request_number);
6201
+ `;
6202
+ var EFFECT_TABLES = `
6203
+ CREATE TABLE IF NOT EXISTS task_effects (
6204
+ tenant TEXT NOT NULL,
6205
+ id TEXT NOT NULL,
6206
+ task_id TEXT NOT NULL,
6207
+ seq INTEGER NOT NULL,
6208
+ kind TEXT NOT NULL,
6209
+ payload TEXT NOT NULL,
6210
+ replay TEXT NOT NULL,
6211
+ status TEXT NOT NULL,
6212
+ attempts INTEGER NOT NULL,
6213
+ claimed_by TEXT,
6214
+ lease_until TEXT,
6215
+ due_at TEXT NOT NULL,
6216
+ last_error TEXT,
6217
+ result TEXT,
6218
+ created_at TEXT NOT NULL,
6219
+ settled_at TEXT,
6220
+ PRIMARY KEY (tenant, id)
6221
+ );
6222
+ CREATE UNIQUE INDEX IF NOT EXISTS task_effects_order ON task_effects (tenant, task_id, seq);
6223
+ CREATE INDEX IF NOT EXISTS task_effects_due ON task_effects (status, due_at);
6224
+ CREATE TABLE IF NOT EXISTS command_receipts (
6225
+ tenant TEXT NOT NULL,
6226
+ actor_id TEXT NOT NULL,
6227
+ command_id TEXT NOT NULL,
6228
+ kind TEXT NOT NULL,
6229
+ task_id TEXT NOT NULL,
6230
+ result TEXT NOT NULL,
6231
+ created_at TEXT NOT NULL,
6232
+ PRIMARY KEY (tenant, actor_id, command_id)
6233
+ );
6234
+ `;
6235
+ var SESSION_LISTING_SQLITE = ["sessions", "identity_sessions"].map((table) => `UPDATE ${table} SET id = 'ses_' || lower(hex(randomblob(13))) WHERE id IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS ${table}_id ON ${table} (id);`).join("\n");
6236
+ var SESSION_LISTING_POSTGRES = ["sessions", "identity_sessions"].map((table) => `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS id TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS created_at TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS last_seen_at TEXT; ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS user_agent TEXT;
6237
+ UPDATE ${table} SET id = 'ses_' || substr(md5(random()::text || token_hash), 1, 26) WHERE id IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS ${table}_id ON ${table} (id);`).join("\n");
6238
+ var IDENTITY_EVENTS_TABLE = `
6239
+ CREATE TABLE IF NOT EXISTS identity_events (
6240
+ id TEXT PRIMARY KEY,
6241
+ identity_id TEXT NOT NULL,
6242
+ at TEXT NOT NULL,
6243
+ kind TEXT NOT NULL,
6244
+ provider TEXT NOT NULL,
6245
+ email_domain TEXT NOT NULL,
6246
+ org TEXT
6247
+ );
6248
+ CREATE INDEX IF NOT EXISTS identity_events_at ON identity_events (at, id);
6249
+ `;
6250
+ var ATTACHMENTS_TABLE = `
6251
+ CREATE TABLE IF NOT EXISTS task_attachments (
6252
+ tenant TEXT NOT NULL,
6253
+ id TEXT NOT NULL,
6254
+ task_id TEXT NOT NULL,
6255
+ name TEXT NOT NULL,
6256
+ mime TEXT NOT NULL,
6257
+ size INTEGER NOT NULL,
6258
+ sha256 TEXT NOT NULL,
6259
+ created_by TEXT NOT NULL,
6260
+ created_at TEXT NOT NULL,
6261
+ PRIMARY KEY (tenant, id)
6262
+ );
6263
+ CREATE INDEX IF NOT EXISTS task_attachments_task ON task_attachments (tenant, task_id);
6264
+ `;
6265
+ var RUNNER_TABLES = `
6266
+ CREATE TABLE IF NOT EXISTS machines (
6267
+ tenant TEXT NOT NULL,
6268
+ id TEXT NOT NULL,
6269
+ user_id TEXT NOT NULL,
6270
+ name TEXT NOT NULL,
6271
+ platform TEXT NOT NULL,
6272
+ public_key TEXT NOT NULL,
6273
+ token_hash TEXT NOT NULL,
6274
+ agents TEXT NOT NULL,
6275
+ created_at TEXT NOT NULL,
6276
+ last_seen_at TEXT,
6277
+ revoked_at TEXT,
6278
+ PRIMARY KEY (tenant, id)
6279
+ );
6280
+ CREATE UNIQUE INDEX IF NOT EXISTS machines_token ON machines (token_hash);
6281
+ CREATE INDEX IF NOT EXISTS machines_user ON machines (tenant, user_id);
6282
+ CREATE TABLE IF NOT EXISTS machine_pairings (
6283
+ tenant TEXT NOT NULL,
6284
+ code_hash TEXT NOT NULL,
6285
+ user_id TEXT NOT NULL,
6286
+ expires_at TEXT NOT NULL,
6287
+ used_at TEXT,
6288
+ PRIMARY KEY (tenant, code_hash)
6289
+ );
6290
+ CREATE TABLE IF NOT EXISTS runner_nonces (
6291
+ tenant TEXT NOT NULL,
6292
+ machine_id TEXT NOT NULL,
6293
+ nonce TEXT NOT NULL,
6294
+ expires_at TEXT NOT NULL,
6295
+ PRIMARY KEY (tenant, machine_id, nonce)
6296
+ );
6297
+ CREATE INDEX IF NOT EXISTS runner_nonces_expiry ON runner_nonces (expires_at);
6298
+ `;
6299
+ var RUNNER_INDEXES = `
6300
+ CREATE INDEX IF NOT EXISTS tasks_claim ON tasks (tenant, status, runner, created_by, created_at);
6301
+ CREATE INDEX IF NOT EXISTS tasks_lease ON tasks (status, lease_until);
6302
+ CREATE UNIQUE INDEX IF NOT EXISTS task_log_source ON task_log (tenant, task_id, source_n);
6303
+ `;
6304
+ var RUNNER_TASK_COLUMNS = [
6305
+ ["tasks", "runner", "TEXT NOT NULL DEFAULT 'server'"],
6306
+ ["tasks", "claimed_by", "TEXT"],
6307
+ ["tasks", "lease_id", "TEXT"],
6308
+ ["tasks", "lease_until", "TEXT"],
6309
+ ["tasks", "native_session", "TEXT"],
6310
+ ["task_log", "kind", "TEXT NOT NULL DEFAULT 'log'"],
6311
+ ["task_log", "data", "TEXT"],
6312
+ ["task_log", "source_n", "INTEGER"]
6313
+ ];
6314
+ var FOLLOW_UPS_TABLE = `
6315
+ CREATE TABLE IF NOT EXISTS task_followups (
6316
+ tenant TEXT NOT NULL,
6317
+ id TEXT NOT NULL,
6318
+ task_id TEXT NOT NULL,
6319
+ source TEXT NOT NULL,
6320
+ key TEXT NOT NULL,
6321
+ text TEXT NOT NULL,
6322
+ quotes TEXT,
6323
+ status TEXT NOT NULL,
6324
+ created_at TEXT NOT NULL,
6325
+ delivered_at TEXT,
6326
+ created_by TEXT NOT NULL,
6327
+ PRIMARY KEY (tenant, id)
6328
+ );
6329
+ CREATE UNIQUE INDEX IF NOT EXISTS task_followups_key ON task_followups (tenant, task_id, key);
6330
+ `;
6331
+ var PROJECT_LOCKS_TABLE = `
6332
+ CREATE TABLE IF NOT EXISTS project_locks (
6333
+ tenant TEXT NOT NULL,
6334
+ project_id TEXT NOT NULL,
6335
+ task_id TEXT NOT NULL,
6336
+ taken_at TEXT NOT NULL,
6337
+ PRIMARY KEY (tenant, project_id)
6338
+ );
6339
+ `;
6340
+ var SETTINGS_BY_KEY = "CREATE INDEX IF NOT EXISTS settings_key ON settings (key);";
6341
+ var TASK_PARENT_INDEX = "CREATE INDEX IF NOT EXISTS tasks_parent ON tasks (tenant, parent_id);";
6342
+ var TASK_REQUESTS_TABLE = `
6343
+ CREATE TABLE IF NOT EXISTS task_requests (
6344
+ tenant TEXT NOT NULL,
6345
+ id TEXT NOT NULL,
6346
+ task_id TEXT NOT NULL,
6347
+ target_position INTEGER,
6348
+ source_key TEXT NOT NULL,
6349
+ kind TEXT NOT NULL,
6350
+ payload TEXT NOT NULL,
6351
+ status TEXT NOT NULL,
6352
+ response_capability TEXT NOT NULL,
6353
+ answer TEXT,
6354
+ answered_by TEXT,
6355
+ answered_via TEXT,
6356
+ created_at TEXT NOT NULL,
6357
+ answered_at TEXT,
6358
+ expires_at TEXT NOT NULL,
6359
+ PRIMARY KEY (tenant, id)
6360
+ );
6361
+ CREATE UNIQUE INDEX IF NOT EXISTS task_requests_source ON task_requests (tenant, task_id, source_key);
6362
+ CREATE INDEX IF NOT EXISTS task_requests_pending ON task_requests (status, expires_at);
6363
+ `;
6364
+ var EVENTS_BY_KIND = "CREATE INDEX IF NOT EXISTS events_first ON events (tenant, kind, at, id);";
6365
+ var EXTRA_SPEND_TABLE = `
6366
+ CREATE TABLE IF NOT EXISTS task_extra_spend (
6367
+ tenant TEXT NOT NULL,
6368
+ id TEXT NOT NULL,
6369
+ created_by TEXT NOT NULL,
6370
+ repo_id TEXT NOT NULL,
6371
+ team TEXT NOT NULL,
6372
+ at TEXT NOT NULL,
6373
+ kind TEXT NOT NULL,
6374
+ usd DOUBLE PRECISION,
6375
+ input_tokens INTEGER,
6376
+ output_tokens INTEGER,
6377
+ PRIMARY KEY (tenant, id)
6378
+ );
6379
+ CREATE INDEX IF NOT EXISTS task_extra_spend_at ON task_extra_spend (tenant, at);
6380
+ CREATE INDEX IF NOT EXISTS invites_address ON invites (email);
6381
+ `;
6382
+ var TASK_TARGETS_TABLE = `
6383
+ CREATE TABLE IF NOT EXISTS task_targets (
6384
+ tenant TEXT NOT NULL,
6385
+ task_id TEXT NOT NULL,
6386
+ position INTEGER NOT NULL,
6387
+ repo_id TEXT NOT NULL,
6388
+ status TEXT NOT NULL,
6389
+ reason TEXT NOT NULL,
6390
+ base_sha TEXT,
6391
+ branch TEXT,
6392
+ tests TEXT,
6393
+ request_number INTEGER,
6394
+ error TEXT,
6395
+ cost_usd DOUBLE PRECISION,
6396
+ input_tokens INTEGER,
6397
+ output_tokens INTEGER,
6398
+ PRIMARY KEY (tenant, task_id, position)
6399
+ );
6400
+ CREATE INDEX IF NOT EXISTS task_targets_request ON task_targets (tenant, repo_id, request_number);
6401
+ `;
6402
+ var MIGRATIONS = [
6403
+ { version: 1, kind: "contract", name: "the first tables", sqlite: (db) => db.exec(BASE_TABLES), postgres: (db) => db.exec(BASE_TABLES) },
6404
+ {
6405
+ version: 2,
6406
+ kind: "expand",
6407
+ name: "task columns added after the first shape",
6408
+ sqlite(db) {
6409
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6410
+ for (const { column, type } of TASK_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} ${type}`);
6411
+ },
6412
+ async postgres(db) {
6413
+ for (const { column, type } of TASK_COLUMNS) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} ${type}`);
6865
6414
  }
6866
- case "skill.delete": {
6867
- const slug = String(input.slug ?? "");
6868
- if (!SKILL_SLUG.test(slug)) throw new ChangeRefused("a skill name is lower-case letters, digits and dashes");
6869
- const files = await filesUnder(mirror, head, `skills/${slug}`);
6870
- if (!files.length) throw new ChangeRefused(`there is no skill ${slug} to remove`);
6871
- return {
6872
- files: files.map((path) => ({ path, content: null })),
6873
- proposal: `chore(skill): remove ${slug}`,
6874
- body: [`Removes the skill \`${slug}\` and every file it ships (${files.length}).`],
6875
- topic: `remove-${slug}`
6876
- };
6415
+ },
6416
+ {
6417
+ version: 3,
6418
+ kind: "expand",
6419
+ name: "the append-only event log",
6420
+ sqlite: (db) => db.exec(EVENTS_TABLE + SQLITE_EVENT_GUARDS),
6421
+ postgres: async (db) => {
6422
+ await db.exec(EVENTS_TABLE);
6423
+ await db.exec(POSTGRES_EVENT_GUARDS);
6877
6424
  }
6878
- case "mcp.add":
6879
- case "mcp.edit": {
6880
- const name = String(input.name ?? "");
6881
- const checked3 = serverProblem(name, input.config);
6882
- if ("refused" in checked3) throw new ChangeRefused(checked3.refused);
6883
- const { audit } = checked3;
6884
- const config = input.config;
6885
- const existing = await show(mirror, head, MCP_FILE);
6886
- const editing = input.kind === "mcp.edit";
6887
- let merged;
6888
- try {
6889
- merged = mergeServersIntoMcpJson(existing, [{ name, scope: "project", config }], (n) => editing && n === name);
6890
- } catch (err) {
6891
- throw new ChangeRefused(err.message);
6425
+ },
6426
+ {
6427
+ // Also parts the role from owning a team: until then "owner" meant a team's owner and "admin"
6428
+ // ran the organization. A team owner becomes a member who keeps their teams, and an admin
6429
+ // becomes an owner, so nobody loses a right they had and every organization that had an
6430
+ // admin keeps someone who can change every role.
6431
+ version: 4,
6432
+ kind: "contract",
6433
+ name: "invitations, service accounts, keys, directory groups, and the owner role",
6434
+ sqlite: (db) => db.exec(IDENTITY_TABLES + ROLE_REWRITE.map((sql) => `${sql};`).join("\n")),
6435
+ postgres: async (db) => {
6436
+ await db.exec(IDENTITY_TABLES);
6437
+ for (const sql of ROLE_REWRITE) await db.run(sql);
6438
+ }
6439
+ },
6440
+ { version: 5, kind: "expand", name: "policies the orchestrator applies itself", sqlite: (db) => db.exec(POLICIES_TABLE), postgres: (db) => db.exec(POLICIES_TABLE) },
6441
+ {
6442
+ // Revoking a key revokes every key it minted, which needs each key to name the one that made it.
6443
+ version: 6,
6444
+ kind: "expand",
6445
+ name: "keys remember the key that minted them",
6446
+ sqlite(db) {
6447
+ const have = new Set(db.prepare("PRAGMA table_info(api_keys)").all().map((c) => c.name));
6448
+ if (!have.has("minted_by")) db.exec("ALTER TABLE api_keys ADD COLUMN minted_by TEXT");
6449
+ },
6450
+ postgres: (db) => db.exec("ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS minted_by TEXT")
6451
+ },
6452
+ {
6453
+ // How long a request waited to merge is the analytics' measure, and the status alone does not say when.
6454
+ version: 7,
6455
+ kind: "expand",
6456
+ name: "requests remember when they were merged",
6457
+ sqlite(db) {
6458
+ const have = new Set(db.prepare("PRAGMA table_info(requests)").all().map((c) => c.name));
6459
+ if (!have.has("merged_at")) db.exec("ALTER TABLE requests ADD COLUMN merged_at TEXT");
6460
+ },
6461
+ postgres: (db) => db.exec("ALTER TABLE requests ADD COLUMN IF NOT EXISTS merged_at TEXT")
6462
+ },
6463
+ { version: 8, kind: "expand", name: "email domains verified for single sign-on", sqlite: (db) => db.exec(DOMAINS_TABLE), postgres: (db) => db.exec(DOMAINS_TABLE) },
6464
+ // The task list is read a page at a time, newest first, and a budget sums one window of it;
6465
+ // without these each read walks every task the organization ever ran.
6466
+ { version: 9, kind: "expand", name: "tasks read newest first and by who started them", sqlite: (db) => db.exec(TASK_INDEXES), postgres: (db) => db.exec(TASK_INDEXES) },
6467
+ {
6468
+ // A task over several repositories keeps each one's run beside the task, and says how they were chosen.
6469
+ version: 10,
6470
+ kind: "expand",
6471
+ name: "tasks over several repositories",
6472
+ sqlite(db) {
6473
+ db.exec(TASK_TARGETS_TABLE);
6474
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6475
+ if (!have.has("target_mode")) db.exec("ALTER TABLE tasks ADD COLUMN target_mode TEXT");
6476
+ },
6477
+ postgres: async (db) => {
6478
+ await db.exec(TASK_TARGETS_TABLE);
6479
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS target_mode TEXT");
6480
+ }
6481
+ },
6482
+ {
6483
+ // The sprint board shows where a running task is, and Run again starts it with the same skills.
6484
+ version: 11,
6485
+ kind: "expand",
6486
+ name: "tasks remember their stage and skills",
6487
+ sqlite(db) {
6488
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6489
+ if (!have.has("stage")) db.exec("ALTER TABLE tasks ADD COLUMN stage TEXT");
6490
+ if (!have.has("skills")) db.exec("ALTER TABLE tasks ADD COLUMN skills TEXT");
6491
+ },
6492
+ postgres: async (db) => {
6493
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS stage TEXT");
6494
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS skills TEXT");
6495
+ }
6496
+ },
6497
+ {
6498
+ // A cloud orchestrator's people: one identity across organizations, each membership an organization's account.
6499
+ version: 12,
6500
+ kind: "expand",
6501
+ name: "identities and the organizations they create",
6502
+ sqlite(db) {
6503
+ db.exec(CLOUD_IDENTITY_TABLES);
6504
+ const have = new Set(db.prepare("PRAGMA table_info(users)").all().map((c) => c.name));
6505
+ if (!have.has("identity_id")) db.exec("ALTER TABLE users ADD COLUMN identity_id TEXT");
6506
+ if (!have.has("sessions_revoked_at")) db.exec("ALTER TABLE users ADD COLUMN sessions_revoked_at TEXT");
6507
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS users_identity ON users (tenant, identity_id)");
6508
+ },
6509
+ postgres: async (db) => {
6510
+ await db.exec(CLOUD_IDENTITY_TABLES);
6511
+ await db.exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS identity_id TEXT");
6512
+ await db.exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS sessions_revoked_at TEXT");
6513
+ await db.exec("CREATE UNIQUE INDEX IF NOT EXISTS users_identity ON users (tenant, identity_id)");
6514
+ }
6515
+ },
6516
+ {
6517
+ // A skill suggestion spends on the model outside any task, and the budgets count it beside
6518
+ // tasks; an identity's invitations are read by address across organizations.
6519
+ version: 13,
6520
+ kind: "expand",
6521
+ name: "model spend outside tasks, and invitations by address",
6522
+ sqlite: (db) => db.exec(EXTRA_SPEND_TABLE),
6523
+ postgres: (db) => db.exec(EXTRA_SPEND_TABLE)
6524
+ },
6525
+ {
6526
+ // Who has reached which step of an organization's setup is read from the first event of each kind.
6527
+ version: 14,
6528
+ kind: "expand",
6529
+ name: "events read by kind",
6530
+ sqlite: (db) => db.exec(EVENTS_BY_KIND),
6531
+ postgres: (db) => db.exec(EVENTS_BY_KIND)
6532
+ },
6533
+ {
6534
+ // A cloud organization's plan decides which features open for it; every one starts on Free.
6535
+ version: 15,
6536
+ kind: "expand",
6537
+ name: "organizations carry a plan",
6538
+ sqlite(db) {
6539
+ const have = new Set(db.prepare("PRAGMA table_info(orgs)").all().map((c) => c.name));
6540
+ if (!have.has("plan")) db.exec("ALTER TABLE orgs ADD COLUMN plan TEXT NOT NULL DEFAULT 'free'");
6541
+ },
6542
+ postgres: (db) => db.exec("ALTER TABLE orgs ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'free'")
6543
+ },
6544
+ {
6545
+ // A task's side effects are written with the command that asks for them and carried out after,
6546
+ // and a command sent twice is answered once.
6547
+ version: 16,
6548
+ kind: "expand",
6549
+ name: "task effects and command receipts",
6550
+ sqlite: (db) => db.exec(EFFECT_TABLES),
6551
+ postgres: (db) => db.exec(EFFECT_TABLES)
6552
+ },
6553
+ {
6554
+ // A task says how far its agent goes without asking, under the organization's ceiling.
6555
+ version: 17,
6556
+ kind: "expand",
6557
+ name: "tasks carry a permission mode",
6558
+ sqlite(db) {
6559
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6560
+ if (!have.has("mode")) db.exec("ALTER TABLE tasks ADD COLUMN mode TEXT");
6561
+ },
6562
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS mode TEXT")
6563
+ },
6564
+ {
6565
+ // What an agent asks while it works is kept before anyone answers it, so any browser answers it once.
6566
+ version: 18,
6567
+ kind: "expand",
6568
+ name: "questions agents ask while they work",
6569
+ sqlite: (db) => db.exec(TASK_REQUESTS_TABLE),
6570
+ postgres: (db) => db.exec(TASK_REQUESTS_TABLE)
6571
+ },
6572
+ {
6573
+ // A person lists the browsers they are signed in from and ends one by its id, not by its token.
6574
+ version: 19,
6575
+ kind: "expand",
6576
+ name: "sessions listed by id",
6577
+ sqlite(db) {
6578
+ for (const table of ["sessions", "identity_sessions"]) {
6579
+ const have = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name));
6580
+ for (const column of ["id", "created_at", "last_seen_at", "user_agent"]) if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`);
6581
+ }
6582
+ db.exec(SESSION_LISTING_SQLITE);
6583
+ },
6584
+ postgres: (db) => db.exec(SESSION_LISTING_POSTGRES)
6585
+ },
6586
+ {
6587
+ // A task an agent delegates records the task that asked for it and how deep it sits.
6588
+ version: 20,
6589
+ kind: "expand",
6590
+ name: "tasks delegated by tasks",
6591
+ sqlite(db) {
6592
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6593
+ if (!have.has("parent_id")) db.exec("ALTER TABLE tasks ADD COLUMN parent_id TEXT");
6594
+ if (!have.has("depth")) db.exec("ALTER TABLE tasks ADD COLUMN depth INTEGER NOT NULL DEFAULT 0");
6595
+ db.exec(TASK_PARENT_INDEX);
6596
+ },
6597
+ postgres: async (db) => {
6598
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS parent_id TEXT");
6599
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS depth INTEGER NOT NULL DEFAULT 0");
6600
+ await db.exec(TASK_PARENT_INDEX);
6601
+ }
6602
+ },
6603
+ {
6604
+ // Who signed up and how far their organization got, kept for the operator apart from every organization.
6605
+ version: 21,
6606
+ kind: "expand",
6607
+ name: "signup steps",
6608
+ sqlite: (db) => db.exec(IDENTITY_EVENTS_TABLE),
6609
+ postgres: (db) => db.exec(IDENTITY_EVENTS_TABLE)
6610
+ },
6611
+ {
6612
+ // An organization that lets people join by their directory is found by its setting's key.
6613
+ version: 22,
6614
+ kind: "expand",
6615
+ name: "settings read by key",
6616
+ sqlite: (db) => db.exec(SETTINGS_BY_KEY),
6617
+ postgres: (db) => db.exec(SETTINGS_BY_KEY)
6618
+ },
6619
+ {
6620
+ // A file a person attaches to a task is recorded beside it; its bytes stay in the data directory.
6621
+ version: 23,
6622
+ kind: "expand",
6623
+ name: "task attachments",
6624
+ sqlite: (db) => db.exec(ATTACHMENTS_TABLE),
6625
+ postgres: (db) => db.exec(ATTACHMENTS_TABLE)
6626
+ },
6627
+ {
6628
+ // A person's machine runs their tasks under a lease it renews; a task it held when the lease
6629
+ // ran out waits for Continue there, and its events are numbered by the machine, written once.
6630
+ version: 24,
6631
+ kind: "expand",
6632
+ name: "machines and the tasks they lease",
6633
+ sqlite(db) {
6634
+ db.exec(RUNNER_TABLES);
6635
+ for (const [table, column, type] of RUNNER_TASK_COLUMNS) {
6636
+ const have = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name));
6637
+ if (!have.has(column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
6892
6638
  }
6893
- if (merged.collided.length) throw new ChangeRefused(`${MCP_FILE} already declares ${name}; edit it instead`);
6894
- if (editing && !merged.replaced.includes(name)) throw new ChangeRefused(`${MCP_FILE} declares no server ${name} to edit`);
6895
- if (editing && JSON.stringify(declaredServers(existing)[name]) === JSON.stringify(config)) throw new ChangeRefused(`${name} is unchanged`);
6896
- return {
6897
- files: [{ path: MCP_FILE, content: merged.merged }],
6898
- proposal: `feat(mcp): ${editing ? "update" : "add"} ${name}`,
6899
- body: [`${editing ? "Changes" : "Declares"} the MCP server \`${name}\` (${audit.transport}) for everyone who installs this plugin.`, ...describeServer(name, config, audit.requiresEnv)],
6900
- topic: `mcp-${name.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`
6901
- };
6902
- }
6903
- case "command.add":
6904
- case "command.edit": {
6905
- const name = String(input.name ?? "");
6906
- if (typeof input.content !== "string" || !input.content.trim()) throw new ChangeRefused("the command's text is empty");
6907
- if (Buffer.byteLength(input.content) > MAX_SKILL_BYTES) throw new ChangeRefused("the command is larger than 256 KiB");
6908
- const content = input.content.replace(/\r\n/g, "\n");
6909
- const audit = auditCommandText(name, content);
6910
- if (!audit.shareable) throw new ChangeRefused(commandRefusal(name, audit));
6911
- const path = `commands/${commandFile(name)}`;
6912
- const existing = await show(mirror, head, path);
6913
- const editing = input.kind === "command.edit";
6914
- if (!editing && existing !== null) throw new ChangeRefused(`/${name} already exists; edit it instead`);
6915
- if (editing && existing === null) throw new ChangeRefused(`there is no command /${name} to edit`);
6916
- const text = content.endsWith("\n") ? content : `${content}
6917
- `;
6918
- if (text === existing) throw new ChangeRefused(`/${name} is unchanged`);
6919
- return {
6920
- files: [{ path, content: text }],
6921
- proposal: `feat(command): ${editing ? "update" : "add"} /${name}`,
6922
- body: [`${editing ? "Changes" : "Adds"} the slash command \`/${name}\` (${path}) for everyone who installs this plugin.`],
6923
- topic: `command-${name.replace(/:/g, "-")}`
6924
- };
6639
+ db.exec(RUNNER_INDEXES);
6640
+ },
6641
+ postgres: async (db) => {
6642
+ await db.exec(RUNNER_TABLES);
6643
+ for (const [table, column, type] of RUNNER_TASK_COLUMNS) await db.exec(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${column} ${type}`);
6644
+ await db.exec(RUNNER_INDEXES);
6925
6645
  }
6926
- case "command.delete": {
6927
- const name = String(input.name ?? "");
6928
- const named2 = auditCommandText(name, "");
6929
- if (!named2.shareable) throw new ChangeRefused(commandRefusal(name, named2));
6930
- const path = `commands/${commandFile(name)}`;
6931
- if (await show(mirror, head, path) === null) throw new ChangeRefused(`there is no command /${name} to remove`);
6932
- return {
6933
- files: [{ path, content: null }],
6934
- proposal: `chore(command): remove /${name}`,
6935
- body: [`Removes the slash command \`/${name}\` (${path}); teammates lose it once their plugin updates.`],
6936
- topic: `remove-command-${name.replace(/:/g, "-")}`
6937
- };
6646
+ },
6647
+ {
6648
+ // A task keeps the agent options it ran with, so Run again sends the same.
6649
+ version: 25,
6650
+ kind: "expand",
6651
+ name: "tasks carry their agent's options",
6652
+ sqlite(db) {
6653
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6654
+ if (!have.has("choices")) db.exec("ALTER TABLE tasks ADD COLUMN choices TEXT");
6655
+ },
6656
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS choices TEXT")
6657
+ },
6658
+ {
6659
+ // A question from an agent on a person's machine has no deadline of its own: it waits as long
6660
+ // as the machine holds the task. SQLite drops a NOT NULL only by copying the table.
6661
+ version: 26,
6662
+ kind: "expand",
6663
+ name: "questions that wait without a deadline",
6664
+ sqlite(db) {
6665
+ const column = db.prepare("PRAGMA table_info(task_requests)").all().find((c) => c.name === "expires_at");
6666
+ if (!column?.notnull) return;
6667
+ db.exec(`${TASK_REQUESTS_TABLE.replace("task_requests (", "task_requests_next (").replace("expires_at TEXT NOT NULL", "expires_at TEXT").replace(/CREATE (UNIQUE )?INDEX[^;]*;/g, "")}
6668
+ INSERT INTO task_requests_next SELECT * FROM task_requests;
6669
+ DROP TABLE task_requests;
6670
+ ALTER TABLE task_requests_next RENAME TO task_requests;
6671
+ ${TASK_REQUESTS_TABLE.replace(/CREATE TABLE[^;]*;/, "")}`);
6672
+ },
6673
+ postgres: (db) => db.exec("ALTER TABLE task_requests ALTER COLUMN expires_at DROP NOT NULL")
6674
+ },
6675
+ {
6676
+ // A link whose provider email is not the identity's waits for the person to confirm it, with
6677
+ // the provider's account kept beside its state until then.
6678
+ version: 27,
6679
+ kind: "expand",
6680
+ name: "pending links keep the account they wait to confirm",
6681
+ sqlite(db) {
6682
+ const have = new Set(db.prepare("PRAGMA table_info(identity_sign_ins)").all().map((c) => c.name));
6683
+ if (!have.has("account")) db.exec("ALTER TABLE identity_sign_ins ADD COLUMN account TEXT");
6684
+ },
6685
+ postgres: (db) => db.exec("ALTER TABLE identity_sign_ins ADD COLUMN IF NOT EXISTS account TEXT")
6686
+ },
6687
+ {
6688
+ // A Stop for a task a machine runs is kept on the task until the run ends, so it reaches the
6689
+ // runner through any instance and across a restart.
6690
+ version: 28,
6691
+ kind: "expand",
6692
+ name: "stops asked for tasks a machine runs",
6693
+ sqlite(db) {
6694
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6695
+ if (!have.has("stop_requested_at")) db.exec("ALTER TABLE tasks ADD COLUMN stop_requested_at TEXT");
6696
+ },
6697
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS stop_requested_at TEXT")
6698
+ },
6699
+ {
6700
+ // What reaches a running task after it started is kept before it is delivered, once per key,
6701
+ // so a second web node or a restarted sweep writes it once.
6702
+ version: 29,
6703
+ kind: "expand",
6704
+ name: "follow-ups waiting for a running task",
6705
+ sqlite: (db) => db.exec(FOLLOW_UPS_TABLE),
6706
+ postgres: (db) => db.exec(FOLLOW_UPS_TABLE)
6707
+ },
6708
+ {
6709
+ // A task in a folder without git works there in place, one at a time, and leaves changes
6710
+ // rather than a request, read between two snapshots of the folder's shadow.
6711
+ version: 30,
6712
+ kind: "expand",
6713
+ name: "tasks working in a folder in place",
6714
+ sqlite(db) {
6715
+ db.exec(PROJECT_LOCKS_TABLE);
6716
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6717
+ for (const column of ["result", "changes"]) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} TEXT`);
6718
+ },
6719
+ postgres: async (db) => {
6720
+ await db.exec(PROJECT_LOCKS_TABLE);
6721
+ for (const column of ["result", "changes"]) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6938
6722
  }
6939
- case "mcp.remove": {
6940
- const name = serverName(input.name);
6941
- return {
6942
- files: [{ path: MCP_FILE, content: withoutServer(await show(mirror, head, MCP_FILE), name) }],
6943
- proposal: `chore(mcp): remove ${name}`,
6944
- body: [`Removes the MCP server \`${name}\`; teammates' Claude Code stops starting it once their plugin updates. Every other entry in ${MCP_FILE} is kept.`],
6945
- topic: `remove-mcp-${name.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`
6946
- };
6723
+ },
6724
+ {
6725
+ // A task's request is checked again each time its head moves: the last head that passed, and
6726
+ // the head that failed with why, which holds the request until a later head passes.
6727
+ version: 31,
6728
+ kind: "expand",
6729
+ name: "the check of a request's head",
6730
+ sqlite(db) {
6731
+ const have = new Set(db.prepare("PRAGMA table_info(requests)").all().map((c) => c.name));
6732
+ for (const column of REQUEST_CHECK_COLUMNS) if (!have.has(column)) db.exec(`ALTER TABLE requests ADD COLUMN ${column} TEXT`);
6733
+ },
6734
+ postgres: async (db) => {
6735
+ for (const column of REQUEST_CHECK_COLUMNS) await db.exec(`ALTER TABLE requests ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6947
6736
  }
6948
- case "team.settings": {
6949
- const reviewers = cleanList(input.reviewers, "reviewers");
6950
- const labels = cleanList(input.labels, "labels");
6951
- const problem = assignmentRecordProblem({ reviewers, labels });
6952
- if (problem) throw new ChangeRefused(problem);
6953
- const { existing, json } = await teamFile(mirror, head);
6954
- const content = JSON.stringify({ ...json, reviewers, labels }, null, 2) + "\n";
6955
- if (content === existing) throw new ChangeRefused("the reviewers and labels are unchanged");
6956
- return {
6957
- files: [{ path: TEAM_PREFIX_FILE, content }],
6958
- proposal: "chore: set the reviewers and labels for requests to this repository",
6959
- body: [
6960
- `Requests to this repository will ask ${reviewers.join(", ") || "no one"} to review`,
6961
- `and carry ${labels.length ? labels.join(", ") : "no label"}. Every other setting in ${TEAM_PREFIX_FILE} is kept.`
6962
- ],
6963
- topic: "request-settings"
6964
- };
6737
+ },
6738
+ {
6739
+ // A task keeps what its starter picked of the project's own skill sources and MCP servers.
6740
+ version: 32,
6741
+ kind: "expand",
6742
+ name: "a task's pick of its project's skills and MCP servers",
6743
+ sqlite(db) {
6744
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6745
+ if (!have.has("tools")) db.exec("ALTER TABLE tasks ADD COLUMN tools TEXT");
6746
+ },
6747
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS tools TEXT")
6748
+ },
6749
+ {
6750
+ // A task shared with a member of its organization to read; nobody outside it.
6751
+ version: 33,
6752
+ kind: "expand",
6753
+ name: "tasks shared with a member to read",
6754
+ sqlite: (db) => db.exec(TASK_SHARES_TABLE),
6755
+ postgres: (db) => db.exec(TASK_SHARES_TABLE)
6756
+ },
6757
+ {
6758
+ // What the person's own Claude Code loaded into a task's run, by count; and where in the task's folder each of its
6759
+ // repositories is, so a change kept on a person's machine is named by its place there.
6760
+ version: 34,
6761
+ kind: "expand",
6762
+ name: "what a person's own setup loaded into a task's run, and each target's place in its folder",
6763
+ sqlite(db) {
6764
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6765
+ if (!have.has("loaded")) db.exec("ALTER TABLE tasks ADD COLUMN loaded TEXT");
6766
+ const targets = new Set(db.prepare("PRAGMA table_info(task_targets)").all().map((c) => c.name));
6767
+ if (!targets.has("path")) db.exec("ALTER TABLE task_targets ADD COLUMN path TEXT");
6768
+ },
6769
+ async postgres(db) {
6770
+ await db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS loaded TEXT");
6771
+ await db.exec("ALTER TABLE task_targets ADD COLUMN IF NOT EXISTS path TEXT");
6965
6772
  }
6966
- case "team.naming": {
6967
- if (typeof input.commitPrefix !== "string" || typeof input.branchExample !== "string") throw new ChangeRefused("the commit prefix and the example branch are text");
6968
- const commitPrefix = input.commitPrefix.trim();
6969
- const branchExample = input.branchExample.trim();
6970
- const prefixProblem = commitPrefixProblem(commitPrefix);
6971
- if (prefixProblem) throw new ChangeRefused(`that commit prefix cannot be recorded: it is ${prefixProblem}`);
6972
- const exampleProblem = branchExample ? branchExampleProblem(branchExample) : null;
6973
- if (exampleProblem) throw new ChangeRefused(`that example branch cannot be recorded: it is ${exampleProblem}`);
6974
- const { existing, json } = await teamFile(mirror, head);
6975
- const recorded = recordedCommitPrefix(json.commitPrefix).prefix ?? "";
6976
- if (commitPrefix !== recorded && await show(mirror, head, CI_BUMP_SCRIPT) !== null) {
6977
- const how = commitPrefix ? `run /handbook:init --upgrade --commit-prefix "${commitPrefix}" from a teammate's machine, which writes the team file and the job in one request` : `set commitPrefix to "" in ${TEAM_PREFIX_FILE}, then run /handbook:init --upgrade from a teammate's machine, which rewrites the job from it`;
6978
- throw new ChangeRefused(`this repository's CI job writes its version commits with the team's prefix built in, so the prefix changes together with that job: ${how}`);
6979
- }
6980
- const next = { ...json, commitPrefix, branchExample };
6981
- if (!branchExample) delete next.branchExample;
6982
- const content = JSON.stringify(next, null, 2) + "\n";
6983
- if (content === existing) throw new ChangeRefused("the commit prefix and the example branch are unchanged");
6984
- return {
6985
- files: [{ path: TEAM_PREFIX_FILE, content }],
6986
- proposal: "chore: set how commits and branches to this repository are named",
6987
- body: [
6988
- commitPrefix ? `Commits to this repository will start with \`${commitPrefix}\`.` : "Commits to this repository will carry no prefix.",
6989
- branchExample ? `Branches will be named like \`${branchExample}\`.` : "Branches will follow no example.",
6990
- `Every other setting in ${TEAM_PREFIX_FILE} is kept.`
6991
- ],
6992
- topic: "naming"
6993
- };
6773
+ },
6774
+ {
6775
+ // How many tokens a task's first agent request carried: the context a cost line names.
6776
+ version: 35,
6777
+ kind: "expand",
6778
+ name: "the context a task's run started from",
6779
+ sqlite(db) {
6780
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6781
+ if (!have.has("context_tokens")) db.exec("ALTER TABLE tasks ADD COLUMN context_tokens INTEGER");
6782
+ },
6783
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS context_tokens INTEGER")
6784
+ },
6785
+ {
6786
+ // What a change kept on a person's machine needs for a later push and request: its head, its remote and that
6787
+ // remote's default branch, and the request's words.
6788
+ version: 36,
6789
+ kind: "expand",
6790
+ name: "a kept change's head, remote and request words",
6791
+ sqlite(db) {
6792
+ const have = new Set(db.prepare("PRAGMA table_info(task_targets)").all().map((c) => c.name));
6793
+ for (const column of ["head", "origin", "target_branch", "description"]) if (!have.has(column)) db.exec(`ALTER TABLE task_targets ADD COLUMN ${column} TEXT`);
6794
+ },
6795
+ async postgres(db) {
6796
+ for (const column of ["head", "origin", "target_branch", "description"]) await db.exec(`ALTER TABLE task_targets ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6994
6797
  }
6995
- default:
6996
- throw new ChangeRefused("unknown kind of change");
6798
+ },
6799
+ {
6800
+ // Why a task was asked to stop when the orchestrator asked it (a limit), and when its current run started.
6801
+ version: 37,
6802
+ kind: "expand",
6803
+ name: "a stop's reason and the run's start",
6804
+ sqlite(db) {
6805
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6806
+ for (const column of ["stop_reason", "run_started_at"]) if (!have.has(column)) db.exec(`ALTER TABLE tasks ADD COLUMN ${column} TEXT`);
6807
+ },
6808
+ async postgres(db) {
6809
+ for (const column of ["stop_reason", "run_started_at"]) await db.exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ${column} TEXT`);
6810
+ }
6811
+ },
6812
+ {
6813
+ // Where the orchestrator sent a task started with no project named, and why.
6814
+ version: 38,
6815
+ kind: "expand",
6816
+ name: "where a task was sent",
6817
+ sqlite(db) {
6818
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6819
+ if (!have.has("routing")) db.exec("ALTER TABLE tasks ADD COLUMN routing TEXT");
6820
+ },
6821
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS routing TEXT")
6822
+ },
6823
+ {
6824
+ // What a stopped run asked its starter, and the answer the next run takes.
6825
+ version: 39,
6826
+ kind: "expand",
6827
+ name: "a task's question to its starter",
6828
+ sqlite(db) {
6829
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6830
+ if (!have.has("question")) db.exec("ALTER TABLE tasks ADD COLUMN question TEXT");
6831
+ },
6832
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS question TEXT")
6833
+ },
6834
+ {
6835
+ // The person's own MCP servers a task's agent found waiting for a sign-in.
6836
+ version: 40,
6837
+ kind: "expand",
6838
+ name: "the servers a task found waiting for a sign-in",
6839
+ sqlite(db) {
6840
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6841
+ if (!have.has("mcp_needs_sign_in")) db.exec("ALTER TABLE tasks ADD COLUMN mcp_needs_sign_in TEXT");
6842
+ },
6843
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS mcp_needs_sign_in TEXT")
6844
+ },
6845
+ {
6846
+ // A task started to plan first: its agent changes nothing until its starter approves the plan.
6847
+ version: 41,
6848
+ kind: "expand",
6849
+ name: "a task that plans first",
6850
+ sqlite(db) {
6851
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6852
+ if (!have.has("plan_first")) db.exec("ALTER TABLE tasks ADD COLUMN plan_first INTEGER");
6853
+ },
6854
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS plan_first INTEGER")
6855
+ },
6856
+ {
6857
+ // A task on a person's machine cut off at their plan's usage limit: when it resets, when it was hit, how many times
6858
+ // the task went on by itself after one, and that its next run is such a going on.
6859
+ version: 42,
6860
+ kind: "expand",
6861
+ name: "a task waiting for its usage limit to reset",
6862
+ sqlite(db) {
6863
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6864
+ if (!have.has("limit_reset_at")) db.exec("ALTER TABLE tasks ADD COLUMN limit_reset_at TEXT");
6865
+ if (!have.has("limit_at")) db.exec("ALTER TABLE tasks ADD COLUMN limit_at TEXT");
6866
+ if (!have.has("auto_continues")) db.exec("ALTER TABLE tasks ADD COLUMN auto_continues INTEGER");
6867
+ if (!have.has("limit_goes_on")) db.exec("ALTER TABLE tasks ADD COLUMN limit_goes_on INTEGER");
6868
+ },
6869
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS limit_reset_at TEXT, ADD COLUMN IF NOT EXISTS limit_at TEXT, ADD COLUMN IF NOT EXISTS auto_continues INTEGER, ADD COLUMN IF NOT EXISTS limit_goes_on INTEGER")
6870
+ },
6871
+ {
6872
+ // The agent's estimate of the turn it is in on a machine, so a run cut off before the turn reported still counts it.
6873
+ version: 43,
6874
+ kind: "expand",
6875
+ name: "the estimate of a machine's turn in progress",
6876
+ sqlite(db) {
6877
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6878
+ if (!have.has("turn_estimate_usd")) db.exec("ALTER TABLE tasks ADD COLUMN turn_estimate_usd REAL");
6879
+ },
6880
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS turn_estimate_usd DOUBLE PRECISION")
6881
+ },
6882
+ {
6883
+ // How long a task's agent worked over its runs on a machine, its cards' waits left out, for the time its page says.
6884
+ version: 44,
6885
+ kind: "expand",
6886
+ name: "the time a task's agent worked",
6887
+ sqlite(db) {
6888
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6889
+ if (!have.has("ran_ms")) db.exec("ALTER TABLE tasks ADD COLUMN ran_ms INTEGER");
6890
+ },
6891
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS ran_ms BIGINT")
6892
+ },
6893
+ {
6894
+ // The skills a task's agent called, by name, for the line that says what a task used and for what a skill is measured on.
6895
+ version: 45,
6896
+ kind: "expand",
6897
+ name: "the skills a task's agent called",
6898
+ sqlite(db) {
6899
+ const have = new Set(db.prepare("PRAGMA table_info(tasks)").all().map((c) => c.name));
6900
+ if (!have.has("used_skills")) db.exec("ALTER TABLE tasks ADD COLUMN used_skills TEXT");
6901
+ },
6902
+ postgres: (db) => db.exec("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS used_skills TEXT")
6903
+ },
6904
+ {
6905
+ // What of the handed-out work a machine's runner says it understands, so a newer part goes only to one that does.
6906
+ version: 46,
6907
+ kind: "expand",
6908
+ name: "what a machine's runner understands",
6909
+ sqlite(db) {
6910
+ const have = new Set(db.prepare("PRAGMA table_info(machines)").all().map((c) => c.name));
6911
+ if (!have.has("features")) db.exec("ALTER TABLE machines ADD COLUMN features TEXT");
6912
+ },
6913
+ postgres: (db) => db.exec("ALTER TABLE machines ADD COLUMN IF NOT EXISTS features TEXT")
6914
+ },
6915
+ {
6916
+ // A request opened with its person's own sign-in on a forge the organization never connected, kept on its target.
6917
+ version: 47,
6918
+ kind: "expand",
6919
+ name: "a request opened on a forge the organization never connected",
6920
+ sqlite(db) {
6921
+ const have = new Set(db.prepare("PRAGMA table_info(task_targets)").all().map((c) => c.name));
6922
+ if (!have.has("forge_request")) db.exec("ALTER TABLE task_targets ADD COLUMN forge_request TEXT");
6923
+ },
6924
+ postgres: (db) => db.exec("ALTER TABLE task_targets ADD COLUMN IF NOT EXISTS forge_request TEXT")
6997
6925
  }
6926
+ ];
6927
+ var SCHEMA_VERSION = MIGRATIONS.length;
6928
+
6929
+ // server/events.ts
6930
+ var ORCHESTRATOR_ACTOR = { kind: "orchestrator", id: null, email: null, name: "TeamHandbook Orchestrator" };
6931
+ function actorOf(user) {
6932
+ return { kind: user.id.startsWith("service:") ? "service" : "user", id: user.id, email: user.email, name: user.name };
6998
6933
  }
6999
- async function teamFile(mirror, head) {
7000
- const existing = await show(mirror, head, TEAM_PREFIX_FILE);
7001
- if (existing === null) return { existing, json: {} };
7002
- let parsed2;
7003
- try {
7004
- parsed2 = JSON.parse(existing);
7005
- } catch {
7006
- throw new ChangeRefused(`${TEAM_PREFIX_FILE} is not valid JSON; fix it in the repository first, the orchestrator will not overwrite a file it cannot read`);
7007
- }
7008
- if (!parsed2 || typeof parsed2 !== "object" || Array.isArray(parsed2)) throw new ChangeRefused(`${TEAM_PREFIX_FILE} is not a JSON object`);
7009
- return { existing, json: parsed2 };
6934
+ var TEXT_MAX3 = 500;
6935
+ function loggedText(text) {
6936
+ const flat = maskUrl(text).replace(/\p{C}+/gu, " ").trim().slice(0, TEXT_MAX3);
6937
+ const secret = detectSecret(flat);
6938
+ return secret ? `[withheld: it looks like a ${secret}]` : flat;
7010
6939
  }
7011
- async function prepareChange(mirror, head, input, message, by, naming = {}, branch) {
7012
- return prepareBuilt(mirror, head, await buildChange(mirror, head, input), message, by, naming, branch);
6940
+ async function recordEvent(ctx, actor, kind, fields, now = /* @__PURE__ */ new Date()) {
6941
+ const by = "role" in actor ? actorOf(actor) : actor;
6942
+ await ctx.store.appendEvent({
6943
+ tenant: ctx.tenant,
6944
+ id: newId("evt", now.getTime()),
6945
+ at: now.toISOString(),
6946
+ kind,
6947
+ actor: { ...by, email: by.email && loggedText(by.email), name: by.name && loggedText(by.name) },
6948
+ repoId: fields.repoId ?? null,
6949
+ subject: fields.subject ? loggedText(fields.subject) : null,
6950
+ detail: loggedText(fields.detail)
6951
+ });
7013
6952
  }
7014
- async function prepareBuilt(mirror, head, built, message, by, naming = {}, branch) {
7015
- if (typeof message !== "string" || !message.trim()) throw new ChangeRefused(`write the commit message; the orchestrator proposes "${built.proposal}"`);
7016
- const problem = commitMessageProblem(message);
7017
- if (problem) throw new ChangeRefused(`that commit message cannot be used: ${problem}`);
7018
- const name = typeof branch === "string" ? branch : proposedBranch(built.topic, naming);
7019
- const branchRefusal = await branchProblem(name);
7020
- if (branchRefusal) throw new ChangeRefused(typeof branch === "string" ? branchRefusal : `this team names branches like ${naming.branchExample}; name the ticket in the branch, in place of ${TICKET_PLACEHOLDER} in ${name}`);
7021
- const raise = await versionRaise(mirror, head);
7022
- const body = [...built.body, "", `Proposed from the TeamHandbook Orchestrator by ${by}.`];
7023
- if (raise) body.push(versionRaiseNote(raise));
7024
- return {
7025
- title: commitSubject(commitMessagePrefix(naming.commitPrefix), message),
7026
- body: body.join("\n"),
7027
- branch: name,
7028
- files: raise ? [...built.files, raise.file] : built.files
6953
+
6954
+ // server/scim.ts
6955
+ var USERS = "/Users";
6956
+ var ONE_USER = `/api/scim/v2${USERS}/:id`;
6957
+
6958
+ // server/directory.ts
6959
+ function tagsUnder(mapping, groups, manual) {
6960
+ const byGroup = new Map(mapping.map((m) => [m.group, m.tag]));
6961
+ const tags = /* @__PURE__ */ new Map();
6962
+ const add = (userId, tag, source) => {
6963
+ const mine = tags.get(userId) ?? /* @__PURE__ */ new Map();
6964
+ if (!mine.has(tag) || source === "manual") mine.set(tag, source);
6965
+ tags.set(userId, mine);
7029
6966
  };
6967
+ for (const { userId, group } of groups) {
6968
+ const tag = byGroup.get(group);
6969
+ if (tag) add(userId, tag, "directory");
6970
+ }
6971
+ for (const { userId, tag } of manual) add(userId, tag, "manual");
6972
+ return new Map([...tags].map(([userId, mine]) => [userId, [...mine].map(([tag, source]) => ({ tag, source })).sort((a, b) => a.tag.localeCompare(b.tag))]));
6973
+ }
6974
+ async function memberTags(store, tenant) {
6975
+ return tagsUnder(await store.groupTags(tenant), await store.memberGroups(tenant), await store.manualTags(tenant));
7030
6976
  }
7031
6977
 
7032
- // shared/forge-def.ts
7033
- var HOSTED_FORGES = ["gitlab", "github", "gitea"];
7034
- var segments = (path) => path.split("/").map(encodeURIComponent).join("/");
7035
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
7036
- var FORGES = {
7037
- gitlab: {
7038
- kind: "gitlab",
7039
- label: "GitLab",
7040
- capabilities: { term: "merge request", review: "approve-only", checksAlwaysReport: true, templates: [".gitlab/merge_request_templates/Default.md", ".gitlab/merge_request_templates/*.md"] },
7041
- projectShape: "group/project",
7042
- homeHosts: ["gitlab.com"],
7043
- gitUser: "oauth2",
7044
- allowsHost: () => true,
7045
- apiUrlFor: (origin) => `${origin.origin}/api/v4`,
7046
- requestRef: (number) => `refs/merge-requests/${number}/head`,
7047
- newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/-/merge_requests/new?${new URLSearchParams({ "merge_request[source_branch]": branch, "merge_request[target_branch]": target })}`,
7048
- // GitLab has no narrower scope that opens merge requests than api.
7049
- credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/-/user_settings/personal_access_tokens?name=TeamHandbook&scopes=api`, scopes: ["api"] },
7050
- visibilities: ["private", "internal", "public"],
7051
- group: { label: "Group (optional)", placeholder: "acme/platform", meaning: "The group or subgroup the repository is made in; left empty, the connected account's own namespace holds it." },
7052
- emptyListHint: "Give the GitLab account you connected access to the team's repository, then read the list again."
7053
- },
7054
- github: {
7055
- kind: "github",
7056
- label: "GitHub",
7057
- capabilities: { term: "pull request", review: "approve-or-request-changes", checksAlwaysReport: false, templates: [".github/pull_request_template.md", "pull_request_template.md", "docs/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE/*.md"] },
7058
- projectShape: "owner/repository",
7059
- homeHosts: ["github.com"],
7060
- gitUser: "x-access-token",
7061
- allowsHost: (hostname4) => hostname4 === "github.com" || LOOPBACK_HOSTS.has(hostname4),
7062
- apiUrlFor: (origin) => LOOPBACK_HOSTS.has(origin.hostname) ? `${origin.origin}/api` : "https://api.github.com",
7063
- requestRef: (number) => `refs/pull/${number}/head`,
7064
- newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/compare/${segments(target)}...${segments(branch)}?expand=1`,
7065
- credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/settings/personal-access-tokens/new`, scopes: ["Contents: read and write", "Pull requests: read and write", "Commit statuses: read and write", "Metadata: read"] },
7066
- visibilities: ["private", "public"],
7067
- group: null,
7068
- emptyListHint: "Where the app is installed on chosen repositories only, add the team's repository to its installation on GitHub, then read the list again."
7069
- },
7070
- /*
7071
- * Gitea, and Forgejo, which keeps Gitea's API, from 1.20, where a branch is made at a commit and
7072
- * files are written to an empty repository. Read from Gitea 1.22's source: git takes the token as
7073
- * the password beside any user name; a description template is looked for at the root, then under
7074
- * .gitea/, then .github/.
7075
- */
7076
- gitea: {
7077
- kind: "gitea",
7078
- label: "Gitea",
7079
- capabilities: {
7080
- term: "pull request",
7081
- review: "approve-or-request-changes",
7082
- checksAlwaysReport: false,
7083
- templates: ["PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/pull_request_template.md"]
7084
- },
7085
- projectShape: "owner/repository",
7086
- homeHosts: ["gitea.com", "codeberg.org"],
7087
- gitUser: "oauth2",
7088
- allowsHost: () => true,
7089
- apiUrlFor: (origin) => `${origin.origin}/api/v1`,
7090
- requestRef: (number) => `refs/pull/${number}/head`,
7091
- newRequestUrl: (webUrl, project, branch, target) => `${webUrl.replace(/\/+$/, "")}/${segments(project)}/compare/${segments(target)}...${segments(branch)}`,
7092
- credentials: { tokenPage: (webUrl) => `${webUrl.replace(/\/+$/, "")}/user/settings/applications`, scopes: ["write:repository", "write:issue", "read:user"] },
7093
- visibilities: ["private", "public"],
7094
- group: { label: "Organization (optional)", placeholder: "acme", meaning: "The organization the repository is made in; left empty, the account whose token is connected owns it." },
7095
- emptyListHint: "Give the Gitea account whose token is connected access to the team's repository, then read the list again."
7096
- }
7097
- };
7098
- function isHostedForge(value) {
7099
- return typeof value === "string" && HOSTED_FORGES.includes(value);
6978
+ // server/limits.ts
6979
+ var WINDOW_MS = 6e4;
6980
+ function windowLimiter(perMinute, now = Date.now, maxKeys = 1e4) {
6981
+ const hits = /* @__PURE__ */ new Map();
6982
+ return (key, count = 1) => {
6983
+ const t = now();
6984
+ const recent = (hits.get(key) ?? []).filter((at2) => t - at2 < WINDOW_MS);
6985
+ hits.delete(key);
6986
+ for (const idle of hits.keys()) {
6987
+ if (hits.size < maxKeys) break;
6988
+ hits.delete(idle);
6989
+ }
6990
+ if (recent.length + count > perMinute) {
6991
+ hits.set(key, recent);
6992
+ return { ok: false, retryAfter: Math.max(1, Math.ceil(((recent[recent.length + count - perMinute - 1] ?? t) + WINDOW_MS - t) / 1e3)) };
6993
+ }
6994
+ for (let i = 0; i < count; i++) recent.push(t);
6995
+ hits.set(key, recent);
6996
+ return { ok: true, retryAfter: 0 };
6997
+ };
7100
6998
  }
7101
-
7102
- // server/forge/own-cli.ts
7103
- import { execFile as execFile3 } from "node:child_process";
7104
- import { rm as rm3 } from "node:fs/promises";
7105
- import { tmpdir as tmpdir2 } from "node:os";
7106
- function cliEnv() {
7107
- return Object.fromEntries(Object.entries(nonInteractiveEnv(process.env)).filter(([name]) => !name.startsWith("ORCHESTRATOR_") && name !== "GITEA_TOKEN" && name !== "GITEA_INSTANCE_URL"));
6999
+ var PER_KEY_PER_MINUTE = 120;
7000
+ var PER_ACCOUNT_PER_MINUTE = 300;
7001
+ function keyGate(now = Date.now) {
7002
+ const perKey = windowLimiter(PER_KEY_PER_MINUTE, now);
7003
+ const perAccount = windowLimiter(PER_ACCOUNT_PER_MINUTE, now);
7004
+ return (caller) => {
7005
+ const key = perKey(`${caller.tenant}\0${caller.keyId}`);
7006
+ if (!key.ok) return { ...key, limit: "key" };
7007
+ const account = perAccount(`${caller.tenant}\0${caller.owner.kind}:${caller.owner.id}`);
7008
+ return account.ok ? account : { ...account, limit: "account" };
7009
+ };
7108
7010
  }
7109
- var runOwnCli = (tool, args, input) => new Promise((resolve11) => {
7110
- const child = execFile3(tool, args, { cwd: tmpdir2(), env: cliEnv(), timeout: 6e4, maxBuffer: 1024 * 1024, encoding: "utf8" }, (err, stdout, stderr) => {
7111
- const failure2 = err;
7112
- resolve11({ code: failure2 ? typeof failure2.code === "number" ? failure2.code : 1 : 0, stdout: String(stdout), stderr: String(stderr), missing: failure2?.code === "ENOENT" });
7113
- });
7114
- child.stdin?.end(input ?? "");
7115
- });
7116
- var hostname2 = (host) => host.replace(/:\d+$/, "");
7117
- var ownRequest = (body) => {
7118
- const b = body;
7119
- return b && { number: b.number ?? b.iid, url: b.url ?? b.web_url };
7120
- };
7121
- var authStatus = (tool) => async (host, run2) => {
7122
- const status2 = await run2(tool, ["auth", "status", "--hostname", hostname2(host)]);
7123
- return { installed: !status2.missing, signedIn: !status2.missing && status2.code === 0, as: ["--hostname", hostname2(host)] };
7011
+ var limitKeyCall = keyGate();
7012
+ var LIMITED_EVENT_MS = 10 * 6e4;
7013
+ function limitedNotes(now = Date.now) {
7014
+ const last2 = /* @__PURE__ */ new Map();
7015
+ return async (ctx, actor, keyId, limit) => {
7016
+ const at2 = now();
7017
+ const mark = `${ctx.tenant}\0${keyId}`;
7018
+ if ((last2.get(mark) ?? -Infinity) > at2 - LIMITED_EVENT_MS) return;
7019
+ last2.set(mark, at2);
7020
+ if (last2.size > 1e4) last2.delete(last2.keys().next().value);
7021
+ await recordEvent(ctx, actor, "key.rate-limited", { subject: `key:${keyId}`, detail: `held back past ${limit === "account" ? `${PER_ACCOUNT_PER_MINUTE} calls a minute for the account` : `${PER_KEY_PER_MINUTE} calls a minute for the key`}; further refusals in the next ten minutes are not written` });
7022
+ };
7023
+ }
7024
+ var noteLimited = limitedNotes();
7025
+
7026
+ // server/keys.ts
7027
+ var MOST = { repositories: "write", requests: "write", tasks: "write", usage: "read", members: "read", settings: "read", keys: "write" };
7028
+ var ROLE_SCOPES = {
7029
+ owner: MOST,
7030
+ admin: MOST,
7031
+ member: { ...MOST, settings: "none" },
7032
+ viewer: { repositories: "read", requests: "read", tasks: "read", usage: "read", members: "read", settings: "none", keys: "read" }
7124
7033
  };
7125
- var helpsGit = (tool) => async (run2) => (await run2(tool, ["auth", "git-credential", "--help"])).code === 0;
7126
- var userField = (tool, field) => async (_host, signIn, run2) => {
7127
- const read = await run2(tool, ["api", ...signIn.as, "user"]);
7128
- if (read.code !== 0) return null;
7129
- const login = String(parsed(read.stdout)?.[field] ?? "");
7130
- return LOGIN.test(login) ? login : null;
7034
+ function serviceId(id) {
7035
+ return `service:${id}`;
7036
+ }
7037
+
7038
+ // server/passwords.ts
7039
+ var N = 1 << 15;
7040
+ var R = 8;
7041
+ var MAX_MEMORY = 128 * N * R * 2;
7042
+
7043
+ // server/integrations/health.ts
7044
+ var FAILURES_BEFORE_ALERT = 3;
7045
+ var REALERT_MS = 6 * 60 * 6e4;
7046
+ var WHAT = {
7047
+ sync: "Reading the repository",
7048
+ forge: "Reaching the repository's forge",
7049
+ tasks: "Running tasks"
7131
7050
  };
7132
- var stderrFirst = (read) => read.stderr || read.stdout;
7133
- var exitFailed = (read) => read.code === 0 ? null : Number(/HTTP (\d{3})/.exec(read.stderr)?.[1] ?? 502);
7134
- var assignmentFlags = (a) => [...a.reviewers.flatMap((r) => ["--reviewer", r]), ...a.labels.flatMap((l) => ["--label", l]), ...a.assignee ? ["--assignee", a.assignee] : []];
7135
- var TEA_SINCE = "0.15.0";
7136
- var TEA_STATUS = /^HTTP\/\S+ (\d{3})\b/m;
7137
- var teaLogins = (text) => {
7138
- try {
7139
- const rows = JSON.parse(text);
7140
- if (!Array.isArray(rows)) return [];
7141
- const field = (row, key) => String(Object.entries(row).find(([k]) => k.toLowerCase() === key)?.[1] ?? "");
7142
- return rows.filter((r) => Boolean(r) && typeof r === "object").map((r) => ({ name: field(r, "name"), url: field(r, "url"), user: field(r, "user") }));
7143
- } catch {
7144
- return [];
7051
+ var states = /* @__PURE__ */ new Map();
7052
+ var keyOf = (tenant, check) => `${tenant}\0${check.kind}\0${"repoId" in check ? check.repoId : ""}`;
7053
+ async function noteHealth(ctx, check, outcome, now = Date.now()) {
7054
+ const key = keyOf(ctx.tenant, check);
7055
+ const state = states.get(key) ?? { failures: 0, alertedAt: null, broken: false, told: false };
7056
+ states.set(key, state);
7057
+ const repoId = "repoId" in check ? check.repoId : null;
7058
+ const record3 = (kind, detail) => recordEvent(ctx, ORCHESTRATOR_ACTOR, kind, { repoId, subject: `health:${check.kind}`, detail }).catch((err) => console.error(`health: the event log did not take ${kind}: ${err.message}`));
7059
+ if (outcome.ok) {
7060
+ const wasTold = state.broken && state.told;
7061
+ Object.assign(state, { failures: 0, broken: false, told: false });
7062
+ if (wasTold) await record3("health.recovered", `${WHAT[check.kind]} works again`);
7063
+ return;
7145
7064
  }
7146
- };
7147
- var TOOLS = {
7148
- github: {
7149
- tool: "gh",
7150
- name: "GitHub's gh",
7151
- helper: "!gh auth git-credential",
7152
- install: "https://cli.github.com",
7153
- login: (host) => `gh auth login --hostname ${hostname2(host)}`,
7154
- signIn: authStatus("gh"),
7155
- helps: helpsGit("gh"),
7156
- account: userField("gh", "login"),
7157
- api: (as, path) => ["api", ...as, path],
7158
- failed: exitFailed,
7159
- told: stderrFirst,
7160
- answerNames: true,
7161
- view: (project, branch) => ["pr", "view", branch, "--repo", project, "--json", "number,url"],
7162
- pick: ownRequest,
7163
- state: (project, number) => ["pr", "view", String(number), "--repo", project, "--json", "state,mergedAt,headRefOid"],
7164
- create: (project, branch, target, title, body, assignment) => ({ args: ["pr", "create", "--repo", project, "--head", branch, "--base", target, "--title", title, "--body-file", "-", ...assignmentFlags(assignment)], input: body }),
7165
- // GitHub's own API is on api.github.com; an Enterprise server's is beside it.
7166
- hostOf: (apiUrl) => new URL(apiUrl).host === "api.github.com" ? "github.com" : new URL(apiUrl).host,
7167
- writeStatus: (project, sha, check, as) => ({ args: ["api", ...as, "-X", "POST", "-f", `state=${check.state}`, "-f", `context=${check.context}`, "-f", `description=${check.description}`, `repos/${project}/statuses/${sha}`] })
7168
- },
7169
- gitlab: {
7170
- tool: "glab",
7171
- name: "GitLab's glab",
7172
- helper: "!glab auth git-credential",
7173
- install: "https://gitlab.com/gitlab-org/cli",
7174
- login: (host) => `glab auth login --hostname ${hostname2(host)}`,
7175
- signIn: authStatus("glab"),
7176
- helps: helpsGit("glab"),
7177
- account: userField("glab", "username"),
7178
- api: (as, path) => ["api", ...as, path],
7179
- failed: exitFailed,
7180
- told: stderrFirst,
7181
- answerNames: true,
7182
- view: (project, branch) => ["mr", "view", branch, "--repo", project, "--output", "json"],
7183
- pick: ownRequest,
7184
- state: (project, number) => ["mr", "view", String(number), "--repo", project, "--output", "json"],
7185
- create: (project, branch, target, title, body, assignment) => ({ args: ["mr", "create", "--repo", project, "--source-branch", branch, "--target-branch", target, "--title", title, "--description", body, "--remove-source-branch", "--yes", ...assignmentFlags(assignment)] }),
7186
- hostOf: (apiUrl) => new URL(apiUrl).host,
7187
- // GitLab names a failed check "failed", and a check with no verdict is one too, as its driver writes it.
7188
- writeStatus: (project, sha, check, as) => ({
7189
- args: ["api", ...as, "-X", "POST", "-f", `state=${check.state === "failure" || check.state === "error" ? "failed" : check.state}`, "-f", `name=${check.context}`, "-f", `description=${check.description}`, `projects/${encodeURIComponent(project)}/statuses/${sha}`]
7190
- })
7191
- },
7192
- gitea: {
7193
- tool: "tea",
7194
- name: "Gitea's tea",
7195
- helper: "!tea login helper",
7196
- install: "https://gitea.com/gitea/tea",
7197
- login: (host) => `tea login add --url https://${host}`,
7198
- async signIn(host, run2) {
7199
- const listed = await run2("tea", ["login", "list", "--output", "json"]);
7200
- if (listed.missing) return { installed: false, signedIn: false, as: [] };
7201
- const version3 = await versionOf("tea", run2);
7202
- if (!version3 || !atLeast(version3, TEA_SINCE)) return { installed: true, signedIn: false, as: [], problem: `your tea is ${version3 ?? "of a version it does not say"}; the orchestrator needs ${TEA_SINCE} or later, update it (https://gitea.com/gitea/tea)` };
7203
- const here = listed.code === 0 ? teaLogins(listed.stdout).filter((l) => URL.canParse(l.url) && new URL(l.url).host === host) : [];
7204
- if (here.length > 1) return { installed: true, signedIn: false, as: [], problem: `tea holds ${here.length} logins for ${host} (${here.map((l) => l.name).join(", ")}); keep one with \`tea login delete <name>\`, then try again` };
7205
- const one = here[0];
7206
- return one ? { installed: true, signedIn: true, as: [`--login=${one.name}`], account: LOGIN.test(one.user) ? one.user : null } : { installed: true, signedIn: false, as: [] };
7207
- },
7208
- helps: async (_run, version3) => {
7209
- const v = await version3;
7210
- return v !== null && atLeast(v, "0.10.1");
7211
- },
7212
- account: async (_host, signIn) => signIn.account ?? null,
7213
- api: (as, path) => ["api", "-i", ...as, path],
7214
- failed(read) {
7215
- const status2 = Number(TEA_STATUS.exec(read.stderr)?.[1] ?? 0);
7216
- if (read.code === 0 && status2 >= 200 && status2 < 300) return null;
7217
- return status2 >= 400 ? status2 : 502;
7218
- },
7219
- // With -i tea writes every response header to stderr; only the status line and the forge's answer are said.
7220
- told: (read) => [TEA_STATUS.exec(read.stderr)?.[0], read.stdout].filter(Boolean).join(" ") || read.stderr,
7221
- answerNames: false,
7222
- view: (project, _branch, as) => ["api", "-i", ...as, `repos/${project}/pulls?state=open&limit=50`],
7223
- pick(body, branch) {
7224
- const pulls = Array.isArray(body) ? body : [];
7225
- const pull = pulls.find((p) => p?.head?.ref === branch);
7226
- return pull ? { number: pull.number, url: pull.html_url } : null;
7065
+ state.failures++;
7066
+ if (state.broken || state.failures < FAILURES_BEFORE_ALERT) return;
7067
+ state.broken = true;
7068
+ if (state.alertedAt !== null && now - state.alertedAt < REALERT_MS) return;
7069
+ state.alertedAt = now;
7070
+ state.told = true;
7071
+ await record3("health.degraded", `${WHAT[check.kind]} failed ${state.failures} times in a row; the last: ${outcome.detail}`);
7072
+ }
7073
+ function forgeBroken(err) {
7074
+ return err instanceof ForgeHttpError && (err.status === 0 || err.status === 401 || err.status === 403 || err.status >= 500);
7075
+ }
7076
+ function watchedForge(ctx, repo, provider) {
7077
+ if (provider.kind === "local") return provider;
7078
+ const check = { kind: "forge", repoId: repo.id };
7079
+ const watch = (call) => call.then(
7080
+ async (value) => {
7081
+ await noteHealth(ctx, check, { ok: true });
7082
+ return value;
7227
7083
  },
7228
- state: (project, number, as) => ["api", "-i", ...as, `repos/${project}/pulls/${number}`],
7229
- create: (project, branch, target, title, body, assignment, as) => ({
7230
- args: ["pulls", "create", ...as, "--repo", project, "--head", branch, "--base", target, "--title", title, "--description-file", "-", ...assignment.labels.length ? ["--labels", assignment.labels.join(",")] : [], ...assignment.assignee ? ["--assignees", assignment.assignee] : []],
7231
- input: body
7232
- }),
7233
- hostOf: (apiUrl) => new URL(apiUrl).host,
7234
- writeStatus: (project, sha, check, as) => ({ args: ["api", "-i", ...as, "-X", "POST", "-d", "@-", `repos/${project}/statuses/${sha}`], input: JSON.stringify({ state: check.state, context: check.context, description: check.description }) }),
7235
- // tea opens a pull request with no reviewers, so they are asked for after, as the person.
7236
- async assign(project, number, assignment, as, run2) {
7237
- if (!assignment.reviewers.length) return [];
7238
- const asked = await run2("tea", ["api", "-i", ...as, "-X", "POST", "-d", "@-", `repos/${project}/pulls/${number}/requested_reviewers`], JSON.stringify({ reviewers: assignment.reviewers }));
7239
- return TOOLS.gitea.failed(asked) === null ? [] : [`reviewers were not added: ${said(asked.stdout || asked.stderr)}`];
7084
+ async (err) => {
7085
+ if (forgeBroken(err)) await noteHealth(ctx, check, { ok: false, detail: err.message });
7086
+ throw err;
7087
+ }
7088
+ );
7089
+ return {
7090
+ kind: provider.kind,
7091
+ open: (r, change2) => watch(provider.open(r, change2)),
7092
+ ...provider.openForBranch ? { openForBranch: (r, pushed) => watch(provider.openForBranch(r, pushed)) } : {},
7093
+ ...provider.updateBranch ? { updateBranch: (r, branch, update) => watch(provider.updateBranch(r, branch, update)) } : {},
7094
+ ...provider.status ? { status: (r, n) => watch(provider.status(r, n)) } : {},
7095
+ ...provider.list ? { list: (r) => watch(provider.list(r)) } : {},
7096
+ ...provider.setCommitStatus ? { setCommitStatus: (sha, c) => watch(provider.setCommitStatus(sha, c)) } : {}
7097
+ };
7098
+ }
7099
+
7100
+ // server/forge/oauth-github.ts
7101
+ import { createHash as createHash4, createHmac, createSign, timingSafeEqual } from "node:crypto";
7102
+
7103
+ // server/forge/oauth.ts
7104
+ import { randomBytes as randomBytes4 } from "node:crypto";
7105
+
7106
+ // server/connect.ts
7107
+ import { isIP as isIP3 } from "node:net";
7108
+
7109
+ // server/versions.ts
7110
+ async function claimsAbove(mirror, head, current) {
7111
+ const branches = (await gitAsync(["for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/"], mirror)).split("\n").filter(Boolean).map((line) => ({ sha: line.slice(0, line.indexOf(" ")), branch: line.slice(line.indexOf(" ") + 1 + "refs/heads/".length) })).filter((b) => b.sha !== head);
7112
+ if (!branches.length) return [];
7113
+ const out = await gitAsyncBytes(["cat-file", "--batch"], mirror, branches.map((b) => `${b.sha}:${PLUGIN_MANIFEST}`).join("\n") + "\n");
7114
+ const claims = [];
7115
+ let at2 = 0;
7116
+ for (const { branch } of branches) {
7117
+ const end = out.indexOf(10, at2);
7118
+ const header = out.subarray(at2, end).toString("utf8");
7119
+ at2 = end + 1;
7120
+ const size = / blob (\d+)$/.exec(header)?.[1];
7121
+ if (size === void 0) continue;
7122
+ const text = out.subarray(at2, at2 + Number(size)).toString("utf8");
7123
+ at2 += Number(size) + 1;
7124
+ try {
7125
+ const version3 = JSON.parse(text).version;
7126
+ if (typeof version3 === "string" && (compareVersions(version3, current) ?? 0) > 0) claims.push({ branch, version: version3 });
7127
+ } catch {
7128
+ continue;
7240
7129
  }
7241
7130
  }
7242
- };
7243
- function hasOwnCli(kind) {
7244
- return typeof kind === "string" && Object.hasOwn(TOOLS, kind);
7131
+ return claims.sort((a, b) => a.branch.localeCompare(b.branch));
7245
7132
  }
7246
- function cliConfig(config) {
7247
- return config && hasOwnCli(config.kind) ? { ...config, kind: config.kind } : null;
7133
+ async function versionRaise(mirror, head) {
7134
+ const text = await gitAsyncMaybe(["show", `${head}:${PLUGIN_MANIFEST}`], mirror);
7135
+ if (text === null) return null;
7136
+ let plugin;
7137
+ try {
7138
+ plugin = JSON.parse(text);
7139
+ } catch {
7140
+ return null;
7141
+ }
7142
+ const current = plugin.version;
7143
+ if (typeof current !== "string" || compareVersions(current, current) === null) return null;
7144
+ const past = await claimsAbove(mirror, head, current);
7145
+ const version3 = versionPast(current, past);
7146
+ const target = (await gitAsyncMaybe(["symbolic-ref", "--short", "HEAD"], mirror))?.trim() || null;
7147
+ return { file: { path: PLUGIN_MANIFEST, content: JSON.stringify({ ...plugin, version: version3 }, null, 2) + "\n" }, version: version3, past, target };
7248
7148
  }
7249
- var VERSION = /\b(\d+\.\d+\.\d+)\b/;
7250
- async function versionOf(tool, run2) {
7251
- const ran = await run2(tool, ["--version"]);
7252
- return ran.code === 0 ? VERSION.exec(ran.stdout.replace(/\x1b\[[0-9;]*m/g, ""))?.[1] ?? null : null;
7149
+ function versionRaiseNote(raise) {
7150
+ const merged = raise.past.filter((c) => c.branch === raise.target);
7151
+ const open = raise.past.filter((c) => c.branch !== raise.target);
7152
+ const parts = [
7153
+ ...merged.length ? [`past ${merged[0].version}, which ${raise.target} reached since this change was prepared`] : [],
7154
+ ...open.length ? [`past ${open.map((c) => `${c.version} on ${c.branch}`).join(" and ")}, which ${open.length === 1 ? "is" : "are"} not merged yet`] : []
7155
+ ];
7156
+ return `Raises the plugin to version ${raise.version}${parts.length ? `, ${parts.join(", and ")}` : ""}, so teammates fetch it once this is merged.`;
7253
7157
  }
7254
- function atLeast(version3, since) {
7255
- const [a, b] = [version3, since].map((v) => v.split(".").map(Number));
7256
- for (let n = 0; n < 3; n++) if (a[n] !== b[n]) return a[n] > b[n];
7257
- return true;
7158
+ var LINE_BACK_COMMITS = 100;
7159
+ async function versionLineBack(mirror, head) {
7160
+ const log = await gitAsyncMaybe(["log", "--first-parent", `-n${LINE_BACK_COMMITS}`, "-G", '"version"', "--format=%H%x00%an%x00%aI", head, "--", PLUGIN_MANIFEST], mirror);
7161
+ const commits = (log ?? "").split("\n").filter(Boolean).map((line) => {
7162
+ const [sha, author, date] = line.split("\0");
7163
+ return { sha, author: (author ?? "").replace(/\p{C}+/gu, " ").trim().slice(0, 200), date: date ?? "" };
7164
+ });
7165
+ if (!commits.length) return null;
7166
+ const out = await gitAsyncBytes(["cat-file", "--batch"], mirror, commits.flatMap((c) => [`${c.sha}:${PLUGIN_MANIFEST}`, `${c.sha}^:${PLUGIN_MANIFEST}`]).join("\n") + "\n");
7167
+ const versions = [];
7168
+ let at2 = 0;
7169
+ while (at2 < out.length) {
7170
+ const end = out.indexOf(10, at2);
7171
+ const header = out.subarray(at2, end).toString("utf8");
7172
+ at2 = end + 1;
7173
+ const size = / blob (\d+)$/.exec(header)?.[1];
7174
+ if (size === void 0) {
7175
+ versions.push(void 0);
7176
+ continue;
7177
+ }
7178
+ const text = out.subarray(at2, at2 + Number(size)).toString("utf8");
7179
+ at2 += Number(size) + 1;
7180
+ let version3;
7181
+ try {
7182
+ version3 = JSON.parse(text).version;
7183
+ } catch {
7184
+ version3 = void 0;
7185
+ }
7186
+ versions.push(typeof version3 === "string" ? version3 : null);
7187
+ }
7188
+ for (const [i, commit] of commits.entries()) {
7189
+ const [now, before] = [versions[2 * i], versions[2 * i + 1]];
7190
+ if (typeof now === "string" && before === null) return { ...commit, version: now.replace(/\p{C}+/gu, " ").trim().slice(0, 40) };
7191
+ if (before === void 0) return null;
7192
+ }
7193
+ return null;
7258
7194
  }
7259
- var TOO_OLD = /unknown (flag|command|shorthand flag)|flag provided but not defined|unknown json field|accepts at most/i;
7260
- function cliSaid(t, ran) {
7261
- const told = t.told(ran);
7262
- return TOO_OLD.test(told) ? `your ${t.tool} does not know what the orchestrator asks of it; update it (${t.install}), then try again` : said(told);
7195
+
7196
+ // server/branches.ts
7197
+ import { randomBytes as randomBytes3 } from "node:crypto";
7198
+ var ORCHESTRATOR_BRANCH_PREFIX = `${DEFAULT_BRANCH_PREFIX}orchestrator-`;
7199
+ var TICKET_PLACEHOLDER = "<TICKET>";
7200
+ var BRANCH_MAX = 200;
7201
+ function recordedCommitPrefix(value) {
7202
+ if (typeof value !== "string") return {};
7203
+ const prefix = value.trim();
7204
+ const problem = commitPrefixProblem(prefix);
7205
+ return problem ? { problem } : { prefix };
7263
7206
  }
7264
- var LOGIN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
7265
- var OwnCliRefused = class extends OrchestratorError {
7207
+ async function teamNaming(mirror, head) {
7208
+ const text = await gitAsyncMaybe(["show", `${head}:${TEAM_PREFIX_FILE}`], mirror);
7209
+ let json = {};
7210
+ try {
7211
+ json = text ? JSON.parse(text) : {};
7212
+ } catch {
7213
+ return {};
7214
+ }
7215
+ const example = typeof json.branchExample === "string" ? json.branchExample.trim() : "";
7216
+ const { prefix } = recordedCommitPrefix(json.commitPrefix);
7217
+ return {
7218
+ ...prefix !== void 0 ? { commitPrefix: prefix } : {},
7219
+ ...example && !branchExampleProblem(example) ? { branchExample: example } : {}
7220
+ };
7221
+ }
7222
+ function proposedBranch(topic, naming) {
7223
+ const slug = `${topic}-${randomBytes3(3).toString("hex")}`;
7224
+ const proposal = proposeBranch(slug, { repoUrl: "", marketplaceName: "", ...naming.commitPrefix !== void 0 ? { commitPrefix: naming.commitPrefix } : {} }, naming.branchExample, {}, /* @__PURE__ */ new Set());
7225
+ if (!("branch" in proposal)) return proposal.template.replace("<TICKET>", TICKET_PLACEHOLDER);
7226
+ return proposal.branch === slug ? `${ORCHESTRATOR_BRANCH_PREFIX}${slug}` : proposal.branch;
7227
+ }
7228
+ async function branchProblem(name) {
7229
+ if (!name.trim() || name !== name.trim()) return "the branch name is empty or starts or ends with a space";
7230
+ if (name.includes(TICKET_PLACEHOLDER)) return `put the ticket in place of ${TICKET_PLACEHOLDER} in the branch name`;
7231
+ if (name.length > BRANCH_MAX) return `the branch name is longer than ${BRANCH_MAX} characters`;
7232
+ if (/\p{C}/u.test(name)) return "the branch name carries a control character";
7233
+ const trace = branchTrace(name);
7234
+ if (trace) return `that branch name cannot be used: ${trace}`;
7235
+ if (name.startsWith("-") || name.includes("@{") || await gitAsyncMaybe(["check-ref-format", "--branch", name], process.cwd()) === null) {
7236
+ return "git does not accept that as a branch name";
7237
+ }
7238
+ return null;
7239
+ }
7240
+
7241
+ // server/changes.ts
7242
+ var ChangeRefused = class extends OrchestratorError {
7266
7243
  constructor(message) {
7267
- super("own-cli", message, 409);
7244
+ super("change-refused", message, 400);
7268
7245
  }
7269
7246
  };
7270
- async function signedIn(kind, host, run2) {
7271
- const t = TOOLS[kind];
7272
- const signIn = await t.signIn(host, run2);
7273
- if (!signIn.installed) throw new OwnCliRefused(`${t.name} is not installed on this machine; install it (${t.install}), then sign in with \`${t.login(host)}\``);
7274
- if (signIn.problem) throw new OwnCliRefused(signIn.problem);
7275
- if (!signIn.signedIn) throw new OwnCliRefused(`${t.name} is not signed in to ${host}; sign in with \`${t.login(host)}\`, then try again`);
7276
- return signIn;
7247
+ var MCP_FILE = ".mcp.json";
7248
+ var CI_BUMP_SCRIPT = "scripts/bump-version.mjs";
7249
+ function show(mirror, head, path) {
7250
+ return gitAsyncMaybe(["show", `${head}:${path}`], mirror);
7277
7251
  }
7278
- async function ownCliReady(kind, host, run2 = runOwnCli) {
7279
- await signedIn(kind, host, run2);
7252
+ async function filesUnder(mirror, head, dir) {
7253
+ const out = await gitAsyncMaybe(["ls-tree", "-r", "--name-only", head, "--", dir], mirror);
7254
+ return out ? out.split("\n").filter(Boolean) : [];
7280
7255
  }
7281
- var said = (text) => redactLine(text.replace(/\p{C}+/gu, " ").trim().slice(0, 300));
7282
- function ownCredentialConfig(kind) {
7283
- return [["credential.helper", ""], ["credential.helper", TOOLS[kind].helper]];
7256
+ async function skillFiles(input, exists2, mirror, head) {
7257
+ if (typeof input.content !== "string") throw new ChangeRefused("SKILL.md is empty");
7258
+ const problem = skillProblem(input.slug, input.content);
7259
+ if (problem) throw new ChangeRefused(problem);
7260
+ const content = input.content.replace(/\r\n/g, "\n");
7261
+ const path = `skills/${input.slug}/SKILL.md`;
7262
+ if (exists2 && await show(mirror, head, path) === content) throw new ChangeRefused("SKILL.md is unchanged");
7263
+ return [{ path, content: content.endsWith("\n") ? content : `${content}
7264
+ ` }];
7284
7265
  }
7285
- function createOwnCliForge(config, workRoot, mirror, gitEnv2, run2 = runOwnCli) {
7286
- const kind = config.kind;
7287
- const t = TOOLS[kind];
7288
- const REQUEST_URL = /https?:\/\/\S+\/(?:pull|-\/merge_requests)\/(\d+)/;
7289
- const NO_ASSIGNMENT = { reviewers: [], labels: [] };
7290
- const OWN_CHECK = /^teamhandbook\/[a-z][a-z-]{0,39}$/;
7291
- const openedFor = async (branch, as) => {
7292
- const read = await run2(t.tool, t.view(config.project, branch, as));
7293
- if (t.failed(read) !== null) return null;
7294
- const found = t.pick(parsed(read.stdout), branch);
7295
- const number = Number(found?.number);
7296
- const url = String(found?.url ?? "");
7297
- return Number.isInteger(number) && number > 0 && /^https?:\/\//.test(url) ? { number, url } : null;
7298
- };
7299
- const createRequest = (branch, target, title, body, assignment, as) => {
7300
- const { args, input } = t.create(config.project, branch, target, title, body, assignment, as);
7301
- return run2(t.tool, args, input);
7302
- };
7303
- const opened = async (repo, answer, branch, assignment, as) => {
7304
- const url = t.answerNames ? REQUEST_URL.exec(answer.stdout) ?? REQUEST_URL.exec(answer.stderr) : null;
7305
- const found = url ? { number: Number(url[1]), url: url[0] } : await openedFor(branch, as);
7306
- if (!found) throw new OwnCliRefused(`${t.tool} opened a request for ${branch} in ${repo.name}, but its number was not read; find it among ${repo.name}'s requests on ${FORGES[kind].label}`);
7307
- const notes = t.assign ? await t.assign(config.project, found.number, assignment, as, run2) : [];
7308
- return { ...found, ...notes.length ? { notes } : {} };
7309
- };
7310
- const targetOf3 = async (repo) => (await gitAsyncMaybe(["symbolic-ref", "--short", "HEAD"], mirror(repo)) ?? "").trim() || "main";
7311
- return {
7312
- kind,
7313
- async open(repo, change2) {
7314
- checkBranch(change2.branch);
7315
- const { as } = await signedIn(kind, new URL(repo.url).host, run2);
7316
- const target = await targetOf3(repo);
7317
- const work = await scratch(workRoot, "own-cli-");
7266
+ function cleanList(values, what) {
7267
+ if (!Array.isArray(values) || !values.every((v) => typeof v === "string")) throw new ChangeRefused(`${what} is a list of names`);
7268
+ return [...new Set(values.map((v) => v.trim()).filter(Boolean))];
7269
+ }
7270
+ function describeServer(name, config, requiresEnv) {
7271
+ const lines = ["", `- server: \`${name}\``];
7272
+ if (typeof config.url === "string") lines.push(`- endpoint: \`${config.url}\``);
7273
+ if (typeof config.command === "string") {
7274
+ const args = Array.isArray(config.args) ? config.args.map(String) : [];
7275
+ lines.push(`- command: \`${[config.command, ...args].join(" ")}\``);
7276
+ lines.push("", "Enabling the plugin runs that command on every teammate's machine, with their privileges. Review it the way you would review a dependency.");
7277
+ }
7278
+ if (requiresEnv.length) lines.push("", `Each teammate sets ${requiresEnv.map((v) => `\`${v}\``).join(", ")} before it starts.`);
7279
+ return lines;
7280
+ }
7281
+ function commandRefusal(name, audit) {
7282
+ if (audit.reason === "unsafe-name") return "a command name is lower-case letters, digits and dashes, with a colon between a folder and the name, at most four deep, and not a device name Windows keeps, such as con or nul";
7283
+ const line = audit.secret?.line ?? (audit.identity?.where === "name" ? void 0 : audit.identity?.line);
7284
+ const where = audit.identity?.where === "name" ? "its name" : `commands/${commandFile(name)}${line ? ` line ${line}` : ""}`;
7285
+ if (audit.reason === "secret") return `/${name} is not shareable as written: ${where} looks like it contains a secret (${audit.detail}); move the value into an environment variable and refer to it by name`;
7286
+ return `/${name} is not shareable as written: ${where} carries a trace of one machine (${audit.detail}); the teammate who types it has no such account or directory, so take it out`;
7287
+ }
7288
+ function serverName(value) {
7289
+ const name = String(value ?? "");
7290
+ if (!SERVER_NAME.test(name)) throw new ChangeRefused("a server name is letters, digits, dot, dash or underscore");
7291
+ return name;
7292
+ }
7293
+ function withoutServer(existing, name) {
7294
+ let parsed2 = null;
7295
+ try {
7296
+ parsed2 = existing === null ? null : JSON.parse(existing);
7297
+ } catch {
7298
+ throw new ChangeRefused(`${MCP_FILE} is not valid JSON; fix it in the repository first, the orchestrator will not overwrite a file it cannot read`);
7299
+ }
7300
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
7301
+ if (existing !== null && !isObject(parsed2)) throw new ChangeRefused(`${MCP_FILE} is not a JSON object`);
7302
+ const servers = isObject(parsed2) ? isObject(parsed2.mcpServers) ? parsed2.mcpServers : parsed2 : {};
7303
+ if (!Object.hasOwn(servers, name)) throw new ChangeRefused(`${MCP_FILE} declares no server ${name} to remove`);
7304
+ delete servers[name];
7305
+ return JSON.stringify(parsed2, null, 2) + "\n";
7306
+ }
7307
+ async function buildChange(mirror, head, raw) {
7308
+ const input = raw ?? {};
7309
+ switch (input.kind) {
7310
+ case "skill.add":
7311
+ case "skill.edit": {
7312
+ const slug = String(input.slug ?? "");
7313
+ if (!SKILL_SLUG.test(slug)) throw new ChangeRefused("a skill name is lower-case letters, digits and dashes");
7314
+ const exists2 = (await filesUnder(mirror, head, `skills/${slug}`)).length > 0;
7315
+ if (input.kind === "skill.add" && exists2) throw new ChangeRefused(`${slug} already exists; edit it instead`);
7316
+ if (input.kind === "skill.edit" && !exists2) throw new ChangeRefused(`there is no skill ${slug} to edit`);
7317
+ return {
7318
+ files: await skillFiles({ slug, content: input.content }, exists2, mirror, head),
7319
+ proposal: `feat(skill): ${exists2 ? "update" : "add"} ${slug}`,
7320
+ body: [`${exists2 ? "Updates" : "Adds"} the skill \`${slug}\`.`],
7321
+ topic: `skill-${slug}`
7322
+ };
7323
+ }
7324
+ case "skill.delete": {
7325
+ const slug = String(input.slug ?? "");
7326
+ if (!SKILL_SLUG.test(slug)) throw new ChangeRefused("a skill name is lower-case letters, digits and dashes");
7327
+ const files = await filesUnder(mirror, head, `skills/${slug}`);
7328
+ if (!files.length) throw new ChangeRefused(`there is no skill ${slug} to remove`);
7329
+ return {
7330
+ files: files.map((path) => ({ path, content: null })),
7331
+ proposal: `chore(skill): remove ${slug}`,
7332
+ body: [`Removes the skill \`${slug}\` and every file it ships (${files.length}).`],
7333
+ topic: `remove-${slug}`
7334
+ };
7335
+ }
7336
+ case "mcp.add":
7337
+ case "mcp.edit": {
7338
+ const name = String(input.name ?? "");
7339
+ const checked3 = serverProblem(name, input.config);
7340
+ if ("refused" in checked3) throw new ChangeRefused(checked3.refused);
7341
+ const { audit } = checked3;
7342
+ const config = input.config;
7343
+ const existing = await show(mirror, head, MCP_FILE);
7344
+ const editing = input.kind === "mcp.edit";
7345
+ let merged;
7318
7346
  try {
7319
- const headSha = await changeCommit(mirror(repo), work, change2, repo.name);
7320
- const env2 = await gitEnv2(repo);
7321
- if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
7322
- const taken = await gitAsyncMaybe(["ls-remote", "--heads", repo.url, change2.branch], work, { env: env2 });
7323
- if (taken === null) throw new OwnCliRefused(`git did not reach ${repo.name} with your ${t.tool} sign-in; check it with \`${t.tool} auth status\``);
7324
- if (taken.trim()) throw new ForgeRefusal(`branch ${change2.branch} already exists in ${repo.name}; remove it on ${FORGES[kind].label}, then try again`);
7325
- await gitAsync(["push", "--porcelain", repo.url, `${headSha}:refs/heads/${change2.branch}`], work, void 0, void 0, { env: env2 }).catch((err) => {
7326
- throw new OwnCliRefused(`git did not push ${change2.branch} to ${repo.name} with your ${t.tool} sign-in: ${said(err.stderr || err.message)}; check it with \`${t.tool} auth status\`, then try again`);
7327
- });
7328
- const assignment = change2.assignment ?? NO_ASSIGNMENT;
7329
- const answer = await createRequest(change2.branch, target, change2.title, change2.body, assignment, as);
7330
- if (answer.code !== 0) {
7331
- const left = await gitAsync(["push", "--porcelain", repo.url, `:refs/heads/${change2.branch}`], work, void 0, void 0, { env: env2 }).then(
7332
- () => "the branch was removed again",
7333
- () => `the branch stayed: ${change2.branch}`
7334
- );
7335
- throw new OwnCliRefused(`${t.tool} did not open the request: ${cliSaid(t, answer)}; ${left}; check it with \`${t.tool} auth status\`, then try again`);
7336
- }
7337
- return { ...await opened(repo, answer, change2.branch, assignment, as), branch: change2.branch, headSha };
7338
- } finally {
7339
- await rm3(work, { recursive: true, force: true });
7347
+ merged = mergeServersIntoMcpJson(existing, [{ name, scope: "project", config }], (n) => editing && n === name);
7348
+ } catch (err) {
7349
+ throw new ChangeRefused(err.message);
7340
7350
  }
7341
- },
7342
- // The branch as the forge holds it now, read with the person's sign-in; the push goes without
7343
- // force, so a branch someone moved meanwhile makes git refuse rather than lose their commit.
7344
- async updateBranch(repo, branch, update) {
7345
- checkBranch(branch);
7346
- await ownCliReady(kind, new URL(repo.url).host, run2);
7347
- const env2 = await gitEnv2(repo);
7348
- if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
7349
- const work = await scratch(workRoot, "own-cli-update-");
7350
- try {
7351
- if (await gitAsyncMaybe(["fetch", "--quiet", repo.url, `refs/heads/${branch}:refs/orchestrator/branch`], work, { env: env2 }) === null) {
7352
- throw new ForgeRefusal(`branch ${branch} was not read from ${repo.name}; check it is on ${FORGES[kind].label}, then check your sign-in with \`${t.tool} auth status\``);
7353
- }
7354
- const head = (await gitAsync(["rev-parse", "refs/orchestrator/branch"], work)).trim();
7355
- if (head !== update.expectedHead) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
7356
- const headSha = await changeCommit(work, work, { title: update.title, body: "", commitBody: update.commitBody ?? "", branch, baseSha: head, files: update.files, author: update.author }, repo.name);
7357
- await gitAsync(["push", "--porcelain", repo.url, `${headSha}:refs/heads/${branch}`], work, void 0, void 0, { env: env2 }).catch((err) => {
7358
- const told = err.stderr || err.message;
7359
- if (/non-fast-forward|fetch first|\[rejected\]/.test(told)) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
7360
- throw new OwnCliRefused(`git did not push ${branch} to ${repo.name} with your ${t.tool} sign-in: ${said(told)}; check it with \`${t.tool} auth status\`, then try again`);
7361
- });
7362
- return { headSha };
7363
- } finally {
7364
- await rm3(work, { recursive: true, force: true });
7351
+ if (merged.collided.length) throw new ChangeRefused(`${MCP_FILE} already declares ${name}; edit it instead`);
7352
+ if (editing && !merged.replaced.includes(name)) throw new ChangeRefused(`${MCP_FILE} declares no server ${name} to edit`);
7353
+ if (editing && JSON.stringify(declaredServers(existing)[name]) === JSON.stringify(config)) throw new ChangeRefused(`${name} is unchanged`);
7354
+ return {
7355
+ files: [{ path: MCP_FILE, content: merged.merged }],
7356
+ proposal: `feat(mcp): ${editing ? "update" : "add"} ${name}`,
7357
+ body: [`${editing ? "Changes" : "Declares"} the MCP server \`${name}\` (${audit.transport}) for everyone who installs this plugin.`, ...describeServer(name, config, audit.requiresEnv)],
7358
+ topic: `mcp-${name.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`
7359
+ };
7360
+ }
7361
+ case "command.add":
7362
+ case "command.edit": {
7363
+ const name = String(input.name ?? "");
7364
+ if (typeof input.content !== "string" || !input.content.trim()) throw new ChangeRefused("the command's text is empty");
7365
+ if (Buffer.byteLength(input.content) > MAX_SKILL_BYTES) throw new ChangeRefused("the command is larger than 256 KiB");
7366
+ const content = input.content.replace(/\r\n/g, "\n");
7367
+ const audit = auditCommandText(name, content);
7368
+ if (!audit.shareable) throw new ChangeRefused(commandRefusal(name, audit));
7369
+ const path = `commands/${commandFile(name)}`;
7370
+ const existing = await show(mirror, head, path);
7371
+ const editing = input.kind === "command.edit";
7372
+ if (!editing && existing !== null) throw new ChangeRefused(`/${name} already exists; edit it instead`);
7373
+ if (editing && existing === null) throw new ChangeRefused(`there is no command /${name} to edit`);
7374
+ const text = content.endsWith("\n") ? content : `${content}
7375
+ `;
7376
+ if (text === existing) throw new ChangeRefused(`/${name} is unchanged`);
7377
+ return {
7378
+ files: [{ path, content: text }],
7379
+ proposal: `feat(command): ${editing ? "update" : "add"} /${name}`,
7380
+ body: [`${editing ? "Changes" : "Adds"} the slash command \`/${name}\` (${path}) for everyone who installs this plugin.`],
7381
+ topic: `command-${name.replace(/:/g, "-")}`
7382
+ };
7383
+ }
7384
+ case "command.delete": {
7385
+ const name = String(input.name ?? "");
7386
+ const named2 = auditCommandText(name, "");
7387
+ if (!named2.shareable) throw new ChangeRefused(commandRefusal(name, named2));
7388
+ const path = `commands/${commandFile(name)}`;
7389
+ if (await show(mirror, head, path) === null) throw new ChangeRefused(`there is no command /${name} to remove`);
7390
+ return {
7391
+ files: [{ path, content: null }],
7392
+ proposal: `chore(command): remove /${name}`,
7393
+ body: [`Removes the slash command \`/${name}\` (${path}); teammates lose it once their plugin updates.`],
7394
+ topic: `remove-command-${name.replace(/:/g, "-")}`
7395
+ };
7396
+ }
7397
+ case "mcp.remove": {
7398
+ const name = serverName(input.name);
7399
+ return {
7400
+ files: [{ path: MCP_FILE, content: withoutServer(await show(mirror, head, MCP_FILE), name) }],
7401
+ proposal: `chore(mcp): remove ${name}`,
7402
+ body: [`Removes the MCP server \`${name}\`; teammates' Claude Code stops starting it once their plugin updates. Every other entry in ${MCP_FILE} is kept.`],
7403
+ topic: `remove-mcp-${name.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`
7404
+ };
7405
+ }
7406
+ case "team.settings": {
7407
+ const reviewers = cleanList(input.reviewers, "reviewers");
7408
+ const labels = cleanList(input.labels, "labels");
7409
+ const problem = assignmentRecordProblem({ reviewers, labels });
7410
+ if (problem) throw new ChangeRefused(problem);
7411
+ const { existing, json } = await teamFile(mirror, head);
7412
+ const content = JSON.stringify({ ...json, reviewers, labels }, null, 2) + "\n";
7413
+ if (content === existing) throw new ChangeRefused("the reviewers and labels are unchanged");
7414
+ return {
7415
+ files: [{ path: TEAM_PREFIX_FILE, content }],
7416
+ proposal: "chore: set the reviewers and labels for requests to this repository",
7417
+ body: [
7418
+ `Requests to this repository will ask ${reviewers.join(", ") || "no one"} to review`,
7419
+ `and carry ${labels.length ? labels.join(", ") : "no label"}. Every other setting in ${TEAM_PREFIX_FILE} is kept.`
7420
+ ],
7421
+ topic: "request-settings"
7422
+ };
7423
+ }
7424
+ case "team.naming": {
7425
+ if (typeof input.commitPrefix !== "string" || typeof input.branchExample !== "string") throw new ChangeRefused("the commit prefix and the example branch are text");
7426
+ const commitPrefix = input.commitPrefix.trim();
7427
+ const branchExample = input.branchExample.trim();
7428
+ const prefixProblem = commitPrefixProblem(commitPrefix);
7429
+ if (prefixProblem) throw new ChangeRefused(`that commit prefix cannot be recorded: it is ${prefixProblem}`);
7430
+ const exampleProblem = branchExample ? branchExampleProblem(branchExample) : null;
7431
+ if (exampleProblem) throw new ChangeRefused(`that example branch cannot be recorded: it is ${exampleProblem}`);
7432
+ const { existing, json } = await teamFile(mirror, head);
7433
+ const recorded = recordedCommitPrefix(json.commitPrefix).prefix ?? "";
7434
+ if (commitPrefix !== recorded && await show(mirror, head, CI_BUMP_SCRIPT) !== null) {
7435
+ const how = commitPrefix ? `run /handbook:init --upgrade --commit-prefix "${commitPrefix}" from a teammate's machine, which writes the team file and the job in one request` : `set commitPrefix to "" in ${TEAM_PREFIX_FILE}, then run /handbook:init --upgrade from a teammate's machine, which rewrites the job from it`;
7436
+ throw new ChangeRefused(`this repository's CI job writes its version commits with the team's prefix built in, so the prefix changes together with that job: ${how}`);
7365
7437
  }
7366
- },
7367
- // The branch is the person's own work, pushed by their runner: it is read, never written or taken back.
7368
- async openForBranch(repo, pushed) {
7369
- checkBranch(pushed.branch);
7370
- const { as } = await signedIn(kind, new URL(repo.url).host, run2);
7371
- const env2 = await gitEnv2(repo);
7372
- if (!env2) throw new OwnCliRefused(`${repo.name} is not connected to reach with your ${t.tool} sign-in; connect it again under Projects with the token left empty`);
7373
- const heads = await gitAsyncMaybe(["ls-remote", "--heads", repo.url, `refs/heads/${pushed.branch}`], tmpdir2(), { env: env2 });
7374
- if (heads === null) throw new OwnCliRefused(`git did not reach ${repo.name} with your ${t.tool} sign-in; check it with \`${t.tool} auth status\``);
7375
- const headSha = /^([0-9a-f]{40})\s/.exec(heads)?.[1];
7376
- if (!headSha) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
7377
- const assignment = pushed.assignment ?? NO_ASSIGNMENT;
7378
- const answer = await createRequest(pushed.branch, pushed.target ?? await targetOf3(repo), pushed.title, pushed.body, assignment, as);
7379
- if (answer.code !== 0) throw new OwnCliRefused(`${t.tool} did not open the request: ${cliSaid(t, answer)}; the branch stays as it was pushed, so open it again once \`${t.tool} auth status\` says you are signed in`);
7380
- return { ...await opened(repo, answer, pushed.branch, assignment, as), branch: pushed.branch, headSha };
7381
- },
7382
- // A commit status alone, in the orchestrator's own checks: a comment, a label or a merge is never written with the person's sign-in.
7383
- async setCommitStatus(sha, check) {
7384
- if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error("a commit status is set on a full commit id");
7385
- if (!OWN_CHECK.test(check.context)) throw new Error(`${check.context} is not one of the orchestrator's own checks`);
7386
- const { as } = await signedIn(kind, t.hostOf(config.apiUrl), run2);
7387
- const { args, input } = t.writeStatus(config.project, sha, { ...check, description: check.description.slice(0, 140) }, as);
7388
- const wrote = await run2(t.tool, args, input);
7389
- if (t.failed(wrote) !== null) throw new OwnCliRefused(`${t.tool} did not write the ${check.context} check on ${sha.slice(0, 7)}: ${cliSaid(t, wrote)}`);
7390
- },
7391
- async status(repo, number) {
7392
- const { as } = await signedIn(kind, new URL(repo.url).host, run2);
7393
- const read = await run2(t.tool, t.state(config.project, number, as));
7394
- if (t.failed(read) !== null) throw new OwnCliRefused(`${t.tool} did not read request ${number}: ${cliSaid(t, read)}`);
7395
- const body = parsed(read.stdout);
7396
- if (!body) throw new OwnCliRefused(`${t.tool} answered request ${number}'s state with something other than JSON; update it (${t.install}), then try again`);
7397
- const state = String(body.state ?? "").toLowerCase();
7398
- const head = body.headRefOid ?? body.sha ?? body.head?.sha;
7399
- if (state === "merged" || body.merged === true) return forgeState("merged", forgeTime(body.mergedAt ?? body.merged_at), head);
7400
- return forgeState(state === "open" || state === "opened" ? "open" : "closed", null, head);
7438
+ const next = { ...json, commitPrefix, branchExample };
7439
+ if (!branchExample) delete next.branchExample;
7440
+ const content = JSON.stringify(next, null, 2) + "\n";
7441
+ if (content === existing) throw new ChangeRefused("the commit prefix and the example branch are unchanged");
7442
+ return {
7443
+ files: [{ path: TEAM_PREFIX_FILE, content }],
7444
+ proposal: "chore: set how commits and branches to this repository are named",
7445
+ body: [
7446
+ commitPrefix ? `Commits to this repository will start with \`${commitPrefix}\`.` : "Commits to this repository will carry no prefix.",
7447
+ branchExample ? `Branches will be named like \`${branchExample}\`.` : "Branches will follow no example.",
7448
+ `Every other setting in ${TEAM_PREFIX_FILE} is kept.`
7449
+ ],
7450
+ topic: "naming"
7451
+ };
7401
7452
  }
7402
- };
7453
+ default:
7454
+ throw new ChangeRefused("unknown kind of change");
7455
+ }
7403
7456
  }
7404
- function parsed(text) {
7457
+ async function teamFile(mirror, head) {
7458
+ const existing = await show(mirror, head, TEAM_PREFIX_FILE);
7459
+ if (existing === null) return { existing, json: {} };
7460
+ let parsed2;
7405
7461
  try {
7406
- const value = JSON.parse(text);
7407
- return value && typeof value === "object" ? value : null;
7462
+ parsed2 = JSON.parse(existing);
7408
7463
  } catch {
7409
- return null;
7464
+ throw new ChangeRefused(`${TEAM_PREFIX_FILE} is not valid JSON; fix it in the repository first, the orchestrator will not overwrite a file it cannot read`);
7410
7465
  }
7466
+ if (!parsed2 || typeof parsed2 !== "object" || Array.isArray(parsed2)) throw new ChangeRefused(`${TEAM_PREFIX_FILE} is not a JSON object`);
7467
+ return { existing, json: parsed2 };
7468
+ }
7469
+ async function prepareChange(mirror, head, input, message, by, naming = {}, branch) {
7470
+ return prepareBuilt(mirror, head, await buildChange(mirror, head, input), message, by, naming, branch);
7471
+ }
7472
+ async function prepareBuilt(mirror, head, built, message, by, naming = {}, branch) {
7473
+ if (typeof message !== "string" || !message.trim()) throw new ChangeRefused(`write the commit message; the orchestrator proposes "${built.proposal}"`);
7474
+ const problem = commitMessageProblem(message);
7475
+ if (problem) throw new ChangeRefused(`that commit message cannot be used: ${problem}`);
7476
+ const name = typeof branch === "string" ? branch : proposedBranch(built.topic, naming);
7477
+ const branchRefusal2 = await branchProblem(name);
7478
+ if (branchRefusal2) throw new ChangeRefused(typeof branch === "string" ? branchRefusal2 : `this team names branches like ${naming.branchExample}; name the ticket in the branch, in place of ${TICKET_PLACEHOLDER} in ${name}`);
7479
+ const raise = await versionRaise(mirror, head);
7480
+ const body = [...built.body, "", `Proposed from the TeamHandbook Orchestrator by ${by}.`];
7481
+ if (raise) body.push(versionRaiseNote(raise));
7482
+ return {
7483
+ title: commitSubject(commitMessagePrefix(naming.commitPrefix), message),
7484
+ body: body.join("\n"),
7485
+ branch: name,
7486
+ files: raise ? [...built.files, raise.file] : built.files
7487
+ };
7411
7488
  }
7412
7489
 
7413
7490
  // ../package.json
7414
7491
  var package_default = {
7415
7492
  name: "teamhandbook",
7416
- version: "0.33.0",
7493
+ version: "0.34.0",
7417
7494
  description: "Manage your team's Claude Code setup from one git repository: approve a skill, an MCP server, or a slash command once, and every teammate's copy picks it up.",
7418
7495
  type: "module",
7419
7496
  private: true,
@@ -9444,11 +9521,8 @@ function canEditTeam(user, team) {
9444
9521
  // server/tasks/routes.ts
9445
9522
  import { isAbsolute as isAbsolute8, join as join29 } from "node:path";
9446
9523
 
9447
- // server/tasks/types.ts
9448
- var ORCHESTRATOR_AGENT = "orchestrator";
9449
-
9450
9524
  // server/tasks/verify.ts
9451
- import { lstat as lstat5, readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
9525
+ import { lstat as lstat5, readdir as readdir4, readFile as readFile4, realpath as realpath3 } from "node:fs/promises";
9452
9526
  import { basename as basename9, dirname as dirname12, isAbsolute as isAbsolute6, join as join23, normalize as normalize2 } from "node:path";
9453
9527
 
9454
9528
  // server/tasks/references.ts
@@ -10393,7 +10467,7 @@ async function toolChoiceOf(ctx, projectId, projectSkills, mcpServers, confirmed
10393
10467
 
10394
10468
  // server/tasks/check-sandbox.ts
10395
10469
  import { execFile as execFile4 } from "node:child_process";
10396
- import { access, realpath as realpath3, stat as stat3 } from "node:fs/promises";
10470
+ import { access, realpath as realpath4, stat as stat3 } from "node:fs/promises";
10397
10471
  import { dirname as dirname14, join as join24 } from "node:path";
10398
10472
  var TOOL_PLACES = [
10399
10473
  ".npm",
@@ -10453,7 +10527,7 @@ var CREDENTIAL_PLACES = [
10453
10527
  ];
10454
10528
  var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
10455
10529
  async function resolved(places) {
10456
- const kept2 = async (paths) => [...new Set((await Promise.all(paths.map((p) => realpath3(p).catch(() => null)))).filter((p) => p !== null))];
10530
+ const kept2 = async (paths) => [...new Set((await Promise.all(paths.map((p) => realpath4(p).catch(() => null)))).filter((p) => p !== null))];
10457
10531
  return { hidden: await kept2(places.hidden), tools: await kept2(places.tools), secrets: await kept2(places.secrets), readable: await kept2(places.readable), writable: await kept2(places.writable) };
10458
10532
  }
10459
10533
  function checkPlaces(task, person, dataDir, platform = process.platform) {
@@ -10556,6 +10630,9 @@ async function sandboxed(box, places, inv) {
10556
10630
  var TEMPLATE_MAX = 8 * 1024;
10557
10631
  var BLOB_MAX = 256 * 1024;
10558
10632
 
10633
+ // server/tasks/plugin-install.ts
10634
+ var HANDBOOK_MARKETPLACE = new URL(REPOSITORY).pathname.replace(/^\//, "");
10635
+
10559
10636
  // server/tasks/folder-trust.ts
10560
10637
  import { lstat as lstat6 } from "node:fs/promises";
10561
10638
  async function inPlaceFolder(repo) {
@@ -11034,6 +11111,9 @@ function processTransport(inv, options) {
11034
11111
  };
11035
11112
  }
11036
11113
 
11114
+ // server/runner-store.ts
11115
+ var MACHINE_FEATURES = ["workspace-continues"];
11116
+
11037
11117
  // runner/profile.ts
11038
11118
  import { createPrivateKey, generateKeyPairSync } from "node:crypto";
11039
11119
  import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync9, readFileSync as readFileSync8, readdirSync as readdirSync4, renameSync as renameSync3, rmSync as rmSync6, writeFileSync as writeFileSync7 } from "node:fs";
@@ -11198,7 +11278,7 @@ function httpLink(profile, fetchImpl = fetch) {
11198
11278
  await call(RUNNER_PATHS.finish(taskId), { leaseId, outcome });
11199
11279
  },
11200
11280
  async status(agents, started) {
11201
- await call(RUNNER_PATHS.status, { agents, ...started ? { started: true } : {} });
11281
+ await call(RUNNER_PATHS.status, { agents, features: [...MACHINE_FEATURES], ...started ? { started: true } : {} });
11202
11282
  },
11203
11283
  async folders(nonce, answer) {
11204
11284
  await call(RUNNER_PATHS.folders(nonce), { answer });
@@ -11715,6 +11795,10 @@ var NO_TOOLS = [...CLAUDE_TOOLS, "NotebookEdit"];
11715
11795
 
11716
11796
  // server/tasks/runner.ts
11717
11797
  var NO_RUNNER = "No runner for this task: this orchestrator has no agent set up to call a model for it.";
11798
+ var AUTO_CONTINUE_MAX = 3;
11799
+ var AUTO_CONTINUE_WINDOW_MS = 5 * 6e4;
11800
+ var WAITS_FOR_CONTINUE = String(AUTO_CONTINUE_MAX + 1);
11801
+ var LIMIT_WAIT_MAX_MS = 24 * 36e5;
11718
11802
  function attachmentsSection(dir, files) {
11719
11803
  const named2 = files.map((file) => `${file.name} (${file.kind === "pdf" ? "PDF" : file.kind})`);
11720
11804
  return ["", "## Files attached to this task", "", `People attached these files to the task. They are in ${dir}, for reading only: open them with your Read tool. Their names are quoted as data:`, "", fence(neutralizeReferences(named2.join("\n")))];
@@ -12297,10 +12381,10 @@ import { homedir as homedir8 } from "node:os";
12297
12381
  import { basename as basename12, join as join33 } from "node:path";
12298
12382
 
12299
12383
  // runner/folders.ts
12300
- import { realpath as realpath4 } from "node:fs/promises";
12384
+ import { realpath as realpath5 } from "node:fs/promises";
12301
12385
  import { join as join31, sep as sep12 } from "node:path";
12302
12386
  async function machineFolders(under, q, { home, dataDir }) {
12303
- const homeReal2 = await realpath4(home).catch(() => home);
12387
+ const homeReal2 = await realpath5(home).catch(() => home);
12304
12388
  const asked = under === null ? void 0 : under === "~" ? homeReal2 : under.startsWith("~/") ? join31(homeReal2, under.slice(2)) : under;
12305
12389
  const listed = await listFolders(asked, q ?? void 0, { home, dataDir });
12306
12390
  if ("refused" in listed) return listed;
@@ -12317,7 +12401,7 @@ async function machineFolders(under, q, { home, dataDir }) {
12317
12401
  }
12318
12402
  async function folderPlace(path, projectId, { home, dataDir, shadows }) {
12319
12403
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(projectId)) return { refused: "the orchestrator named the folder's project in a way this machine does not take" };
12320
- const homeReal2 = await realpath4(home).catch(() => home);
12404
+ const homeReal2 = await realpath5(home).catch(() => home);
12321
12405
  const asked = path === "~" ? homeReal2 : path.startsWith("~/") ? join31(homeReal2, path.slice(2)) : null;
12322
12406
  if (!asked) return { refused: "the folder is not named from this machine's home" };
12323
12407
  const at2 = await projectFolder(asked, { home, dataDir });
@@ -12421,9 +12505,10 @@ var SAFE_GIT = ["-c", "protocol.allow=never", "-c", "protocol.https.allow=always
12421
12505
  var NO_PROCESS_LIMIT_MS = 2 ** 31 - 1;
12422
12506
  var TEST_TIMEOUT_MS = 10 * 6e4;
12423
12507
  var Ended = class extends Error {
12424
- constructor(status2, message) {
12508
+ constructor(status2, message, kept2 = { nativeSessionId: null }) {
12425
12509
  super(message);
12426
12510
  this.status = status2;
12511
+ this.kept = kept2;
12427
12512
  }
12428
12513
  };
12429
12514
  var CONVERSATION_PROCESS_MS2 = 2 ** 31 - 1;
@@ -12457,7 +12542,7 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12457
12542
  if (!adapter) return ended3("failed", `This machine runs no ${task.agent} for tasks yet.`);
12458
12543
  const root2 = join33(orgDir(dataDir, org), "tasks", task.id);
12459
12544
  if ("folder" in work) return inFolder2(task, work, adapter, root2, hooks);
12460
- if ("workspace" in work) return inWorkspace(task, work, adapter, root2, hooks);
12545
+ if ("workspace" in work) return inWorkspace2(task, work, adapter, root2, hooks);
12461
12546
  if (work.branch === work.repo.baseBranch) return ended3("failed", "The task's branch is the repository's own base branch; nothing is pushed there.");
12462
12547
  const paths = { root: root2, work: join33(root2, "work"), home: join33(root2, "home"), tmp: join33(root2, "tmp"), git: join33(root2, "git") };
12463
12548
  const resume = task.nativeSession !== null && existsSync11(paths.work) && existsSync11(paths.git);
@@ -12466,7 +12551,7 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12466
12551
  try {
12467
12552
  outcome = await runIn(task, work, adapter, paths, resume, hooks);
12468
12553
  } catch (error) {
12469
- outcome = error instanceof Ended ? ended3(error.status, error.message) : ended3("failed", error instanceof Error ? error.message : String(error));
12554
+ outcome = error instanceof Ended ? { ...ended3(error.status, error.message), ...error.kept } : ended3("failed", error instanceof Error ? error.message : String(error));
12470
12555
  }
12471
12556
  if (outcome.status !== "interrupted") {
12472
12557
  await releasePersonalGuard(root2);
@@ -12560,14 +12645,14 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12560
12645
  outcome = refused ? { ...ended3("failed", refused.failed), changes: { ...changes, undone: refused.undone } } : { status: "needs-review", error: result.stopped ?? null, nativeSessionId: result.nativeSessionId, branch: null, position: null, request: null, changes };
12561
12646
  } catch (error) {
12562
12647
  const changes = await keep().catch(() => null);
12563
- outcome = { ...error instanceof Ended ? ended3(error.status, error.message) : ended3("failed", error instanceof Error ? error.message : String(error)), changes };
12648
+ outcome = { ...error instanceof Ended ? { ...ended3(error.status, error.message), ...error.kept } : ended3("failed", error instanceof Error ? error.message : String(error)), changes };
12564
12649
  }
12565
12650
  await releasePersonalGuard(root2);
12566
12651
  await rm7(root2, { recursive: true, force: true });
12567
12652
  working.delete(place.folder);
12568
12653
  return outcome;
12569
12654
  }
12570
- async function inWorkspace(task, work, adapter, root2, hooks) {
12655
+ async function inWorkspace2(task, work, adapter, root2, hooks) {
12571
12656
  if (work.workspace.machineId !== machineId) return ended3("failed", "This task's folder is on another of your machines, so this one does not run it.");
12572
12657
  const place = await folderPlace(work.workspace.path, work.workspace.projectId, { home: hostEnv.HOME || homedir8(), dataDir, shadows: join33(orgDir(dataDir, org), "shadow") });
12573
12658
  if ("refused" in place) return ended3("failed", `The task did not run: ${place.refused}.`);
@@ -12577,11 +12662,11 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12577
12662
  if (task.nativeSession !== null && !resume) return ended3("failed", "The copies this task's session worked on are gone from this machine, so it cannot go on; start it again.");
12578
12663
  let outcome;
12579
12664
  try {
12580
- const repos = resume ? JSON.parse(await readFile7(manifest, "utf8")) : await copyRepos(place.folder, paths, manifest, hooks);
12665
+ const repos = resume ? JSON.parse(await readFile7(manifest, "utf8")) : await copyRepos(place.folder, paths, manifest, hooks, work);
12581
12666
  const result = await agentRun(task, work, adapter, paths, resume, hooks);
12582
12667
  outcome = await deliverRepos(task, work, place.folder, paths, repos, result, hooks);
12583
12668
  } catch (error) {
12584
- outcome = error instanceof Ended ? ended3(error.status, error.message) : ended3("failed", error instanceof Error ? error.message : String(error));
12669
+ outcome = error instanceof Ended ? { ...ended3(error.status, error.message), ...error.kept } : ended3("failed", error instanceof Error ? error.message : String(error));
12585
12670
  }
12586
12671
  if (outcome.status !== "interrupted") {
12587
12672
  await releasePersonalGuard(root2);
@@ -12589,23 +12674,31 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12589
12674
  }
12590
12675
  return outcome;
12591
12676
  }
12592
- async function copyRepos(folder, paths, manifest, hooks) {
12677
+ async function copyRepos(folder, paths, manifest, hooks, work) {
12593
12678
  await releasePersonalGuard(paths.root);
12594
12679
  await rm7(paths.root, { recursive: true, force: true });
12595
12680
  await Promise.all([paths.work, paths.home, paths.tmp, paths.git].map((dir) => mkdir5(dir, { recursive: true })));
12596
12681
  const found = await workingCopies(folder);
12597
12682
  if ("tooMany" in found) throw new Ended("failed", `The task did not run: the folder holds more than ${WORKING_COPIES_MAX} repositories; pick the one, or the folder of the few, the task is about.`);
12598
12683
  if (!found.length) throw new Ended("failed", "The task did not run: the folder holds no git repository; open it as a folder project to work in it in place.");
12684
+ const goingOn = work.continues?.repos ?? [];
12685
+ const gone = goingOn.find((entry) => !found.includes(entry.path));
12686
+ if (gone) throw new Ended("failed", `${gone.path || basename12(folder)} is no longer a repository in the folder, so the task cannot go on from it; nothing was changed.`);
12599
12687
  const repos = [];
12600
12688
  for (const path of found) {
12601
12689
  const own = join33(folder, path);
12602
- const head = (await git3(paths, ["-C", own, "rev-parse", "--verify", "HEAD^{commit}"], { noDirs: true }).catch(() => "")).trim();
12690
+ const from = goingOn.find((entry) => entry.path === path);
12691
+ if (from) {
12692
+ const at3 = (await git3(paths, ["-C", own, "rev-parse", "--verify", "--quiet", `refs/heads/${work.branch}^{commit}`], { noDirs: true }).catch(() => "")).trim();
12693
+ if (at3 !== from.head) throw new Ended("failed", `${work.branch} of ${path || basename12(folder)} moved since the request was read; nothing was changed.`);
12694
+ }
12695
+ const head = from ? from.head : (await git3(paths, ["-C", own, "rev-parse", "--verify", "HEAD^{commit}"], { noDirs: true }).catch(() => "")).trim();
12603
12696
  if (!head) {
12604
12697
  hooks.log(`${path || "The folder"} has no commit yet, so the task leaves it out.`);
12605
12698
  continue;
12606
12699
  }
12607
12700
  const objects = (await git3(paths, ["-C", own, "rev-parse", "--path-format=absolute", "--git-common-dir"], { noDirs: true })).trim();
12608
- const repo = { path, head, git: join33(paths.git, path ? path.replace(/[^A-Za-z0-9._-]/g, "_") : "_folder") };
12701
+ const repo = { path, head, git: join33(paths.git, path ? path.replace(/[^A-Za-z0-9._-]/g, "_") : "_folder"), ...from ? { baseSha: from.baseSha } : {} };
12609
12702
  const at2 = repoPaths(paths, repo);
12610
12703
  await mkdir5(at2.work, { recursive: true });
12611
12704
  await git3(at2, ["init", "--quiet", "--bare", at2.git], { noDirs: true });
@@ -12616,7 +12709,8 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12616
12709
  }
12617
12710
  if (!repos.length) throw new Ended("failed", "The task did not run: no repository in the folder has a commit to start from.");
12618
12711
  await writeFile5(manifest, JSON.stringify(repos));
12619
- hooks.log(`Copied ${repos.length} repositories of ${basename12(folder)} for the agent at their last commits; what you have not committed there is not in the task, and your own copies stay as they are.`);
12712
+ if (goingOn.length) hooks.log(`Went on from ${work.branch} in ${goingOn.length} of the ${repos.length} repositories of ${basename12(folder)}, where the request left it; the others start at their last commits.`);
12713
+ else hooks.log(`Copied ${repos.length} repositories of ${basename12(folder)} for the agent at their last commits; what you have not committed there is not in the task, and your own copies stay as they are.`);
12620
12714
  return repos;
12621
12715
  }
12622
12716
  async function deliverRepos(task, work, folder, paths, repos, result, hooks) {
@@ -12638,14 +12732,25 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
12638
12732
  const tree = (await git3(at2, ["write-tree"])).trim();
12639
12733
  const commit = (await git3(at2, ["commit-tree", tree, "-p", repo.head, "-m", task.title], { extraEnv: { GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: email } })).trim();
12640
12734
  if (!await hooks.leaseHeld()) throw new Ended("interrupted", "This machine no longer holds the task, so its change was not pushed.");
12641
- await git3(paths, ["-C", own, "fetch", "--quiet", "--no-tags", at2.git, `${commit}:refs/heads/${work.branch}`], { noDirs: true, ...result.stopped ? {} : { signal: hooks.signal }, extraEnv: { GIT_ALLOW_PROTOCOL: "file" } });
12642
- const origin = withoutCredential((await git3(paths, ["-C", own, "config", "--get", "remote.origin.url"], { noDirs: true }).catch(() => "")).trim());
12643
12735
  const label = repo.path || basename12(folder);
12736
+ const refused = await git3(paths, ["-C", own, "fetch", "--quiet", "--no-tags", at2.git, `${commit}:refs/heads/${work.branch}`], { noDirs: true, ...result.stopped ? {} : { signal: hooks.signal }, extraEnv: { GIT_ALLOW_PROTOCOL: "file" } }).then(
12737
+ () => null,
12738
+ (error) => {
12739
+ if (!result.stopped) stopped(hooks);
12740
+ return error.message;
12741
+ }
12742
+ );
12743
+ if (refused) {
12744
+ hooks.log(`${label}: the change was not written to ${work.branch} in your repository (${refused}); it is left out of this task.`);
12745
+ continue;
12746
+ }
12747
+ const origin = withoutCredential((await git3(paths, ["-C", own, "config", "--get", "remote.origin.url"], { noDirs: true }).catch(() => "")).trim());
12644
12748
  const target = origin ? (await git3(paths, ["-C", own, "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], { noDirs: true }).catch(() => "")).trim().replace(/^origin\//, "") || null : null;
12645
12749
  if (origin && !target) hooks.log(`${label} does not say which branch its origin's default is, so its request has no target; git remote set-head origin -a in it names one.`);
12646
12750
  hooks.log(origin ? `The branch ${work.branch} of ${label} is in your repository; this machine pushes nothing to its origin, so the push is yours.` : `${label} has no remote; its branch ${work.branch} is in your repository.`);
12647
- delivered.push({ path: repo.path, branch: work.branch, head: commit, baseSha: repo.head, origin, target, request: { title: task.title, body }, pushed: false });
12751
+ delivered.push({ path: repo.path, branch: work.branch, head: commit, baseSha: repo.baseSha ?? repo.head, origin, target, request: { title: task.title, body }, pushed: false });
12648
12752
  }
12753
+ if (!delivered.length) throw new Ended("failed", "No repository's change could be written to its task branch, so there is nothing to review; the log says why for each.");
12649
12754
  if (result.stopped) hooks.log(keptAfterStop(result.stopped));
12650
12755
  return { status: "needs-review", error: result.stopped ?? null, nativeSessionId: result.nativeSessionId, branch: null, position: null, request: null, repos: delivered };
12651
12756
  }
@@ -12767,7 +12872,7 @@ After a repair round: ${again.summary.trim()}`;
12767
12872
  const result = await converse(session, hooks, work.limits.timeoutMs, stop, ownMcpTool(work.setup.mcpTools), ready2.masked, launched !== null);
12768
12873
  stopped(hooks);
12769
12874
  if (result.timedOut) throw new Ended("failed", `The agent ran past the task's ${Math.round(work.limits.timeoutMs / 6e4)} minutes and was stopped.`);
12770
- if (result.terminal?.status !== "completed") throw new Ended("failed", result.terminal?.failure?.message ?? "The agent stopped before it finished.");
12875
+ if (result.terminal?.status !== "completed") throw untilReset(work, result.terminal?.failure, result.terminal?.nativeSessionId ?? sessionId) ?? new Ended("failed", result.terminal?.failure?.message ?? "The agent stopped before it finished.");
12771
12876
  return { summary: result.terminal.summary, nativeSessionId: result.terminal.nativeSessionId ?? sessionId };
12772
12877
  }
12773
12878
  async function servedTurn(work, adapter, paths, ready2, hooks, prompt) {
@@ -12863,6 +12968,10 @@ function withoutCredential(remote) {
12863
12968
  }
12864
12969
  }
12865
12970
  var repoPaths = (paths, repo) => ({ ...paths, work: repo.path ? join33(paths.work, repo.path) : paths.work, git: repo.git });
12971
+ function untilReset(work, failure2, nativeSessionId) {
12972
+ if (failure2?.class !== "usage_limit" || !failure2.resetAt || !nativeSessionId || "folder" in work) return null;
12973
+ return new Ended("interrupted", failure2.message, { nativeSessionId, limitResetAt: failure2.resetAt });
12974
+ }
12866
12975
  function stoppedByPerson(hooks) {
12867
12976
  return hooks.signal.aborted && hooks.signal.reason instanceof Error && hooks.signal.reason.message === STOPPED;
12868
12977
  }