@cbartens/bkit 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.bkit/README.md +12 -16
  2. package/.bkit/core/.agents/rules.md +57 -57
  3. package/.bkit/core/.bkit/README.md +11 -15
  4. package/.bkit/core/.bkit/cloud.md +22 -30
  5. package/.bkit/core/.bkit/comparison.md +36 -28
  6. package/.bkit/core/.bkit/install.md +55 -150
  7. package/.bkit/core/.bkit/jsonl.md +5 -5
  8. package/.bkit/core/.bkit/providers.md +6 -3
  9. package/.bkit/core/.bkit/templates.md +9 -7
  10. package/.bkit/core/.bkit/trackers.md +1 -1
  11. package/.bkit/core/.bkit/workflows.md +7 -3
  12. package/.bkit/core/engine/checks/after/auth.ts +16 -114
  13. package/.bkit/core/engine/checks/after/ci-yml.ts +36 -74
  14. package/.bkit/core/engine/checks/after/github.ts +1 -1
  15. package/.bkit/core/engine/checks/after/index.ts +158 -184
  16. package/.bkit/core/engine/checks/after/suppression.ts +53 -0
  17. package/.bkit/core/engine/checks/before/env.ts +5 -19
  18. package/.bkit/core/engine/checks/before/files.ts +2 -0
  19. package/.bkit/core/engine/cli.ts +4 -8
  20. package/.bkit/core/engine/commands/install/doctor.ts +9 -2
  21. package/.bkit/core/engine/commands/install/install.ts +24 -2
  22. package/.bkit/core/engine/commands/install/uninstall.ts +56 -1
  23. package/.bkit/core/engine/commands/install/upgrade.ts +14 -3
  24. package/.bkit/core/engine/commands/lib.ts +4 -3
  25. package/.bkit/core/engine/install/cloud-env.ts +4 -2
  26. package/.bkit/core/engine/install/modules/cloud.ts +3 -4
  27. package/.bkit/core/engine/install/modules/core.ts +33 -13
  28. package/.bkit/core/engine/install/modules/opencode.ts +34 -13
  29. package/.bkit/core/engine/install/payload-links.ts +150 -0
  30. package/.bkit/core/engine/install/template-copies.ts +1 -1
  31. package/.bkit/core/engine/shared/egress.ts +1 -1
  32. package/.bkit/core/workflows/bkit-debug.md +19 -12
  33. package/.bkit/shared/.bkit/.env.example +43 -36
  34. package/.bkit/shared/.claude/bkit-cloud.md +1 -1
  35. package/.bkit/shared/.cursor/bkit-cloud.md +2 -2
  36. package/.bkit/shared/.opencode/opencode.json +3 -1
  37. package/.bkit/shared/docs/deployments.md +7 -10
  38. package/.bkit/shared/docs/security.md +1 -1
  39. package/.bkit/shared/gitignore +5 -0
  40. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +0 -5
  41. package/.bkit/templates/.cursor/Dockerfile +1 -1
  42. package/.bkit/templates/.cursor/environment.json +1 -1
  43. package/.bkit/templates/.github/renovate.json5 +0 -15
  44. package/.bkit/templates/.github/workflows/bkit-ci.yml +7 -24
  45. package/.bkit/templates/.github/workflows/bkit-cloud.yml +0 -2
  46. package/.bkit/templates/.github/workflows/bkit-renovate.yml +7 -10
  47. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +125 -12
  48. package/CHANGELOG.md +37 -0
  49. package/README.md +96 -38
  50. package/dist/checks/after/auth.js +16 -108
  51. package/dist/checks/after/ci-yml.js +30 -67
  52. package/dist/checks/after/github.js +1 -1
  53. package/dist/checks/after/index.js +138 -154
  54. package/dist/checks/after/suppression.js +39 -0
  55. package/dist/checks/before/env.js +5 -15
  56. package/dist/checks/before/files.js +2 -0
  57. package/dist/cli.js +4 -8
  58. package/dist/commands/install/doctor.js +4 -2
  59. package/dist/commands/install/install.js +16 -2
  60. package/dist/commands/install/uninstall.js +45 -1
  61. package/dist/commands/install/upgrade.js +14 -3
  62. package/dist/commands/lib.js +4 -3
  63. package/dist/install/cloud-env.js +4 -2
  64. package/dist/install/modules/cloud.js +3 -4
  65. package/dist/install/modules/core.js +33 -13
  66. package/dist/install/modules/opencode.js +34 -14
  67. package/dist/install/payload-links.js +119 -0
  68. package/dist/install/template-copies.js +1 -1
  69. package/dist/shared/egress.js +1 -1
  70. package/package.json +25 -3
  71. package/.bkit/core/engine/checks/after/vercel.ts +0 -101
  72. package/dist/checks/after/vercel.js +0 -102
@@ -18,6 +18,7 @@ import {
18
18
  formatChecklist,
19
19
  writeAdvisoriesArtifact,
20
20
  } from "../../checks/after/index.js";
21
+ import type { SuppressionNote } from "../../checks/after/suppression.js";
21
22
  import { parseDotenv } from "../../install/cloud-env.js";
22
23
 
23
24
  /**
@@ -126,7 +127,12 @@ export async function runDoctor(
126
127
  `${LOG_PREFIX} Payload roots: core=${getCoreRoot()} shared=${getSharedRoot()} templates=${getTemplatesRoot()}`,
127
128
  );
128
129
  const { blockers, advisories: preflightAdvisories } = runPreflight(modules, process.cwd());
129
- const allFindings = runPostInstallCheck([...preflightAdvisories, ...blockers], process.cwd());
130
+ const suppressed: SuppressionNote[] = [];
131
+ const allFindings = runPostInstallCheck(
132
+ [...preflightAdvisories, ...blockers],
133
+ process.cwd(),
134
+ suppressed,
135
+ );
130
136
  // Broken install: the opencode host is on disk but neither provider signal survives.
131
137
  // `bkit check` and `bkit upgrade` exit 1 with the fix; doctor reports it here and does
132
138
  // not enforce.
@@ -142,7 +148,7 @@ export async function runDoctor(
142
148
  }
143
149
  }
144
150
 
145
- const banner = formatChecklist(allFindings);
151
+ const banner = formatChecklist(allFindings, suppressed);
146
152
  if (banner) {
147
153
  console.log(banner);
148
154
  } else {
@@ -153,6 +159,7 @@ export async function runDoctor(
153
159
  mode: "doctor",
154
160
  version: getInstallingVersion(),
155
161
  logPrefix: LOG_PREFIX,
162
+ suppressed,
156
163
  });
157
164
 
158
165
  // opencode host diagnostics: report required tools and cred presence per provider.
@@ -23,6 +23,7 @@ import {
23
23
  runPostInstallCheck,
24
24
  writeAdvisoriesArtifact,
25
25
  } from "../../checks/after/index.js";
26
+ import type { SuppressionNote } from "../../checks/after/suppression.js";
26
27
  import { findMissingOwnedHooks, detectOwnedHookMissing } from "../../checks/after/managed.js";
27
28
  import { resolveTokens } from "../../install/placeholders.js";
28
29
  import {
@@ -339,6 +340,7 @@ export async function runInstall(
339
340
  const advisories: import("../../checks/before/index.js").PreflightFinding[] = [
340
341
  ...preflightAdvisories,
341
342
  ];
343
+
342
344
  const ws: WriteSet = { writes: [] };
343
345
  const postDispatch: Array<() => void> = [];
344
346
 
@@ -461,6 +463,24 @@ export async function runInstall(
461
463
  console.log(`${LOG_PREFIX} Done. ${totalWrites} write(s).`);
462
464
  }
463
465
 
466
+ // Phase 2 has completed its writes. Re-run Phase 1 detection and use its result for the
467
+ // post-install checklist, so the banner reflects the state on disk AFTER the writes.
468
+ // Otherwise a drift finding Phase 2 just resolved (tier2-json-drift, tier2-text-drift,
469
+ // bkit-version-pin-stale) is still reported as unresolved, contradicting the "Done"
470
+ // banner above. `check` (dryRun) wrote nothing, so its Phase 1 findings already describe
471
+ // the current state and are kept as-is. Module-accumulated advisories (pushed during
472
+ // dispatch) are preserved; only the Phase 1 seeds are replaced, in their original order.
473
+ if (!dryRun) {
474
+ const moduleAdvisories = advisories.slice(preflightAdvisories.length);
475
+ const { advisories: freshPreflightAdvisories } = runPreflight(
476
+ effectiveModules,
477
+ process.cwd(),
478
+ undefined,
479
+ issueTracker,
480
+ );
481
+ ctx.advisories = [...freshPreflightAdvisories, ...moduleAdvisories];
482
+ }
483
+
464
484
  // --- Phase 3: Post-install checks (re-detect + unified output) ---
465
485
  // Runs for both install AND check — detectors are read-only, so check produces
466
486
  // the same advisory set as install would emit against the same filesystem state.
@@ -475,19 +495,21 @@ export async function runInstall(
475
495
  } catch (err) {
476
496
  void err; // Non-fatal — changelog header is informational
477
497
  }
478
- const postFindings = runPostInstallCheck(ctx.advisories, process.cwd());
498
+ const suppressed: SuppressionNote[] = [];
499
+ const postFindings = runPostInstallCheck(ctx.advisories, process.cwd(), suppressed);
479
500
  // check only: install has just written every hook file of the modules it dispatched, and a
480
501
  // missing bkit-cloud-bootstrap.sh after `install --claude` is not that run's fault.
481
502
  const missingHooks = dryRun ? findMissingOwnedHooks(process.cwd(), effectiveModules) : [];
482
503
  const missingHooksFinding = detectOwnedHookMissing(missingHooks);
483
504
  if (missingHooksFinding) postFindings.push(missingHooksFinding);
484
- const banner = formatChecklist(postFindings);
505
+ const banner = formatChecklist(postFindings, suppressed);
485
506
  if (banner) console.log(banner);
486
507
  writeAdvisoriesArtifact(postFindings, {
487
508
  cwd: process.cwd(),
488
509
  mode: dryRun ? "check" : "install",
489
510
  version: getInstallingVersion(),
490
511
  logPrefix: LOG_PREFIX,
512
+ suppressed,
491
513
  });
492
514
 
493
515
  // Check mode: exit 1 on drift (see reportCheckDrift).
@@ -31,13 +31,19 @@ import {
31
31
  type ModuleName,
32
32
  type IssueTracker,
33
33
  } from "../../install/manifest.js";
34
- import { isConsumerModified, readBkitVersion } from "../../install/version-file.js";
34
+ import {
35
+ isConsumerModified,
36
+ mergeCanonicalHashes,
37
+ readBkitVersion,
38
+ writeBkitVersion,
39
+ } from "../../install/version-file.js";
35
40
  import {
36
41
  getPkgRoot,
37
42
  getSharedRoot,
38
43
  findTemplateSource,
39
44
  TEMPLATE_COPIES_DIR,
40
45
  } from "../../shared/package-roots.js";
46
+ import { PAYLOAD_LINKS } from "../../install/payload-links.js";
41
47
  import { removeOpencodeProviderBlock, renderOpencodeJson } from "../../install/modules/opencode.js";
42
48
  import {
43
49
  CLAUDE_CLOUD_RELPATH,
@@ -793,6 +799,28 @@ export async function runUninstall(
793
799
  }
794
800
  }
795
801
 
802
+ // Full/core uninstall: the payload view links (`.bkit/core`, `.bkit/shared`) are
803
+ // bkit-created symlinks into the package and go with it. Symlinks ONLY — a real
804
+ // directory or file at that path is consumer content (install's no-clobber guard)
805
+ // and stays. Never in dogfood, where `.bkit/core` is bkit's own source.
806
+ if (moduleList.includes("core") && path.resolve(ctx.cwd) !== getPkgRoot()) {
807
+ for (const { relPath } of PAYLOAD_LINKS) {
808
+ const linkAbs = path.join(ctx.cwd, relPath);
809
+ let st: fs.Stats | null = null;
810
+ try {
811
+ st = fs.lstatSync(linkAbs);
812
+ } catch {
813
+ st = null; // absent
814
+ }
815
+ if (st?.isSymbolicLink() !== true) continue;
816
+ result.deleted.push(relPath);
817
+ if (!ctx.dryRun) {
818
+ fs.rmSync(linkAbs, { force: true });
819
+ console.log(`${ctx.logPrefix} delete: ${relPath} (payload view link)`);
820
+ }
821
+ }
822
+ }
823
+
796
824
  // Prune bkit-authored dirs left empty by the deletions above (e.g. .claude/agents,
797
825
  // .claude/hooks). Candidates are the parent
798
826
  // dirs of everything deleted, plus their ancestors; each is removed ONLY when it is actually
@@ -822,6 +850,33 @@ export async function runUninstall(
822
850
  }
823
851
  }
824
852
 
853
+ // Targeted (non-core) uninstall: `.bkit/version` stays (the modules that remain read it),
854
+ // but its canonicalHashes still list every path this run deleted — absent entries that
855
+ // `mergeCanonicalHashes` prunes. Left in place, the very next `bkit check` (a dry-run
856
+ // install whose core postDispatch prunes the same absent paths) reports write-drift on
857
+ // `.bkit/version` and fails the CI gate. Recompute and rewrite here so the on-disk manifest
858
+ // already matches what the next check would produce. A full/core uninstall deletes the file
859
+ // earlier instead (zero footprint) and never reaches this branch.
860
+ if (!moduleList.includes("core")) {
861
+ const versionFile = path.join(ctx.cwd, ".bkit", "version");
862
+ const existing = readBkitVersion(versionFile);
863
+ if (existing) {
864
+ const { canonicalHashes, pruned } = mergeCanonicalHashes(
865
+ ctx.cwd,
866
+ existing.canonicalHashes,
867
+ {},
868
+ );
869
+ if (pruned > 0) {
870
+ console.log(
871
+ `${ctx.logPrefix}${ctx.dryRun ? " [dry-run]" : ""} update version pin: .bkit/version (pruned ${pruned})`,
872
+ );
873
+ if (!ctx.dryRun) {
874
+ writeBkitVersion(versionFile, { ...existing, canonicalHashes });
875
+ }
876
+ }
877
+ }
878
+ }
879
+
825
880
  return result;
826
881
  }
827
882
 
@@ -68,6 +68,7 @@ import {
68
68
  writeCursorCliPermissionsArtifact,
69
69
  } from "../../install/cloud-env.js";
70
70
  import { syncTemplateCopies, formatTemplateChanges } from "../../install/template-copies.js";
71
+ import { formatPayloadLinkChanges, syncPayloadLinks } from "../../install/payload-links.js";
71
72
  import { renderOpencodeJson, reconcileOpencodeJson } from "../../install/modules/opencode.js";
72
73
  import { type ModuleContext, renderManagedOutputs } from "../../install/modules/index.js";
73
74
  import { reconcileMcpJson, enrichClaudeSettingsAllows } from "../../install/modules/claude.js";
@@ -552,8 +553,8 @@ async function resolveLatestPublishedVersion(cwd: string): Promise<string> {
552
553
  if (r.status !== 0 || !r.stdout || !r.stdout.trim()) {
553
554
  console.error(
554
555
  `${LOG_PREFIX} could not resolve the latest @cbartens/bkit version from the registry ` +
555
- `(pnpm view exit ${r.status ?? "null"}). Ensure GitHub Packages read auth (BKIT_GH_TOKEN_INSTALL, ` +
556
- `classic PAT, read:packages), or pin a version with --to=<version>.`,
556
+ `(pnpm view exit ${r.status ?? "null"}). Check your network / registry access, ` +
557
+ `or pin a version with --to=<version>.`,
557
558
  );
558
559
  process.exit(1);
559
560
  }
@@ -626,7 +627,7 @@ export async function runSelfBump(flags: UpgradeFlags, cwd: string): Promise<boo
626
627
  if (add.status !== 0) {
627
628
  console.error(
628
629
  `${LOG_PREFIX} \`${addCmd}\` failed (exit ${add.status ?? "null"}). ` +
629
- `Most common cause: GitHub Packages auth — set BKIT_GH_TOKEN_INSTALL (classic PAT, read:packages). Nothing re-rendered.`,
630
+ `Check your network / registry access. Nothing re-rendered.`,
630
631
  );
631
632
  process.exit(1);
632
633
  }
@@ -799,6 +800,16 @@ export async function runUpgradeCommand(upgradeFlags: UpgradeFlags): Promise<voi
799
800
  const templateReport = formatTemplateChanges(templateChanges);
800
801
  if (templateReport) console.log(`${LOG_PREFIX} ${templateReport}`);
801
802
 
803
+ // Payload view links — the same sync install runs (`.bkit/core` + `.bkit/shared`
804
+ // point into the installed package). Never clobbers a real directory; a platform
805
+ // refusal is reported, never fatal. Throwaway WriteSet: links carry no hash.
806
+ const linkChanges = syncPayloadLinks(process.cwd(), {
807
+ dryRun: upgradeFlags.dryRun,
808
+ ws: { writes: [] },
809
+ });
810
+ const linkReport = formatPayloadLinkChanges(linkChanges);
811
+ if (linkReport) console.log(`${LOG_PREFIX} ${linkReport}`);
812
+
802
813
  // Re-render all installed provider blocks for upgrade.
803
814
  // The candidates walk above handles the ACTIVE provider's block via renderOpencodeJson.
804
815
  // For each ADDITIONAL installed provider, reconcile their template block into opencode.json
@@ -274,8 +274,9 @@ const isHelp = (arg: string | undefined) => arg === "--help" || arg === "-h";
274
274
  * Run `argv` (without the leading `bkit`) if it names a registered command.
275
275
  * Returns the exit code, or null when `argv` is not a command, so the caller falls
276
276
  * through to the classic verbs. A noun that is also a classic verb (`status`)
277
- * routes only when the second word is one of its verbs, so `bkit status` keeps
278
- * its classic meaning.
277
+ * routes only when the second word is one of its verbs or a help flag, so
278
+ * `bkit status` keeps its classic meaning while `bkit status --help` still lists
279
+ * the noun's own verbs.
279
280
  */
280
281
  export async function runCommand(
281
282
  argv: string[],
@@ -287,7 +288,7 @@ export async function runCommand(
287
288
  if (!cmd) return null;
288
289
  const verb = argv[1];
289
290
  const isVerb = verb !== undefined && Object.hasOwn(cmd.verbs, verb);
290
- if (!isVerb && options.classicVerbs.has(cmd.noun)) return null;
291
+ if (!isVerb && options.classicVerbs.has(cmd.noun) && !isHelp(verb)) return null;
291
292
 
292
293
  const tag = logTag(cmd.noun);
293
294
  if (!isVerb) {
@@ -39,8 +39,10 @@ export const SESSION_HIJACK_KEYS = [
39
39
  // placeholder ONLY when absent from the resolved `.envrc` set — a present value
40
40
  // (e.g. BKIT_GH_TOKEN already in `.bkit/.env`) keeps its real resolved value.
41
41
  const BASELINE_TOKEN_PLACEHOLDERS: ReadonlyArray<readonly [string, string]> = [
42
- ["BKIT_GH_TOKEN", "<fine-grained PAT — see .bkit/cloud.md § BKIT_GH_TOKEN permissions>"],
43
- ["BKIT_GH_TOKEN_INSTALL", "<classic PAT with read:packages>"],
42
+ [
43
+ "BKIT_GH_TOKEN",
44
+ "<PAT — fine-grained one owner / classic across owners; see .bkit/cloud.md § BKIT_GH_TOKEN token permissions>",
45
+ ],
44
46
  ];
45
47
 
46
48
  // Earlier-compaction override — a bkit constant, not a secret. Appended to the
@@ -84,7 +84,6 @@ export function runCloudModule(ctx: ModuleContext): void {
84
84
  " - Run `/install-github-app` (Claude Code CLI) to install the Claude GitHub App on your repo. This is required — `claude-code-action@v1` authenticates as the App via OIDC (`id-token: write`); without the App it fails at boot with an OIDC error.\n" +
85
85
  " - GitHub Actions permissions — flip BOTH org AND repo: Settings → Actions → General → Workflow permissions = **Read and write permissions** + tick **Allow GitHub Actions to create and approve pull requests**.\n" +
86
86
  " - Add `ANTHROPIC_API_KEY` to repo secrets (Settings → Secrets and variables → Actions). Used by `claude-code-action@v1` (job env keeps this vendor name; local `.bkit/.env` stores it as `BKIT_ANTHROPIC_API_KEY`).\n" +
87
- " - Do NOT add `BKIT_GH_TOKEN_INSTALL` to this workflow — it is package-install scoped and has no access to the consumer repo. Repo git/gh ops use the auto-provided `github.token` via the workflow's `permissions:` block.\n" +
88
87
  " - Label the issue `bkit:auto` before pushing the build commit — without the label the CI auto-route exits no-op.\n\n" +
89
88
  "OPTIONAL (manual phase launch): after `/install-github-app`, comment `@claude /bkit-plan` (or any phase) on a GitHub issue/PR to launch it from the tracker UI. The App's generated `claude.yml` triggers on mention events; `bkit-cloud.yml` triggers on CI completion + `workflow_dispatch` — the two coexist.\n\n" +
90
89
  "Both the CI-driven path and the `@claude` mention path invoke the same `/bkit-auto` orchestrator (mirrored to `.claude/commands/bkit-auto.md` on each `pnpm bkit install`).",
@@ -103,8 +102,8 @@ export function runCloudModule(ctx: ModuleContext): void {
103
102
  "IN CLAUDE APP (claude.ai/code → environment selector → + Add environment):\n" +
104
103
  " - Name: the repo name (e.g. `acme-web`) — one environment per repo, since secrets are per-repo.\n" +
105
104
  " - Setup script: paste from bkit's `cloud.md` § Setup script (installs vale + gh + corepack-pinned pnpm — exact versions live in cloud.md, not duplicated here).\n" +
106
- " - Environment variables: `BKIT_GH_TOKEN` (fine-grained PAT for GitHub MCP), `BKIT_GH_TOKEN_INSTALL` (classic PAT with read:packages), `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70`.\n" +
107
- " - Tracker env vars (GitHub): No tracker PAT needed. Run `gh auth login` once for CLI surface. MCP auth is browser OAuth (automatic on first tool call). Set `BKIT_GH_TOKEN` (fine-grained PAT for GitHub MCP server).\n" +
105
+ " - Environment variables: `BKIT_GH_TOKEN` (fine-grained for one owner, classic across owners — GitHub MCP), `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70`.\n" +
106
+ " - Tracker env vars (GitHub): No tracker PAT needed. Run `gh auth login` once for CLI surface. MCP auth is browser OAuth (automatic on first tool call). Set `BKIT_GH_TOKEN` (fine-grained for one owner, classic across owners — GitHub MCP server).\n" +
108
107
  " - Network access: `Trusted` (default). One environment per repo (secrets differ per repo); the setup script + variable *names* are identical across repos, only the values change. See cloud.md § Sharing across repos → Claude.",
109
108
  });
110
109
  } else if (variant === "opencode") {
@@ -165,7 +164,7 @@ export function runCloudModule(ctx: ModuleContext): void {
165
164
  action:
166
165
  "Copy-paste-ready values (resolved from your `.envrc`) are written to `.cursor/bkit-cloud.md` (gitignored) on every install.\n\n" +
167
166
  "IN THE CLOUD AGENTS DASHBOARD (https://cursor.com/dashboard/cloud-agents → your environment → Secrets tab) — add each as a **Runtime Secret** (loaded as an env var, redacted from the agent's transcript):\n" +
168
- " - `BKIT_GH_TOKEN`, `BKIT_GH_TOKEN_INSTALL`.\n" +
167
+ " - `BKIT_GH_TOKEN`.\n" +
169
168
  " - Tracker secret (Linear): `BKIT_LINEAR_API_KEY` (generate at https://linear.app/settings/api). `LINEAR_ISSUE_ID` is injected per-session — don't hardcode.\n" +
170
169
  " - First session after Dockerfile changes rebuilds the image; subsequent sessions reuse cached layers.\n\n" +
171
170
  "Full recipe in bkit's `cloud.md`; the paste-ready block is in `.cursor/bkit-cloud.md`.",
@@ -13,6 +13,7 @@ import {
13
13
  } from "../version-file.js";
14
14
  import type { TokenMap } from "../placeholders.js";
15
15
  import { listFilesRecursive, syncTemplateCopies } from "../template-copies.js";
16
+ import { PAYLOAD_LINK_RELPATHS, syncPayloadLinks } from "../payload-links.js";
16
17
  import type { PreflightFinding } from "../../checks/before/index.js";
17
18
  import {
18
19
  getPkgRoot,
@@ -498,6 +499,34 @@ export function runCoreModule(ctx: ModuleContext): void {
498
499
  }
499
500
  }
500
501
 
502
+ // 3b3. Payload view links — `.bkit/core` + `.bkit/shared` symlinks into the
503
+ // installed package (browse-only, gitignored; no-op in dogfood). A real
504
+ // directory or file at either path is never clobbered (advisory); a platform
505
+ // refusal is an advisory, never a failure.
506
+ const linkChanges = syncPayloadLinks(cwd, { dryRun, ws });
507
+ for (const rel of linkChanges.created) {
508
+ console.log(`${logPrefix} ${tag}payload link: ${rel}`);
509
+ }
510
+ for (const rel of linkChanges.repaired) {
511
+ console.log(`${logPrefix} ${tag}payload link repaired: ${rel}`);
512
+ }
513
+ for (const rel of linkChanges.skippedRealDir) {
514
+ advisories.push({
515
+ id: "payload-link-real-dir",
516
+ severity: "advisory",
517
+ detect: `${rel} is a real directory or file, not a view symlink into the installed package — left untouched.`,
518
+ action: `bkit never overwrites consumer content. The ${rel} view is a symlink into node_modules/@cbartens/bkit; if you want it, remove your own ${rel} by hand and re-run \`bkit install\`.`,
519
+ });
520
+ }
521
+ for (const rel of linkChanges.failed) {
522
+ advisories.push({
523
+ id: "payload-link-failed",
524
+ severity: "advisory",
525
+ detect: `could not create the ${rel} view symlink into the installed package (the platform refused).`,
526
+ action: `Browse-only — bkit reads its payload from the package regardless. To add the view by hand on POSIX: ln -s ../node_modules/@cbartens/bkit/${rel} ${rel}`,
527
+ });
528
+ }
529
+
501
530
  // 3c. The bkit:gate:* / bkit:deps:* package.json scripts (add-if-missing). The
502
531
  // advisories read the result.
503
532
  seedCorePackageJsonScripts(ctx);
@@ -526,6 +555,8 @@ export function runCoreModule(ctx: ModuleContext): void {
526
555
  if (relPath.startsWith(".agents" + path.sep)) continue;
527
556
  // Template copies carry no hash.
528
557
  if (relPath.startsWith(TEMPLATE_COPIES_DIR + path.sep)) continue;
558
+ // Payload view links carry no hash either — a symlink's bytes are the package's.
559
+ if (PAYLOAD_LINK_RELPATHS.has(relPath)) continue;
529
560
  if (!fs.existsSync(absPath)) continue;
530
561
  const hash = hashFile(absPath);
531
562
  if (hash) newCanonicalEntries[relPath] = hash;
@@ -572,19 +603,8 @@ export function runCoreModule(ctx: ModuleContext): void {
572
603
  detect: "First install detected (.bkit/version was absent).",
573
604
  action:
574
605
  "Post-install steps:\n\n" +
575
- "1. Add BKIT_GH_TOKEN_INSTALL to your GitHub Actions repository secrets:\n" +
576
- " - Create a classic PAT with `read:packages` scope (fine-grained PATs are\n" +
577
- " not currently supported by GitHub Packages npm registry).\n" +
578
- " - GitHub Settings → Secrets and variables → Actions → New repository secret\n" +
579
- " - Name: BKIT_GH_TOKEN_INSTALL\n" +
580
- " - See README.md ## Consumer CI auth for full setup.\n\n" +
581
- "2. Add a `.npmrc` at your repo root with the @cbartens registry mapping (the\n" +
582
- " auth token is NOT stored here — it goes in pnpm's user-level config):\n" +
583
- " @cbartens:registry=https://npm.pkg.github.com\n\n" +
584
- "3. Write the token into pnpm's user-level config (run once; CI does this in its\n" +
585
- " install step). pnpm >=10.34.3 401s on a project-.npmrc ${BKIT_GH_TOKEN_INSTALL} ref:\n" +
586
- ' pnpm config set "//npm.pkg.github.com/:_authToken=$BKIT_GH_TOKEN_INSTALL"\n\n' +
587
- "4. Run `pnpm install` to refresh the lockfile, then commit.\n\n" +
606
+ "1. Run `pnpm install` to refresh the lockfile, then commit.\n\n" +
607
+ "2. See `.bkit/install.md` for consumer setup and `.bkit/README.md` for ongoing ops.\n\n" +
588
608
  "Note: bkit seeded the bkit:gate:* / bkit:deps:* package.json scripts every workflow\n" +
589
609
  "runs (existing values are never touched). The tool scripts they chain (typecheck,\n" +
590
610
  "lint, format:check, lint:prose, slop:delta) and the devDeps those need are yours to\n" +
@@ -251,10 +251,11 @@ const OPENCODE_PROVIDER_BASE_URL_SENTINEL = "@@OPENCODE_PROVIDER_BASE_URL@@";
251
251
  * Resolves the @@OPENCODE_TRACKER_MCP@@ sentinel into the correct mcpServers entry
252
252
  * and fills in provider-specific fields.
253
253
  *
254
- * Also injects `curl *{domain}*` / `wget *{domain}*` **allow** rules (after the
255
- * template's `curl *` / `wget *` ask) for {@link resolveNetworkAllowlist} so
256
- * context-fetch / provider hosts do not prompt (OpenCode bash is last-match-wins), and
257
- * `<server>_*` allows for the consumer's `mcp-servers` block.
254
+ * Also injects derived **allow** rules for {@link resolveNetworkAllowlist} so
255
+ * context-fetch / provider hosts do not prompt on either fetch surface: `curl *{domain}*` /
256
+ * `wget *{domain}*` after the template's `curl *` / `wget *` ask (OpenCode bash is
257
+ * last-match-wins), and `*{domain}*` into the `permission.webfetch` URL map (after its
258
+ * `"*": "ask"`). Adds `<server>_*` allows for the consumer's `mcp-servers` block.
258
259
  */
259
260
  export function renderOpencodeJson(
260
261
  templatePath: string,
@@ -274,10 +275,14 @@ export function renderOpencodeJson(
274
275
  // opencode's MCP schema differs from Claude/Cursor: remote servers use type "remote"
275
276
  // (NOT "http" — not in opencode's enum, which makes the whole config invalid) and read
276
277
  // secrets via {env:VAR} (NOT shell ${VAR}). See https://opencode.ai/config.json.
278
+ // github: "oauth": false disables opencode's automatic OAuth. api.githubcopilot.com/mcp/
279
+ // authenticates via the Authorization header and has no OAuth DCR, so a stale/empty
280
+ // {env:BKIT_GH_TOKEN} would otherwise surface as a "sign in" prompt whose flow fails with
281
+ // "dynamic auth not supported" instead of a clear 401. See opencode.ai/docs/mcp-servers.
277
282
  let mcpEntry: string;
278
283
  if (tracker === "github") {
279
284
  mcpEntry =
280
- '"github": { "type": "remote", "url": "https://api.githubcopilot.com/mcp/", "headers": { "Authorization": "Bearer {env:BKIT_GH_TOKEN}", "X-MCP-Toolsets": "context,issues,pull_requests,repos,users,projects" } }';
285
+ '"github": { "type": "remote", "url": "https://api.githubcopilot.com/mcp/", "oauth": false, "headers": { "Authorization": "Bearer {env:BKIT_GH_TOKEN}", "X-MCP-Toolsets": "context,issues,pull_requests,repos,users,projects" } }';
281
286
  } else if (tracker === "linear") {
282
287
  mcpEntry = '"linear": { "type": "remote", "url": "https://mcp.linear.app/mcp" }';
283
288
  } else {
@@ -332,9 +337,16 @@ export function renderOpencodeJson(
332
337
  }
333
338
 
334
339
  /**
335
- * Append curl/wget domain allows after template ask rules (OpenCode last-match-wins),
336
- * and one `<server>_*` allow per declared MCP server — opencode names MCP tools
337
- * `<server>_<tool>` and matches permission keys as globs against the tool name.
340
+ * Append derived allows for the consumer's resolved network allowlist (OpenCode
341
+ * last-match-wins), and one `<server>_*` allow per declared MCP server — opencode names
342
+ * MCP tools `<server>_<tool>` and matches permission keys as globs against the tool name.
343
+ *
344
+ * The allowlist is applied to BOTH fetch surfaces, so an allowlisted host does not prompt
345
+ * whichever path the agent takes:
346
+ * - fetch tool — `permission.webfetch` is a URL-keyed map (`{ "*": "ask" }` from the
347
+ * template); opencode matches the resource against the URL, so `*{base}*` allows it;
348
+ * - shell fetch — `permission.bash` gains `curl *{base}*` / `wget *{base}*` after the
349
+ * template's `curl *` / `wget *` ask.
338
350
  */
339
351
  function injectOpencodeDerivedAllows(parsed: Record<string, unknown>, cwd: string): void {
340
352
  const permission = parsed.permission as Record<string, unknown> | undefined;
@@ -342,11 +354,20 @@ function injectOpencodeDerivedAllows(parsed: Record<string, unknown>, cwd: strin
342
354
  for (const server of extractMcpServers(cwd)) {
343
355
  permission[`${server}_*`] = "allow";
344
356
  }
345
- if (typeof permission.bash !== "object" || permission.bash === null) return;
346
- const bash = permission.bash as Record<string, string>;
347
- for (const base of networkAllowlistBases(resolveNetworkAllowlist(cwd))) {
348
- bash[`curl *${base}*`] = "allow";
349
- bash[`wget *${base}*`] = "allow";
357
+ const bases = networkAllowlistBases(resolveNetworkAllowlist(cwd));
358
+ if (typeof permission.bash === "object" && permission.bash !== null) {
359
+ const bash = permission.bash as Record<string, string>;
360
+ for (const base of bases) {
361
+ bash[`curl *${base}*`] = "allow";
362
+ bash[`wget *${base}*`] = "allow";
363
+ }
364
+ }
365
+ // Fetch tool — opencode matches the webfetch resource against the requested URL.
366
+ if (typeof permission.webfetch === "object" && permission.webfetch !== null) {
367
+ const webfetch = permission.webfetch as Record<string, string>;
368
+ for (const base of bases) {
369
+ webfetch[`*${base}*`] = "allow";
370
+ }
350
371
  }
351
372
  }
352
373
 
@@ -0,0 +1,150 @@
1
+ // install/payload-links.ts — the consumer's `.bkit/core` and `.bkit/shared` view
2
+ // links: relative symlinks into the installed package payload (#525), so the
3
+ // workflow / prompt / hook sources are browsable from the consumer repo without
4
+ // copying. Views, not copies — always the installed version, never hashed.
5
+
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { getCoreRoot, getPkgRoot, getSharedRoot } from "../shared/package-roots.js";
9
+ import type { WriteSet } from "./write.js";
10
+
11
+ // The two view links: a symlink at the consumer-relative `relPath` pointing at the
12
+ // package payload dir `target()` resolves to. Relative targets, so the link keeps
13
+ // working when the repo moves; both dangle on a fresh clone or in CI (no
14
+ // node_modules), which is why the managed `.gitignore` block carries both paths
15
+ // and checks/before/files.ts BKIT_GITIGNORE_LINES lists them.
16
+ export const PAYLOAD_LINKS: ReadonlyArray<{ relPath: string; target: () => string }> = [
17
+ { relPath: path.join(".bkit", "core"), target: getCoreRoot },
18
+ { relPath: path.join(".bkit", "shared"), target: getSharedRoot },
19
+ ];
20
+
21
+ /** The consumer-relative paths above, as a lookup set (version-hash exclusion). */
22
+ export const PAYLOAD_LINK_RELPATHS: ReadonlySet<string> = new Set(
23
+ PAYLOAD_LINKS.map((l) => l.relPath),
24
+ );
25
+
26
+ /** What a sync did, per link path. */
27
+ export interface PayloadLinkChanges {
28
+ created: string[];
29
+ repaired: string[];
30
+ kept: string[];
31
+ /** Real directory or file at the link path — never clobbered; advisory-worthy. */
32
+ skippedRealDir: string[];
33
+ /** Platform refused the symlink (e.g. Windows without Developer Mode). Advisory, never fatal. */
34
+ failed: string[];
35
+ }
36
+
37
+ /**
38
+ * Create the view link at `linkAbs` pointing at `targetAbs`: a relative `dir`
39
+ * symlink first; where the platform refuses it (Windows without Developer Mode or
40
+ * elevation) fall back to an absolute `junction`, which needs no privilege.
41
+ * `symlinkFn` is injectable so the platform branch is testable off-Windows.
42
+ */
43
+ export function createPayloadLink(
44
+ targetAbs: string,
45
+ linkAbs: string,
46
+ symlinkFn: (target: string, link: string, type?: "dir" | "junction") => void = fs.symlinkSync,
47
+ ): "relative" | "junction" {
48
+ const relTarget = path.relative(path.dirname(linkAbs), targetAbs);
49
+ try {
50
+ symlinkFn(relTarget, linkAbs, "dir");
51
+ return "relative";
52
+ } catch {
53
+ symlinkFn(targetAbs, linkAbs, "junction");
54
+ return "junction";
55
+ }
56
+ }
57
+
58
+ // Create or refresh the consumer's `.bkit/core` + `.bkit/shared` view links into
59
+ // the package payload. Idempotent: a correct link is kept, a dangling or
60
+ // mis-pointed symlink is re-pointed, a real directory or file is NEVER clobbered
61
+ // (skippedRealDir) and a platform refusal is only recorded (failed). Every create
62
+ // or repair pushes a ws write in dry-run and live alike, so `bkit check` flags a
63
+ // missing or broken link as drift. No-op in dogfood: there `.bkit/core` IS the
64
+ // package source, never a view onto it.
65
+ export function syncPayloadLinks(
66
+ cwd: string,
67
+ opts: { dryRun: boolean; ws: WriteSet },
68
+ ): PayloadLinkChanges {
69
+ const changes: PayloadLinkChanges = {
70
+ created: [],
71
+ repaired: [],
72
+ kept: [],
73
+ skippedRealDir: [],
74
+ failed: [],
75
+ };
76
+ if (path.resolve(cwd) === getPkgRoot()) return changes;
77
+
78
+ for (const { relPath, target } of PAYLOAD_LINKS) {
79
+ const linkAbs = path.join(cwd, relPath);
80
+ const targetAbs = target();
81
+ if (!fs.existsSync(targetAbs)) {
82
+ changes.failed.push(relPath); // package payload missing — package corrupt?
83
+ continue;
84
+ }
85
+
86
+ // lstat, not stat: the symlink itself is what matters, never its target.
87
+ let st: fs.Stats | null = null;
88
+ try {
89
+ st = fs.lstatSync(linkAbs);
90
+ } catch {
91
+ st = null; // absent
92
+ }
93
+
94
+ if (st !== null && !st.isSymbolicLink()) {
95
+ changes.skippedRealDir.push(relPath); // consumer content — never clobber
96
+ continue;
97
+ }
98
+
99
+ if (st !== null) {
100
+ // A symlink: keep when it already resolves to the payload, re-point otherwise
101
+ // (dangling — realpathSync throws — or pointing somewhere else).
102
+ let resolves = false;
103
+ try {
104
+ resolves = fs.realpathSync(linkAbs) === fs.realpathSync(targetAbs);
105
+ } catch {
106
+ resolves = false;
107
+ }
108
+ if (resolves) {
109
+ changes.kept.push(relPath);
110
+ continue;
111
+ }
112
+ if (!opts.dryRun) fs.rmSync(linkAbs);
113
+ }
114
+
115
+ if (!opts.dryRun) {
116
+ fs.mkdirSync(path.dirname(linkAbs), { recursive: true });
117
+ try {
118
+ createPayloadLink(targetAbs, linkAbs);
119
+ } catch {
120
+ changes.failed.push(relPath);
121
+ continue;
122
+ }
123
+ }
124
+ (st !== null ? changes.repaired : changes.created).push(relPath);
125
+ opts.ws.writes.push({ path: relPath, action: "write" });
126
+ }
127
+ return changes;
128
+ }
129
+
130
+ // The upgrade report for a link sync: one line per created, repaired, skipped or
131
+ // failed link. Empty when every link was already correct.
132
+ export function formatPayloadLinkChanges(changes: PayloadLinkChanges): string {
133
+ const lines = [
134
+ ...changes.created.map((p) => ` linked: ${p}`),
135
+ ...changes.repaired.map((p) => ` repaired: ${p}`),
136
+ ...changes.skippedRealDir.map(
137
+ (p) =>
138
+ ` skipped: ${p} — a real directory or file, never overwritten; remove it yourself to get the view link`,
139
+ ),
140
+ ...changes.failed.map(
141
+ (p) =>
142
+ ` failed: ${p} — platform refused the symlink (browse-only; bkit reads its payload from the package regardless)`,
143
+ ),
144
+ ];
145
+ if (lines.length === 0) return "";
146
+ return [
147
+ "Payload view links — `.bkit/core` + `.bkit/shared` point into the installed package (gitignored, browse-only):",
148
+ ...lines,
149
+ ].join("\n");
150
+ }
@@ -98,7 +98,7 @@ function pruneEmptyDirs(root: string): void {
98
98
 
99
99
  /** One-line pointer to the template docs, shared by the install and upgrade messages. */
100
100
  export const TEMPLATES_POINTER =
101
- "Templates: see .bkit/templates.md; copies live in .bkit/templates/ (if your own gates scan the repo, ignore .bkit/templates/).";
101
+ "Templates (adopt, do not skip): read .bkit/templates.md; bkit never applies templates, so adopt each copy in .bkit/templates/ unless adoption would break existing functionality — state which you did not adopt and why. (If your own gates scan the repo, ignore .bkit/templates/.)";
102
102
 
103
103
  /**
104
104
  * The upgrade report for a template sync: one line per changed, added or removed
@@ -173,7 +173,7 @@ export const BKIT_EGRESS_SOURCES: readonly EgressSource[] = [
173
173
  {
174
174
  id: "pkg-github",
175
175
  kind: "package-registry",
176
- hosts: ["npm.pkg.github.com", "raw.githubusercontent.com"],
176
+ hosts: ["raw.githubusercontent.com"],
177
177
  bases: ["github.com", "githubusercontent.com"],
178
178
  },
179
179
  { id: "skills-sh", kind: "skills", hosts: ["skills.sh"], bases: ["skills.sh"] },