castle-web-cli 0.4.141 → 0.4.144

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.
@@ -73,6 +73,7 @@ export declare function applyPlanOps(fileText: string, ops: PlanOp[], sources?:
73
73
  export declare function renderPlanDigest(plan: RouterPlanOpts, tasks: PromptTask[]): string;
74
74
  export declare function planOpenQuestionLines(fileText: string): string[];
75
75
  export declare function renderTaskPlanSlice(fileText: string, item: string | undefined, finishedWork?: PlanFinishedWork[]): string;
76
+ export declare const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
76
77
  export declare function buildRouterPrompt(opts: {
77
78
  deckLabel: string;
78
79
  quickReference?: string;
@@ -790,6 +790,11 @@ function renderTasks(tasks, showItems) {
790
790
  })
791
791
  .join("\n");
792
792
  }
793
+ // Said outright rather than left out: a router/task agent on a deck with no
794
+ // quick reference otherwise cannot tell "no docs exist" from "the section was
795
+ // not included" and burns its first turns hunting for CLAUDE.md. Exported so
796
+ // the platform block (platformDoc.ts) can keep the sentence after itself.
797
+ export const NO_DECK_DOCS = "This deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
793
798
  export function buildRouterPrompt(opts) {
794
799
  // Making the ABSENCE explicit, not just omitting the section, matters: a
795
800
  // router on a bare/greenfield deck otherwise has no way to tell "no docs
@@ -799,7 +804,7 @@ export function buildRouterPrompt(opts) {
799
804
  // 8-file deck with zero markdown files).
800
805
  const quickReference = opts.quickReference?.trim()
801
806
  ? `\n\n== how this deck works ==\n${opts.quickReference.trim()}`
802
- : "\n\n== how this deck works ==\nThis deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).";
807
+ : `\n\n== how this deck works ==\n${NO_DECK_DOCS}`;
803
808
  const deckFiles = opts.deckTree?.trim()
804
809
  ? `\n\n== deck files ==\n${opts.deckTree.trim()}`
805
810
  : "";
@@ -869,7 +874,7 @@ export function buildTaskPrompt(opts) {
869
874
  // does if it has to discover the absence itself via a failed read/grep.
870
875
  const quickReference = opts.quickReference?.trim()
871
876
  ? `\n\nHow this deck works (from its docs -- read the full CLAUDE.md / AGENTS.md only when you need detail beyond this):\n\n${opts.quickReference.trim()}\n`
872
- : "\n\nThis deck has no CLAUDE.md / AGENTS.md quick reference. There is no documentation to read -- do not search for one (CLAUDE.md, README, **/*.md, etc.).\n";
877
+ : `\n\n${NO_DECK_DOCS}\n`;
873
878
  const layout = opts.deckTree?.trim()
874
879
  ? `\n\nDeck files (snapshot at task start; parallel sibling tasks may create files named in your prompt that are absent here):\n\n${opts.deckTree.trim()}\n`
875
880
  : "";
package/dist/agent.d.ts CHANGED
@@ -77,6 +77,8 @@ export declare function createAgentServer(opts: {
77
77
  deckDir: string;
78
78
  deckLabel: string;
79
79
  port?: number;
80
+ playtestServeUrl?: string;
80
81
  restart?: () => void;
82
+ authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
81
83
  }): AgentServer;
82
84
  export {};
package/dist/agent.js CHANGED
@@ -15,6 +15,7 @@
15
15
  // runs with --mode ask (read-only at the CLI level); task agents run with
16
16
  // --force. Claude support can slot in later behind runAgentCli.
17
17
  import { execFileSync, spawn } from 'child_process';
18
+ import { quickReferenceFor } from './platformDoc.js';
18
19
  import { IMPORTS_DIR } from './imports.js';
19
20
  import { isSameOriginUpgrade } from './wsOrigin.js';
20
21
  import * as fs from 'fs';
@@ -641,13 +642,11 @@ function extractDirectives(full) {
641
642
  };
642
643
  }
643
644
  const planSessions = new Map();
644
- // What a deck that says nothing gets. Off unless the serve was told otherwise,
645
- // so a serve nobody configured -- one started from a terminal, or by a caller
646
- // that forgot the flag -- lands on the default rather than quietly handing the
647
- // feature to someone outside the rollout. The cloud editor sets it per user
648
- // from a feature gate; see serveOnPort in castle-www's cloudSandbox.ts.
645
+ // What a deck that says nothing gets. On unless the serve was explicitly told
646
+ // otherwise -- `CASTLE_AGENT_PLAN=off` is what the agent-qa harness uses to keep
647
+ // the plan doc out of scenarios that aren't testing it.
649
648
  function planDefault() {
650
- return process.env.CASTLE_AGENT_PLAN === 'on';
649
+ return process.env.CASTLE_AGENT_PLAN !== 'off';
651
650
  }
652
651
  function planSession(deckDir) {
653
652
  const existing = planSessions.get(deckDir);
@@ -1355,7 +1354,10 @@ function readClaudeSectionWithImports(deckDir, section) {
1355
1354
  const text = readClaudeSection(path.join(deckDir, IMPORTS_DIR, alias), section);
1356
1355
  if (!text)
1357
1356
  continue;
1358
- const role = alias === entry ? 'this deck runs on it' : 'imported, not the entry';
1357
+ // "not the entry" only distinguishes an import from the one that IS the
1358
+ // entry. A deck running its own code has no entry import, and every import
1359
+ // it has is simply an import.
1360
+ const role = alias === entry ? 'this deck runs on it' : entry ? 'imported, not the entry' : 'imported';
1359
1361
  parts.push(`### from the ${alias} kit (${role})\n\n${text}`);
1360
1362
  }
1361
1363
  return parts.join('\n\n');
@@ -2377,7 +2379,7 @@ async function runTaskAgentIn(ctx, task) {
2377
2379
  ? { maxEntries: DECK_TREE_SLIM_MAX_ENTRIES, perDir: DECK_TREE_SLIM_PER_DIR }
2378
2380
  : undefined),
2379
2381
  deckContents,
2380
- quickReference: ctx.quickReference,
2382
+ quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, ctx.backend),
2381
2383
  plan: taskPlanOpts(ctx.deckDir, task.item, ctx.finishedWork),
2382
2384
  siblings: ctx.siblings,
2383
2385
  });
@@ -3103,7 +3105,7 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3103
3105
  const isSmith = ctx.backend() === 'smith';
3104
3106
  return buildRouterPrompt({
3105
3107
  deckLabel: ctx.deckLabel,
3106
- quickReference: ctx.quickReference,
3108
+ quickReference: quickReferenceFor(ctx.deckDir, ctx.quickReference, ctx.backend()),
3107
3109
  deckTree: buildDeckTree(ctx.deckDir, isSmith
3108
3110
  ? { maxEntries: DECK_TREE_SLIM_MAX_ENTRIES, perDir: DECK_TREE_SLIM_PER_DIR }
3109
3111
  : undefined),
@@ -3995,7 +3997,7 @@ export function createAgentServer(opts) {
3995
3997
  // 127.0.0.1 never answers there, and playtest would fail every call
3996
3998
  // with a navigation error. `localhost` resolves correctly under
3997
3999
  // every binding mode (default ::1, --host 0.0.0.0, explicit IPs).
3998
- serveUrl: `http://localhost:${opts.port}`,
4000
+ serveUrl: opts.playtestServeUrl ?? `http://localhost:${opts.port}`,
3999
4001
  // Kicks off the one-time Chromium download in the background at
4000
4002
  // smith-task start (see runTaskAgentIn) -- single-flight with any
4001
4003
  // real playtest call, silent on every failure path.
@@ -4215,7 +4217,7 @@ export function createAgentServer(opts) {
4215
4217
  // The agent socket drives the coding agent (exec, file writes) — reject any upgrade
4216
4218
  // that isn't same-origin (a co-tenant reaching this port directly sends no browser
4217
4219
  // Origin). Consumed either way so a rejected upgrade never falls through.
4218
- if (!isSameOriginUpgrade(req)) {
4220
+ if (!isSameOriginUpgrade(req) || (opts.authorizeUpgrade && !opts.authorizeUpgrade(req, 'agent'))) {
4219
4221
  socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
4220
4222
  socket.destroy();
4221
4223
  return true;
package/dist/ide.d.ts CHANGED
@@ -28,4 +28,6 @@ export declare function createIdeServer(opts: {
28
28
  * deck-relative paths whose resolution changed, not just their contents.
29
29
  */
30
30
  invalidate?: (paths?: string[]) => void;
31
+ shellBootstrap?: (req: http.IncomingMessage) => string;
32
+ authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'pty') => boolean;
31
33
  }): IdeServer;
package/dist/ide.js CHANGED
@@ -101,6 +101,22 @@ function serveShellFile(res, asset) {
101
101
  fs.createReadStream(filePath).pipe(res);
102
102
  return true;
103
103
  }
104
+ function serveShellIndex(req, res, bootstrap) {
105
+ const filePath = path.join(SHELL_DIR, 'index.html');
106
+ if (!fs.existsSync(filePath)) {
107
+ res.writeHead(404).end();
108
+ return true;
109
+ }
110
+ let html = fs.readFileSync(filePath, 'utf8');
111
+ if (bootstrap)
112
+ html = html.replace(/<head(\s[^>]*)?>/i, (head) => `${head}${bootstrap(req)}`);
113
+ res.writeHead(200, {
114
+ 'content-type': 'text/html; charset=utf-8',
115
+ 'cache-control': 'no-store',
116
+ });
117
+ res.end(html);
118
+ return true;
119
+ }
104
120
  // The split-view shell is served at the deck root `/` (the deck itself moves
105
121
  // into the iframe at `/index.html`); `/__castle/ide/<asset>` are the shell's
106
122
  // static assets; `/__castle/pty` is the PTY WebSocket (handled via a direct
@@ -1111,7 +1127,7 @@ export function createIdeServer(opts) {
1111
1127
  // The PTY is a root login shell — reject any upgrade that isn't same-origin (a
1112
1128
  // co-tenant reaching this port directly sends no browser Origin). Consumed either
1113
1129
  // way so a rejected upgrade never falls through to another handler.
1114
- if (!isSameOriginUpgrade(req)) {
1130
+ if (!isSameOriginUpgrade(req) || (opts.authorizeUpgrade && !opts.authorizeUpgrade(req, 'pty'))) {
1115
1131
  socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
1116
1132
  socket.destroy();
1117
1133
  return true;
@@ -1122,7 +1138,7 @@ export function createIdeServer(opts) {
1122
1138
  function handleHttpRequest(req, res, reqPath) {
1123
1139
  // `/` -> the shell's index.html; `/__castle/ide/<asset>` -> bundle assets.
1124
1140
  if (reqPath === '/')
1125
- return serveShellFile(res, 'index.html');
1141
+ return serveShellIndex(req, res, opts.shellBootstrap);
1126
1142
  // Root-served favicons, unless the deck ships its own (then fall through
1127
1143
  // to Vite, which serves the deck's file).
1128
1144
  const favicon = FAVICON_FILES.find((name) => reqPath === `/${name}`);
package/dist/imports.js CHANGED
@@ -5,6 +5,7 @@ import * as api from './api.js';
5
5
  import { runTar } from './save-deck.js';
6
6
  import { normalizeDeckPackageJson } from './normalize.js';
7
7
  import { getKitsDir } from './localPaths.js';
8
+ import { writePlatformDocs } from './platformDoc.js';
8
9
  import { ensureVisibleGlob, IMPORTS_DIR, readCastleJson as tryReadCastleJson, readCastleJsonOrThrow as readCastleJson, } from './castleJson.js';
9
10
  // Adding another deck as a dependency (`castle-web add-import`; removing one is a
10
11
  // later command). Deliberately NOT `get-deck`: that one
@@ -380,6 +381,23 @@ function backupImport(deckDir, alias) {
380
381
  fs.writeFileSync(path.join(dest, '.castle-import-pin.json'), JSON.stringify(pin, null, 2), 'utf-8');
381
382
  }
382
383
  }
384
+ // The docs-only kit a bare scaffold imports for its agent guide. A deck that
385
+ // adopts a real kit no longer has anything to say: leaving it would put two
386
+ // quick references in front of the agent every turn, one of them opening "No
387
+ // kit: nothing in this deck comes from a framework" about a deck that has one.
388
+ function dropBareDocsImport(deckDir, alias) {
389
+ const dir = path.join(deckDir, IMPORTS_DIR, alias);
390
+ if (fs.existsSync(dir)) {
391
+ unlockImportTree(dir);
392
+ fs.rmSync(dir, { recursive: true, force: true });
393
+ }
394
+ const existing = readCastleJson(deckDir);
395
+ if (!existing?.imports?.[alias])
396
+ return;
397
+ const imports = { ...existing.imports };
398
+ delete imports[alias];
399
+ fs.writeFileSync(path.join(deckDir, 'castle.json'), JSON.stringify({ ...existing, imports }, null, 2) + '\n', 'utf-8');
400
+ }
383
401
  async function placeImport(deckDir, alias, deckId, source, via) {
384
402
  const destDir = path.join(deckDir, IMPORTS_DIR, alias);
385
403
  const replaced = fs.existsSync(destDir);
@@ -493,10 +511,12 @@ export async function addImportTo(dir, options = {}) {
493
511
  const declaredMain = tryReadCastleJson(importDir)?.main;
494
512
  let adoptedMain = null;
495
513
  if (typeof declaredMain === 'string' && declaredMain.trim()) {
496
- const { isPristineBareDeck, adoptImportEntry, writeStarterScene, writeStarterTheme } = await import('./init.js');
514
+ const { isPristineBareDeck, adoptImportEntry, writeStarterScene, writeStarterTheme, retargetBareClaudeMd, BARE_DOCS_ALIAS, } = await import('./init.js');
497
515
  if (isPristineBareDeck(targetDir)) {
498
516
  adoptImportEntry(targetDir, alias, declaredMain.trim());
499
517
  adoptedMain = declaredMain.trim();
518
+ retargetBareClaudeMd(targetDir, alias);
519
+ dropBareDocsImport(targetDir, BARE_DOCS_ALIAS);
500
520
  // A kit's runtime with no scene to run is a blank screen, and the agent
501
521
  // has nothing to edit. Give the deck the kit's own starter, same as
502
522
  // `init --kit`. Only when the deck has no scenes -- never overwrite.
@@ -535,6 +555,9 @@ export async function addImportTo(dir, options = {}) {
535
555
  console.warn(`Imported ${alias}, but installing its dependencies failed -- run \`castle-web install\`. ${e instanceof Error ? e.message : String(e)}`);
536
556
  }
537
557
  }
558
+ // The platform guide's media list names the deck's declared types, which
559
+ // this import may have just changed.
560
+ writePlatformDocs(targetDir);
538
561
  const trimmedMain = typeof declaredMain === 'string' && declaredMain.trim() ? declaredMain.trim() : null;
539
562
  const offersMain = trimmedMain && !adoptedMain ? trimmedMain : null;
540
563
  return { deckId, alias, replaced, transitive, dependencies, adoptedMain, offersMain };
@@ -712,6 +735,7 @@ export async function updateImport(dir, options = {}) {
712
735
  for (const alias of aliases)
713
736
  revertImport(deckDir, alias);
714
737
  syncImportDependencies(deckDir);
738
+ writePlatformDocs(deckDir);
715
739
  return;
716
740
  }
717
741
  let changed = false;
@@ -749,6 +773,7 @@ export async function updateImport(dir, options = {}) {
749
773
  const added = syncImportDependencies(deckDir);
750
774
  for (const dep of added)
751
775
  console.log(`Added dependency ${dep}`);
776
+ writePlatformDocs(deckDir);
752
777
  console.log('Play the deck to check the update before saving; `--revert` puts the old version back.');
753
778
  }
754
779
  // Restore the copy taken when this import was last replaced.
package/dist/init.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export declare const BARE_DOCS_KIT = "blank";
2
+ export declare const BARE_DOCS_ALIAS = "castle.blank";
1
3
  export declare function resolveScaffoldRefs(): {
2
4
  workspaceMode: boolean;
3
5
  sdkRef: string;
@@ -5,11 +7,13 @@ export declare function resolveScaffoldRefs(): {
5
7
  cliDistAbs: string | null;
6
8
  sdkPathPosix: string | null;
7
9
  };
10
+ export declare function ensureAgentsSymlink(projectDir: string): void;
8
11
  export declare function isPristineBareDeck(dir: string): boolean;
9
12
  export declare function adoptImportEntry(deckDir: string, alias: string, mainFile: string): void;
10
13
  export declare function getCliVersion(): string;
11
14
  export declare function writeStarterScene(projectDir: string, kitDir: string, alias: string): void;
12
15
  export declare function writeStarterTheme(projectDir: string, kitDir: string): void;
16
+ export declare function retargetBareClaudeMd(deckDir: string, alias: string): void;
13
17
  export declare function init(dir: string, opts?: {
14
18
  kit?: string;
15
19
  serve?: boolean;
package/dist/init.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { COMMON_INSTRUCTIONS } from './commonInstructions.js';
3
+ import { CLAUDE_MD_PLATFORM_SECTION } from './platformDoc.js';
4
4
  import { installDeps } from './install.js';
5
5
  import { deckMainFile, deckStarterScene } from './castleJson.js';
6
6
  import { addImportTo, IMPORTS_DIR, lockImportTree, restoreMissingImports, syncImportDependencies, } from './imports.js';
7
7
  import { discardParentSource, fetchParentSource, unpackParentSource, writeRemixIdentity, } from './remix.js';
8
- import { getCliEntryPath, getKitsDir, getRepoRoot, getSdkPackagePath, toPosixPath, } from './localPaths.js';
8
+ import { getCliEntryPath, getKitsDir, getSdkPackagePath, toPosixPath, } from './localPaths.js';
9
9
  import { serve } from './serve.js';
10
10
  import { createVersion } from './versions.js';
11
11
  const INDEX_HTML = `<!DOCTYPE html>
@@ -36,13 +36,21 @@ card.appendChild(el);
36
36
  // Default kit imported by `init` when no --kit is given. `none`/`bare` skip the
37
37
  // kit and produce the minimal index.html + game.js stub above.
38
38
  const DEFAULT_KIT = 'physics-2d';
39
+ // A kit-less deck still imports ONE kit: a docs-only deck holding the guide to
40
+ // building without a framework. It is imported rather than written into the
41
+ // deck's own CLAUDE.md so it behaves like every other kit's guide -- the quick
42
+ // reference reaches the agent every turn, the rest is read on demand, and the
43
+ // text ships to existing decks via `autoUpdateWhenImported` instead of waiting
44
+ // for whatever CLI release the deck was scaffolded by.
45
+ export const BARE_DOCS_KIT = 'blank';
39
46
  // Registry version of castle-web-sdk to inject when scaffolding from a
40
47
  // globally-installed castle-web (not from inside the workspace). Bumped
41
48
  // alongside cli/sdk version bumps.
42
- const PUBLISHED_SDK_VERSION = '0.4.16';
49
+ const PUBLISHED_SDK_VERSION = '0.4.17';
43
50
  // The account the first-party kits are (to be) published under, so a kit
44
51
  // imported from the CLI's copy is named the same as one fetched from the server.
45
52
  const KIT_AUTHOR = 'castle';
53
+ export const BARE_DOCS_ALIAS = `${KIT_AUTHOR}.${BARE_DOCS_KIT}`;
46
54
  // Never copied into a deck's import: build/dependency junk.
47
55
  const KIT_COPY_EXCLUDE = new Set(['node_modules', '.castle', 'dist', '.git']);
48
56
  // The bare (`--kit none`) deck's default editor config: just the Files panel and
@@ -77,28 +85,15 @@ export function resolveScaffoldRefs() {
77
85
  sdkPathPosix,
78
86
  };
79
87
  }
80
- function makeClaudeMd() {
81
- // Inline the upstream CLAUDE.md content. An @-import works inside the
82
- // castle-experimental-web checkout, but breaks when the scaffold lives
83
- // outside the repo (the relative path no longer resolves).
84
- const repoRoot = getRepoRoot();
85
- const upstream = path.join(repoRoot, 'CLAUDE.md');
86
- try {
87
- return fs.readFileSync(upstream, 'utf8').trimEnd() + '\n';
88
- }
89
- catch {
90
- return `# Castle Experimental Web\n\nSee https://github.com/castle-xyz/castle-experimental-web for the agent guide.\n`;
91
- }
92
- }
93
- // Append the cli-owned common guidance to the deck's CLAUDE.md. Runs after
94
- // the kit's (or bare) CLAUDE.md is written; the AGENTS.md symlink picks the
95
- // appended content up for free.
96
- function appendCommonInstructions(projectDir) {
88
+ // Append the platform section -- the @import of the serve-written platform
89
+ // guide (platformDoc.ts) -- after the kit's (or bare) pointer is written. The
90
+ // AGENTS.md symlink picks it up for free.
91
+ function appendPlatformSection(projectDir) {
97
92
  const claudePath = path.join(projectDir, 'CLAUDE.md');
98
93
  const existing = fs.existsSync(claudePath)
99
94
  ? fs.readFileSync(claudePath, 'utf8').trimEnd() + '\n\n'
100
95
  : '';
101
- fs.writeFileSync(claudePath, existing + COMMON_INSTRUCTIONS);
96
+ fs.writeFileSync(claudePath, existing + CLAUDE_MD_PLATFORM_SECTION);
102
97
  }
103
98
  function tryMakeAgentsSymlink(agentsPath) {
104
99
  try {
@@ -143,7 +138,7 @@ function makePackageJson(projectDir) {
143
138
  }
144
139
  // Some coding agents read AGENTS.md by convention. Symlink so they get the
145
140
  // same guidance without a duplicate copy.
146
- function ensureAgentsSymlink(projectDir) {
141
+ export function ensureAgentsSymlink(projectDir) {
147
142
  const agentsPath = path.join(projectDir, 'AGENTS.md');
148
143
  if (fs.lstatSync(agentsPath, { throwIfNoEntry: false }))
149
144
  return;
@@ -182,11 +177,16 @@ function scaffoldBare(projectDir) {
182
177
  fs.mkdirSync(projectDir, { recursive: true });
183
178
  fs.writeFileSync(path.join(projectDir, 'index.html'), INDEX_HTML);
184
179
  fs.writeFileSync(path.join(projectDir, 'game.js'), GAME_JS);
185
- fs.writeFileSync(path.join(projectDir, 'castle.json'), JSON.stringify(BARE_CASTLE_JSON, null, 2) + '\n');
186
- fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), makeClaudeMd());
187
- appendCommonInstructions(projectDir);
180
+ const pins = {};
181
+ copyKitImport(projectDir, requireKitDir(BARE_DOCS_KIT), BARE_DOCS_KIT, BARE_DOCS_ALIAS, pins, new Map());
182
+ writeJsonFile(path.join(projectDir, 'castle.json'), { ...BARE_CASTLE_JSON, imports: pins });
183
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), makeBareClaudeMd(BARE_DOCS_ALIAS));
184
+ appendPlatformSection(projectDir);
188
185
  ensureAgentsSymlink(projectDir);
189
186
  fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify(makePackageJson(projectDir), null, 2) + '\n');
187
+ // The docs kit declares no dependencies, so unlike a real kit's import there
188
+ // is nothing to merge into package.json before the install.
189
+ lockImportTree(path.join(projectDir, IMPORTS_DIR, BARE_DOCS_ALIAS));
190
190
  }
191
191
  // Copy a framework kit from kits/<kit>/ into the new deck dir, dropping
192
192
  // build/dependency junk and castle.json.
@@ -295,6 +295,24 @@ export function writeStarterTheme(projectDir, kitDir) {
295
295
  return;
296
296
  fs.copyFileSync(src, dest);
297
297
  }
298
+ function makeBareClaudeMd(alias) {
299
+ return `# Castle deck (no kit)
300
+
301
+ This deck is a normal browser project: \`index.html\` loads \`game.js\` as an ES
302
+ module, \`package.json\` holds its scripts and any npm package it adds, and
303
+ \`castle.json\` is its editor config. Nothing here comes from a framework -- there
304
+ is no scene, behavior, sprite, or level format unless this deck defines one, and
305
+ no editor other than the code editor unless this deck builds one. Everything it
306
+ renders, it renders itself: DOM, canvas, WebGL, React, Pixi, Three, WebAssembly,
307
+ whatever the web offers.
308
+
309
+ Read \`${IMPORTS_DIR}/${alias}/CLAUDE.md\` for the authoring guide: the deck's
310
+ file layout, the Castle SDK, and how to give a file type an editor of its own.
311
+
312
+ Do not edit anything under \`${IMPORTS_DIR}/\`: those files belong to the deck they
313
+ came from, and are replaced wholesale when the import is updated.
314
+ `;
315
+ }
298
316
  function makeImportedKitClaudeMd(alias) {
299
317
  return `# Castle deck
300
318
 
@@ -312,6 +330,24 @@ something in the kit behaves, define your own behavior of the same name in
312
330
  \`behaviors/\` -- the deck's own files win over an import's.
313
331
  `;
314
332
  }
333
+ // A bare deck's CLAUDE.md points at the docs kit, which adopting a real kit is
334
+ // about to remove. Rewrite it to point at the kit that is now mounted -- but
335
+ // only while the file is still byte-for-byte what the scaffold wrote, since
336
+ // `isPristineBareDeck` answers for the entry point and says nothing about
337
+ // whatever the creator may have written here.
338
+ export function retargetBareClaudeMd(deckDir, alias) {
339
+ const claudePath = path.join(deckDir, 'CLAUDE.md');
340
+ const scaffolded = makeBareClaudeMd(BARE_DOCS_ALIAS).trimEnd() + '\n\n' + CLAUDE_MD_PLATFORM_SECTION;
341
+ try {
342
+ if (fs.readFileSync(claudePath, 'utf8') !== scaffolded)
343
+ return;
344
+ }
345
+ catch {
346
+ return;
347
+ }
348
+ fs.writeFileSync(claudePath, makeImportedKitClaudeMd(alias));
349
+ appendPlatformSection(deckDir);
350
+ }
315
351
  // How the deck names the kit it was built on. `scripts/publish-kits.mjs` stamps
316
352
  // a published kit's castle.json with the deckId it lives at and the version it
317
353
  // was published as, and both have to be present to pin it that way: a deckId
@@ -445,7 +481,8 @@ function scaffoldFromKitImport(kit, projectDir) {
445
481
  dependencies,
446
482
  });
447
483
  fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), makeImportedKitClaudeMd(alias));
448
- appendCommonInstructions(projectDir);
484
+ appendPlatformSection(projectDir);
485
+ ensureAgentsSymlink(projectDir);
449
486
  for (const importedAlias of copied.keys()) {
450
487
  lockImportTree(path.join(projectDir, IMPORTS_DIR, importedAlias));
451
488
  }
package/dist/install.js CHANGED
@@ -2,6 +2,7 @@ import { execSync, spawn } from 'child_process';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import { restoreMissingImports, syncImportDependencies } from './imports.js';
5
+ import { writePlatformDocs } from './platformDoc.js';
5
6
  function hasPnpm() {
6
7
  try {
7
8
  execSync('pnpm --version', { stdio: 'ignore' });
@@ -67,6 +68,9 @@ export async function install(dir) {
67
68
  const restored = await restoreMissingImports(projectDir);
68
69
  for (const alias of restored)
69
70
  console.log(`Restored import ${alias}`);
71
+ // A fetched deck's CLAUDE.md already @imports the platform guide; write it
72
+ // now rather than leaving the reference dangling until the first serve.
73
+ writePlatformDocs(projectDir);
70
74
  // Imports declare packages the deck has to install (see syncImportDependencies).
71
75
  // Re-done here, not just at add-import time, so a deck fetched with get-deck --
72
76
  // which brings castle.json's pins but not the dependency files -- still ends up
@@ -0,0 +1,12 @@
1
+ export declare const PLATFORM_DOCS_DIR: string;
2
+ export declare const PLATFORM_DOC_REL: string;
3
+ export declare function everyDeckBullets(deckDir: string): string[];
4
+ export declare const PLATFORM_SECTION_HEADING = "### from the Castle platform (every deck)";
5
+ export declare function platformSection(deckDir: string): string;
6
+ export declare function quickReferenceFor(deckDir: string, quickReference: string, backend: 'claude' | 'cursor' | 'smith'): string;
7
+ export declare function platformGuide(deckDir: string): string;
8
+ export declare function writePlatformDocs(deckDir: string): void;
9
+ export declare const CLAUDE_MD_IMPORT_LINE: string;
10
+ export declare const CLAUDE_MD_PLATFORM_SECTION: string;
11
+ export type ClaudeMdMigration = 'absent' | 'current' | 'migrated' | 'added' | 'kept' | 'gated';
12
+ export declare function migrateClaudeMd(deckDir: string): ClaudeMdMigration;