@codyn06/cboard 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.
@@ -2,13 +2,15 @@
2
2
  // Connects a repository to a cboard project. Normally run as `npx @codyn06/cboard connect`; from a
3
3
  // cboard checkout (development) run this file directly, inside the target repo (or pass --repo):
4
4
  // node <cboard>/scripts/cboard-connect.js --project <uuid> [--server <https url>]
5
- // [--repo <path>] [--no-hooks] [--no-agents] [--no-skill] [--strict] [--codex]
5
+ // [--repo <path>] [--no-hooks] [--no-agents] [--no-skill] [--no-login] [--strict] [--codex] [--goal "<one line>"]
6
+ // [--reference <projectId> --name <name>]... [--remove-reference <name>]...
6
7
  // It writes `.cboard.json`, copies the dependency-free kit (scripts/cboard-kit) into `.cboard/`,
7
8
  // registers the `cboard` MCP server in `.mcp.json`, adds the SessionStart hooks to
8
9
  // `.claude/settings.json`, adds a marked block to AGENTS.md, installs the `cboard-graph` Claude Code
9
10
  // skill (`.claude/skills/cboard-graph/SKILL.md`), keeps the token file out of Git, and keeps the
10
11
  // generated files on LF line endings with a marked block in `.gitattributes`.
11
- // It never reads or prints a token. Rerunning with the same arguments changes nothing.
12
+ // Without a usable token it first runs the browser login (device flow; --project is then optional,
13
+ // the project is chosen in the browser) and saves the token it receives. It never prints a token. Rerunning with the same arguments changes nothing.
12
14
  //
13
15
  // Merge policy for an existing `mcpServers.cboard` entry in `.mcp.json`: other servers, other keys
14
16
  // and key order are untouched. Extra keys a user added to the cboard entry are kept. `type` is set
@@ -19,6 +21,7 @@ import { execFileSync } from "node:child_process";
19
21
  import { createHash } from "node:crypto";
20
22
  import {
21
23
  existsSync,
24
+ rmSync,
22
25
  renameSync,
23
26
  mkdirSync,
24
27
  readFileSync,
@@ -28,6 +31,9 @@ import {
28
31
  } from "node:fs";
29
32
  import { dirname, join, relative, resolve } from "node:path";
30
33
  import { fileURLToPath } from "node:url";
34
+ import { McpError, mcpCall } from "./cboard-kit/mcp.js";
35
+ import { DeviceError, deviceLogin, openBrowser } from "./cboard-kit/device.js";
36
+ import { retryWake } from "./cboard-kit/wait.js";
31
37
  import { parseArgs } from "node:util";
32
38
  import {
33
39
  CONFIG_FILE,
@@ -37,12 +43,21 @@ import {
37
43
  DEFAULT_TOKEN_FILE,
38
44
  ConfigError,
39
45
  isStaleSyncCommand,
46
+ pinSyncCommand,
40
47
  isLocalHost,
41
48
  isLocalOrHttps,
49
+ isTrustedServer,
50
+ REFERENCE_NAME,
42
51
  readConfigFile,
52
+ readToken,
53
+ referenceServer,
54
+ referenceTokenFile,
55
+ resolveConfig,
56
+ tokenFix,
43
57
  validateRepoPath,
44
58
  validateTokenEnv,
45
59
  } from "./cboard-kit/config.js";
60
+ import { CACHE_FILE } from "./cboard-kit/drift.js";
46
61
 
47
62
  // The kit sits beside this file in both layouts: scripts/cboard-kit in a cboard checkout and
48
63
  // kit/cboard-kit in the installed @codyn06/cboard package (copied by packages/code-context/scripts/build-kit.js).
@@ -67,7 +82,15 @@ export function kitVersion() {
67
82
  }
68
83
  return "unknown";
69
84
  }
70
- export const KIT_FILES = ["config.js", "mcp.js", "headers.js", "connect-check.js", "brief.js"];
85
+ export const KIT_FILES = [
86
+ "config.js",
87
+ "mcp.js",
88
+ "headers.js",
89
+ "connect-check.js",
90
+ "brief.js",
91
+ "drift.js",
92
+ "references.js",
93
+ ];
71
94
  export const KIT_DIR = ".cboard";
72
95
  export const SKILL_PATH = ".claude/skills/cboard-graph/SKILL.md";
73
96
  export const BLOCK_START = "<!-- cboard:start -->";
@@ -89,7 +112,8 @@ const ATTR_LINES = [
89
112
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
90
113
  // Generated forms of the cboard MCP entry; anything else is treated as user-edited.
91
114
  const GENERATED_URL = /^\$\{CBOARD_GRAPH_URL:-[^}]*\}\/mcp$/;
92
- const GENERATED_HELPER = /^node (\.cboard\/headers\.js|scripts\/graph-up\.js --headers)$/;
115
+ const GENERATED_HELPER =
116
+ /^node (\.cboard\/headers\.js|scripts\/graph-up\.js --headers|scripts\/cboard-kit\/headers\.js)( [a-z0-9-]+)?$/;
93
117
 
94
118
  export class ConnectError extends Error {
95
119
  constructor(message) {
@@ -140,8 +164,19 @@ function git(repo, args) {
140
164
  }
141
165
  }
142
166
 
167
+ function serverOrigin(input) {
168
+ try {
169
+ const url = new URL(String(input));
170
+ if (!isLocalOrHttps(url)) throw new Error("scheme");
171
+ return url.origin;
172
+ } catch {
173
+ throw new ConnectError(`--server must be an https URL (got "${String(input)}")`);
174
+ }
175
+ }
176
+
143
177
  /**
144
178
  * @param {{ repo?: string, project?: string, server?: string, hooks?: boolean, agents?: boolean, skill?: boolean,
179
+ * references?: { name: string, projectId: string, tokenFile?: string }[], removeReferences?: string[],
145
180
  * strict?: boolean, codex?: boolean, env?: Record<string, string | undefined> }} options
146
181
  * @returns {{ code: number, changed: string[], warnings: string[], lines: string[] }}
147
182
  */
@@ -183,21 +218,29 @@ export function connect(options = {}) {
183
218
  : `--project <uuid> is required: ${CONFIG_FILE} does not name a project yet`,
184
219
  );
185
220
  }
186
- const serverInput = options.server ?? existing?.server ?? DEFAULT_SERVER;
187
- let server;
188
- try {
189
- const url = new URL(String(serverInput));
190
- if (!isLocalOrHttps(url)) throw new Error("scheme");
191
- server = url.origin;
192
- } catch {
193
- throw new ConnectError(`--server must be an https URL (got "${String(serverInput)}")`);
194
- }
221
+ const server = serverOrigin(options.server ?? existing?.server ?? DEFAULT_SERVER);
195
222
  const config = {
196
223
  server,
197
224
  projectId,
198
225
  tokenFile: existing?.tokenFile ?? DEFAULT_TOKEN_FILE,
199
226
  tokenEnv: existing?.tokenEnv ?? DEFAULT_TOKEN_ENV,
200
227
  };
228
+ // A stable identity for clones without an origin remote: the (sorted-first) root commit.
229
+ if (typeof existing?.repoId !== "string") {
230
+ try {
231
+ const roots = execFileSync("git", ["rev-list", "--max-parents=0", "HEAD"], {
232
+ cwd: repo,
233
+ encoding: "utf8",
234
+ stdio: ["ignore", "pipe", "ignore"],
235
+ })
236
+ .split("\n")
237
+ .filter(Boolean)
238
+ .sort();
239
+ if (roots[0]) config.repoId = roots[0];
240
+ } catch {
241
+ // Not a git repository, or no commits yet: a later connect adds it.
242
+ }
243
+ }
201
244
  for (const [key, value] of Object.entries(existing ?? {}))
202
245
  if (!(key in config) && !(key === "syncCommand" && isStaleSyncCommand(value)))
203
246
  config[key] = value;
@@ -210,6 +253,42 @@ export function connect(options = {}) {
210
253
  } catch (error) {
211
254
  throw new ConnectError(error instanceof Error ? error.message : String(error));
212
255
  }
256
+ // Reference projects (read-only): --reference/--name add or update one, --remove-reference drops one.
257
+ let references = Array.isArray(existing?.references) ? [...existing.references] : [];
258
+ const removedReferences = [];
259
+ for (const name of options.removeReferences ?? []) {
260
+ if (references.some((r) => r?.name === name)) removedReferences.push(name);
261
+ else warnings.push(`no reference named ${name} to remove`);
262
+ references = references.filter((r) => r?.name !== name);
263
+ }
264
+ for (const want of options.references ?? []) {
265
+ const old = references.find((r) => r?.name === want.name);
266
+ const next = {
267
+ name: want.name,
268
+ projectId: want.projectId,
269
+ tokenFile: want.tokenFile ?? old?.tokenFile ?? referenceTokenFile(want.name),
270
+ };
271
+ references = old ? references.map((r) => (r === old ? next : r)) : [...references, next];
272
+ }
273
+ for (const ref of references) {
274
+ if (
275
+ !isObject(ref) ||
276
+ !REFERENCE_NAME.test(String(ref.name)) ||
277
+ !UUID.test(String(ref.projectId)) ||
278
+ typeof ref.tokenFile !== "string"
279
+ ) {
280
+ throw new ConnectError(
281
+ `a reference needs a name (lowercase letters, digits, hyphens), a project UUID and a token file (got ${JSON.stringify(ref)})`,
282
+ );
283
+ }
284
+ try {
285
+ validateRepoPath(repo, ref.tokenFile, `references.${ref.name}.tokenFile`);
286
+ } catch (error) {
287
+ throw new ConnectError(error instanceof Error ? error.message : String(error));
288
+ }
289
+ }
290
+ if (references.length) config.references = references;
291
+ else delete config.references;
213
292
  // Parse the files we merge before writing anything, so a broken file aborts with no changes.
214
293
  const mcpFile = join(repo, ".mcp.json");
215
294
  const mcp = readJson(mcpFile) ?? {};
@@ -238,32 +317,43 @@ export function connect(options = {}) {
238
317
  // 3. .mcp.json
239
318
  const before = JSON.stringify(mcp);
240
319
  if (!isObject(mcp.mcpServers)) mcp.mcpServers = {};
241
- const entry = isObject(mcp.mcpServers.cboard) ? mcp.mcpServers.cboard : {};
242
320
  const desiredUrl = `\${CBOARD_GRAPH_URL:-${server}}/mcp`;
243
- if (!("type" in entry)) entry.type = "http";
244
- const setGenerated = (key, value, mayOverwrite) => {
245
- if (!(key in entry) || entry[key] === value) {
246
- entry[key] = value;
247
- } else if (mayOverwrite(entry[key])) {
248
- entry[key] = value;
249
- } else {
250
- warnings.push(
251
- `kept your edited mcpServers.cboard.${key} in .mcp.json (${String(entry[key])})`,
252
- );
253
- }
321
+ const mergeEntry = (serverName, helperCommand) => {
322
+ const entry = isObject(mcp.mcpServers[serverName]) ? mcp.mcpServers[serverName] : {};
323
+ if (!("type" in entry)) entry.type = "http";
324
+ const setGenerated = (key, value, mayOverwrite) => {
325
+ if (!(key in entry) || entry[key] === value) {
326
+ entry[key] = value;
327
+ } else if (mayOverwrite(entry[key])) {
328
+ entry[key] = value;
329
+ } else {
330
+ warnings.push(
331
+ `kept your edited mcpServers.${serverName}.${key} in .mcp.json (${String(entry[key])})`,
332
+ );
333
+ }
334
+ };
335
+ setGenerated(
336
+ "url",
337
+ desiredUrl,
338
+ (current) =>
339
+ options.server !== undefined ||
340
+ (typeof current === "string" && GENERATED_URL.test(current)),
341
+ );
342
+ setGenerated(
343
+ "headersHelper",
344
+ helperCommand,
345
+ (current) => typeof current === "string" && GENERATED_HELPER.test(current),
346
+ );
347
+ mcp.mcpServers[serverName] = entry;
254
348
  };
255
- setGenerated(
256
- "url",
257
- desiredUrl,
258
- (current) =>
259
- options.server !== undefined || (typeof current === "string" && GENERATED_URL.test(current)),
260
- );
261
- setGenerated(
262
- "headersHelper",
263
- headersCommand,
264
- (current) => typeof current === "string" && GENERATED_HELPER.test(current),
265
- );
266
- mcp.mcpServers.cboard = entry;
349
+ mergeEntry("cboard", headersCommand);
350
+ // One read-only MCP server per reference project; its helper sends that reference's own token.
351
+ for (const ref of references) {
352
+ const helper = self ? "node scripts/cboard-kit/headers.js" : `node ${KIT_DIR}/headers.js`;
353
+ mergeEntry(referenceServer(ref.name), `${helper} ${ref.name}`);
354
+ }
355
+ for (const name of removedReferences)
356
+ Reflect.deleteProperty(mcp.mcpServers, referenceServer(name));
267
357
  if (JSON.stringify(mcp) !== before) put(mcpFile, json(mcp));
268
358
 
269
359
  // 4. .claude/settings.json
@@ -272,8 +362,12 @@ export function connect(options = {}) {
272
362
  const enabled = Array.isArray(settings.enabledMcpjsonServers)
273
363
  ? settings.enabledMcpjsonServers
274
364
  : [];
275
- if (!enabled.includes("cboard")) enabled.push("cboard");
276
- settings.enabledMcpjsonServers = enabled;
365
+ for (const name of ["cboard", ...references.map((r) => referenceServer(r.name))]) {
366
+ if (!enabled.includes(name)) enabled.push(name);
367
+ }
368
+ settings.enabledMcpjsonServers = enabled.filter(
369
+ (name) => !removedReferences.some((r) => name === referenceServer(r)),
370
+ );
277
371
  if (!isObject(settings.hooks)) settings.hooks = {};
278
372
  const groups = Array.isArray(settings.hooks.SessionStart) ? settings.hooks.SessionStart : [];
279
373
  settings.hooks.SessionStart = groups;
@@ -295,7 +389,10 @@ export function connect(options = {}) {
295
389
 
296
390
  // 5. AGENTS.md
297
391
  if (options.agents !== false) {
298
- const syncCommand = String(config.syncCommand ?? DEFAULT_SYNC_COMMAND);
392
+ const syncCommand = pinSyncCommand(
393
+ String(config.syncCommand ?? DEFAULT_SYNC_COMMAND),
394
+ kitVersion(),
395
+ );
299
396
  const blockLines = [
300
397
  "## cboard graph (generated by cboard-connect)",
301
398
  "",
@@ -319,6 +416,18 @@ export function connect(options = {}) {
319
416
  " items, duplicate active handoffs). Claude Code prompts: `/mcp__cboard__orient`,",
320
417
  " `/mcp__cboard__record`. Older servers may lack these; the rules above still apply.",
321
418
  "",
419
+ "Empty project? `.cboard.json` may name a `goalNodeId`: the project goal (a `requirement` node). Link the first",
420
+ "decisions to it with `answers`, then create the first `status_update`. No goal yet: ask the owner for one line and",
421
+ `run \`${syncCommand} connect --goal "<text>"\`.`,
422
+ "",
423
+ ...(references.length
424
+ ? [
425
+ `Reference projects (${references.map((r) => `\`${r.name}\``).join(", ")}) are READ-ONLY. Query them with the`,
426
+ `\`cboard-ref-<name>\` MCP tools (\`project_id\` from \`references\` in \`${CONFIG_FILE}\`) and never call`,
427
+ "`submit_contribution` there; record what you learn in this project's graph instead.",
428
+ "",
429
+ ]
430
+ : []),
322
431
  "Keep code nodes current: run the sync below when the session brief says they lag HEAD.",
323
432
  "",
324
433
  "```sh",
@@ -394,6 +503,24 @@ export function connect(options = {}) {
394
503
  );
395
504
  }
396
505
  }
506
+ // The brief's npm-latest cache and last-good-brief cache live in the kit directory; keep both out of Git too.
507
+ // Reference token files stay out of Git too.
508
+ for (const cacheRel of [
509
+ `${KIT_DIR}/${CACHE_FILE}`,
510
+ `${KIT_DIR}/brief-cache.json`,
511
+ ...references.map((r) => r.tokenFile.replaceAll("\\", "/")),
512
+ ]) {
513
+ if (git(repo, ["check-ignore", "-q", "--", cacheRel]) !== null) continue;
514
+ const gitignore = join(repo, ".gitignore");
515
+ const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
516
+ if (text.split(/\r?\n/).some((l) => l.trim() === cacheRel || l.trim() === `/${cacheRel}`))
517
+ continue;
518
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
519
+ put(
520
+ gitignore,
521
+ `${text === "" || text.endsWith("\n") ? text : `${text}${eol}`}${cacheRel}${eol}`,
522
+ );
523
+ }
397
524
  const tracked = git(repo, ["ls-files", "--", tokenRel]);
398
525
  if (tracked && tracked.trim() !== "") {
399
526
  warnings.push(
@@ -410,8 +537,21 @@ export function connect(options = {}) {
410
537
  );
411
538
  if (!env[config.tokenEnv] && !existsSync(tokenFile)) {
412
539
  lines.push(
413
- `No token yet. In the cboard web app press "Agent tokens" in the project header (scopes graph:read, ` +
414
- `graph:contribute, graph:context), then save it to ${tokenRel} or export ${config.tokenEnv}.`,
540
+ `No token yet. In the cboard web app press "Agent tokens" in the project header; members choose graph:read, ` +
541
+ `graph:contribute, graph:context; viewers are read-only (graph:read only)), then save it to ${tokenRel} or export ${config.tokenEnv}.`,
542
+ );
543
+ }
544
+ for (const ref of references) {
545
+ if (!existsSync(join(repo, ref.tokenFile))) {
546
+ lines.push(
547
+ `Reference ${ref.name}: no token yet. Ask the owner of project ${ref.projectId} to add you as a member, create a ` +
548
+ `graph:read token there and save it to ${ref.tokenFile} (read-only; never use a token that can write).`,
549
+ );
550
+ }
551
+ }
552
+ for (const name of removedReferences) {
553
+ lines.push(
554
+ `Reference ${name} removed. Its token file is left in place; delete it if you no longer need it.`,
415
555
  );
416
556
  }
417
557
  if (server !== DEFAULT_SERVER && !isLocalHost(new URL(server))) {
@@ -423,7 +563,7 @@ export function connect(options = {}) {
423
563
  lines.push(
424
564
  "",
425
565
  "Sync code nodes:",
426
- ` ${String(config.syncCommand ?? DEFAULT_SYNC_COMMAND)} sync`,
566
+ ` ${pinSyncCommand(String(config.syncCommand ?? DEFAULT_SYNC_COMMAND), kitVersion())} sync`,
427
567
  );
428
568
  if (suggestions.length) lines.push(...suggestions);
429
569
  if (options.codex) {
@@ -446,7 +586,219 @@ export function connect(options = {}) {
446
586
  };
447
587
  }
448
588
 
449
- function main() {
589
+ /** False when this repository has no token or the server rejects it; a network failure is not a rejection. */
590
+ async function tokenUsable({ repo, env, server, tokenRel, fetchImpl }) {
591
+ let config;
592
+ try {
593
+ // CBOARD_GRAPH_URL stands in for the target server; the trust check below replaces resolveConfig's.
594
+ config = resolveConfig({ ...env, CBOARD_GRAPH_URL: server }, repo);
595
+ } catch {
596
+ return true; // connect() reports the configuration problem as it always did.
597
+ }
598
+ const token =
599
+ readToken(config, env) || readToken({ ...config, tokenFile: join(repo, tokenRel) }, env);
600
+ if (!token) return false;
601
+ // Never send a token to a server the user has not trusted; assume it works.
602
+ if (config.hosted && !isTrustedServer(server, { ...env, CBOARD_GRAPH_URL: undefined })) {
603
+ return true;
604
+ }
605
+ try {
606
+ await retryWake(
607
+ (attemptMs) =>
608
+ mcpCall({
609
+ api: config.api,
610
+ token,
611
+ name: "list_projects",
612
+ timeoutMs: config.hosted ? attemptMs : 5000,
613
+ ...(fetchImpl ? { fetchImpl } : {}),
614
+ }),
615
+ { budgetMs: config.hosted ? 60_000 : 0 },
616
+ );
617
+ } catch (error) {
618
+ return !(error instanceof McpError && error.kind === "unauthorized");
619
+ }
620
+ return true;
621
+ }
622
+
623
+ /**
624
+ * `connect`, preceded by the browser (device) login when the repository has no usable token.
625
+ * The token is written to the repository's token file before `connect` runs, so `connect` keeps it
626
+ * out of Git. `login` injects the network, browser and clock for tests.
627
+ * `noLogin` skips the token check and the login (the pre-login behaviour).
628
+ * @param {Parameters<typeof connect>[0] & { noLogin?: boolean, login?: { fetchImpl?: typeof fetch,
629
+ * open?: ((url: string) => void) | null, sleep?: (ms: number) => Promise<void>,
630
+ * now?: () => number, print?: (line: string) => void, interactive?: boolean } }} options
631
+ */
632
+ export async function connectWithLogin(options = {}) {
633
+ const env = options.env ?? process.env;
634
+ const repo = resolve(options.repo ?? process.cwd());
635
+ const { login = {}, noLogin = false, ...rest } = options;
636
+ // Removing a reference needs no token, so it never starts a login.
637
+ if (
638
+ noLogin ||
639
+ options.removeReferences?.length ||
640
+ !existsSync(repo) ||
641
+ !statSync(repo).isDirectory()
642
+ )
643
+ return connect(rest);
644
+ let existing;
645
+ try {
646
+ existing = readConfigFile(repo) ?? undefined;
647
+ } catch (error) {
648
+ throw new ConnectError(error instanceof ConfigError ? error.message : String(error));
649
+ }
650
+ const server = serverOrigin(options.server ?? existing?.server ?? DEFAULT_SERVER);
651
+ const tokenRel =
652
+ typeof existing?.tokenFile === "string" ? existing.tokenFile : DEFAULT_TOKEN_FILE;
653
+ try {
654
+ validateRepoPath(repo, tokenRel, "tokenFile");
655
+ } catch (error) {
656
+ throw new ConnectError(error instanceof Error ? error.message : String(error));
657
+ }
658
+ if (await tokenUsable({ repo, env, server, tokenRel, fetchImpl: login.fetchImpl })) {
659
+ return connect(rest);
660
+ }
661
+ const interactive = login.interactive ?? (Boolean(process.stdout.isTTY) && !env.CI);
662
+ const granted = await deviceLogin({
663
+ server,
664
+ ...(login.fetchImpl ? { fetchImpl: login.fetchImpl } : {}),
665
+ ...(login.sleep ? { sleep: login.sleep } : {}),
666
+ ...(login.now ? { now: login.now } : {}),
667
+ ...(login.print ? { print: login.print } : {}),
668
+ open: login.open === undefined ? (interactive ? openBrowser : null) : login.open,
669
+ wakeBudgetMs: isLocalHost(new URL(server)) ? 0 : 60_000,
670
+ });
671
+ const tokenFile = join(repo, tokenRel);
672
+ mkdirSync(dirname(tokenFile), { recursive: true });
673
+ writeFileSync(tokenFile, `${granted.token}\n`, { mode: 0o600 });
674
+ let result;
675
+ try {
676
+ result = connect({ ...rest, project: granted.projectId });
677
+ } catch (error) {
678
+ // connect() adds the token path to .gitignore; if it fails first, do not leave a live token unignored.
679
+ rmSync(tokenFile, { force: true });
680
+ throw error;
681
+ }
682
+ if (options.project && options.project !== granted.projectId) {
683
+ result.warnings.push(
684
+ `you approved project ${granted.projectId} in the browser, not the --project ${options.project} you passed`,
685
+ );
686
+ }
687
+ return {
688
+ ...result,
689
+ lines: [
690
+ `Logged in: token saved to ${tokenRel.replaceAll("\\", "/")} (not shown), project ${granted.projectId}.`,
691
+ ...result.lines,
692
+ ],
693
+ };
694
+ }
695
+
696
+ export const GOAL_KEY = "cboard:project-goal";
697
+
698
+ /**
699
+ * Creates or revises the project's goal: one `requirement` node (client key `cboard:project-goal`,
700
+ * property `cboardGoal`), remembered as `goalNodeId` in .cboard.json. The same text changes nothing;
701
+ * a different text revises the node. Needs a token with graph:read and graph:contribute.
702
+ * @returns {Promise<{ action: "created" | "revised" | "unchanged", nodeId: string }>}
703
+ */
704
+ export async function setGoal({ repo, goal, env = process.env, fetchImpl }) {
705
+ const title = String(goal).replace(/\s+/g, " ").trim();
706
+ if (!title || title.length > 300) {
707
+ throw new ConnectError("--goal must be a one-line text of 1 to 300 characters");
708
+ }
709
+ let config;
710
+ try {
711
+ config = resolveConfig(env, repo, { required: true });
712
+ } catch (error) {
713
+ throw new ConnectError(error instanceof Error ? error.message : String(error));
714
+ }
715
+ const token = readToken(config, env);
716
+ if (!token || !config.projectId) {
717
+ throw new ConnectError(
718
+ `--goal needs a token (${tokenFix(config)}) and a project in ${CONFIG_FILE}`,
719
+ );
720
+ }
721
+ const call = (name, args) =>
722
+ mcpCall({
723
+ api: config.api,
724
+ token,
725
+ name,
726
+ args,
727
+ timeoutMs: 60_000,
728
+ ...(fetchImpl ? { fetchImpl } : {}),
729
+ });
730
+ const project_id = config.projectId;
731
+ try {
732
+ let node = null;
733
+ if (config.goalNodeId) {
734
+ node =
735
+ (await call("get_graph_node", { project_id, node_id: config.goalNodeId })).data?.node ??
736
+ null;
737
+ }
738
+ if (!node) {
739
+ const found = await call("query_graph", { project_id, types: ["requirement"], limit: 50 });
740
+ node = (found.data?.nodes ?? []).find((n) => n.properties?.cboardGoal === true) ?? null;
741
+ }
742
+ const stamp = createHash("sha256").update(title).digest("hex").slice(0, 12);
743
+ const contributionId = `cboard-goal-${stamp}-${Date.now().toString(36)}`;
744
+ const provenance = [{ kind: "contribution", ref: contributionId }];
745
+ let action = "unchanged";
746
+ let nodeId = node?.id;
747
+ if (!node) {
748
+ const receipt = (
749
+ await call("submit_contribution", {
750
+ project_id,
751
+ contribution: {
752
+ contributionId,
753
+ summary: "Set the project goal",
754
+ nodes: [
755
+ {
756
+ ref: "goal",
757
+ clientKey: GOAL_KEY,
758
+ type: "requirement",
759
+ title,
760
+ body: "Project goal, set with `cboard connect --goal`.",
761
+ status: "req",
762
+ properties: { cboardGoal: true },
763
+ provenance,
764
+ },
765
+ ],
766
+ },
767
+ })
768
+ ).data;
769
+ if (receipt?.status !== "applied" || !receipt.nodeIds?.[0]) {
770
+ throw new Error("the server returned the goal contribution");
771
+ }
772
+ action = "created";
773
+ nodeId = receipt.nodeIds[0];
774
+ } else if (node.title !== title) {
775
+ const receipt = (
776
+ await call("submit_contribution", {
777
+ project_id,
778
+ contribution: {
779
+ contributionId,
780
+ summary: "Revise the project goal",
781
+ revisions: [{ nodeId: node.id, expectedRevision: node.revision, title, provenance }],
782
+ },
783
+ })
784
+ ).data;
785
+ if (receipt?.status !== "applied") throw new Error("the server returned the goal revision");
786
+ action = "revised";
787
+ }
788
+ if (config.goalNodeId !== nodeId) {
789
+ const file = readConfigFile(repo) ?? {};
790
+ writeFileSync(join(repo, CONFIG_FILE), json({ ...file, goalNodeId: nodeId }));
791
+ }
792
+ return { action, nodeId };
793
+ } catch (error) {
794
+ if (error instanceof ConnectError) throw error;
795
+ throw new ConnectError(
796
+ `could not set the goal (${error instanceof Error ? error.message : String(error)}); the token needs graph:read and graph:contribute`,
797
+ );
798
+ }
799
+ }
800
+
801
+ async function main() {
450
802
  let values;
451
803
  try {
452
804
  ({ values } = parseArgs({
@@ -457,34 +809,61 @@ function main() {
457
809
  "no-hooks": { type: "boolean", default: false },
458
810
  "no-agents": { type: "boolean", default: false },
459
811
  "no-skill": { type: "boolean", default: false },
812
+ "no-login": { type: "boolean", default: false },
460
813
  strict: { type: "boolean", default: false },
461
814
  codex: { type: "boolean", default: false },
815
+ goal: { type: "string" },
816
+ reference: { type: "string", multiple: true },
817
+ name: { type: "string", multiple: true },
818
+ "remove-reference": { type: "string", multiple: true },
462
819
  },
463
820
  }));
464
821
  } catch (error) {
465
822
  console.error(`cboard-connect: ${error instanceof Error ? error.message : String(error)}`);
466
823
  process.exit(2);
467
824
  }
825
+ const referenceIds = values.reference ?? [];
826
+ const referenceNames = values.name ?? [];
827
+ if (referenceIds.length !== referenceNames.length) {
828
+ console.error("cboard-connect: each --reference <projectId> needs a matching --name <name>");
829
+ process.exit(2);
830
+ }
468
831
  try {
469
- const result = connect({
832
+ const result = await connectWithLogin({
833
+ references: referenceIds.map((projectId, i) => ({
834
+ projectId,
835
+ name: referenceNames[i],
836
+ })),
837
+ removeReferences: values["remove-reference"] ?? [],
470
838
  ...(values.repo ? { repo: values.repo } : {}),
471
839
  ...(values.project ? { project: values.project } : {}),
472
840
  ...(values.server ? { server: values.server } : {}),
473
841
  hooks: !values["no-hooks"],
474
842
  agents: !values["no-agents"],
475
843
  skill: !values["no-skill"],
844
+ noLogin: values["no-login"],
476
845
  strict: values.strict,
477
846
  codex: values.codex,
478
847
  });
479
848
  for (const line of result.lines) console.log(line);
849
+ if (values.goal !== undefined) {
850
+ const goal = await setGoal({
851
+ repo: resolve(values.repo ?? process.cwd()),
852
+ goal: values.goal,
853
+ });
854
+ console.log(`Goal ${goal.action}: requirement node ${goal.nodeId}`);
855
+ }
480
856
  for (const warning of result.warnings) console.error(`cboard-connect: warning: ${warning}`);
481
857
  process.exitCode = result.code;
482
858
  } catch (error) {
483
859
  if (error instanceof ConnectError) {
484
860
  console.error(`cboard-connect: ${error.message}`);
485
861
  process.exitCode = 2;
862
+ } else if (error instanceof DeviceError) {
863
+ console.error(`cboard-connect: ${error.message}`);
864
+ process.exitCode = 1;
486
865
  } else throw error;
487
866
  }
488
867
  }
489
868
 
490
- if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
869
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();