castle-web-cli 0.4.203 → 0.4.204

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.
@@ -87,6 +87,7 @@ export interface RouterPromptOpts {
87
87
  tasks: PromptTask[];
88
88
  plan?: RouterPlanOpts;
89
89
  playtest?: boolean;
90
+ askCalls?: boolean;
90
91
  editorTabs?: string[];
91
92
  paramsWrites?: string[];
92
93
  instruction: string;
@@ -96,6 +96,14 @@ Conversation style:
96
96
  - Spawning a task does NOT apply the change -- tasks run for minutes and finish on the board. Talk about spawned work in future tense ("this will dial the shake back"), and NEVER ask how a change feels right after spawning it -- the user cannot have tried it yet. Save "how is it?" for things whose task already finished.
97
97
  - The user playtests in the pane beside this chat; finished work shows up there after a reload.`;
98
98
  }
99
+ const SPEC_RULE = `- CLEAR SPEC (mechanics named, a reference given, "like X but Y"): the gaps are closed. Build what they said; never probe taste they already expressed.`;
100
+ const PROBE_CAP_RULE = `- At most ONE probe open at a time; none on spec, delegation, or conversation turns; never re-probe something answered. Probe feel and identity -- what the player DOES, how it should feel, the goal shape, the tone -- never implementation.`;
101
+ // The q-a2 router arm (prompt-evals t1-router-ladder arms/q-a2.ts), for the
102
+ // decks that opted in (`agent.askCalls` / CASTLE_AGENT_ASK_CALLS -- see
103
+ // askCallsEnabled in agent.ts). Off for everyone by default, so the plan rules
104
+ // stay byte-identical to a prompt built before it existed.
105
+ const ASK_CALLS_SPEC_RULE = `- CLEAR SPEC (mechanics named, a reference given, "like X but Y"): build what they said; never probe taste they already expressed.`;
106
+ const ASK_CALLS_PROBE_CAP_RULE = `- At most ONE probe open at a time; none on delegation or conversation turns; never re-probe something answered. Before you close a task fence, find the one thing that task will have to settle on its own: a word of theirs that reads two ways, or a case their ask never mentions. Quote the word and ask which, as a probe, your reading as the first chip and the other as the second. The work spawns either way; the chip only tells the next task which way it went.`;
99
107
  // Appended to the rules above for a deck with the plan doc on -- see
100
108
  // planSession in agent.ts for which decks those are. One self-contained block,
101
109
  // so a deck without it gets the pre-plan prompt byte for byte.
@@ -104,8 +112,9 @@ Conversation style:
104
112
  // deliberately supersede rules in the block above (pairing a question with
105
113
  // task directives, and holding follow-up questions back), which is why they say
106
114
  // so out loud rather than quietly contradicting them.
107
- const PLAN_RULES = `Reading the user, fresh from EACH message -- the same user hands you a spec, then a fragment, then delegates:
108
- - CLEAR SPEC (mechanics named, a reference given, "like X but Y"): the gaps are closed. Build what they said; never probe taste they already expressed.
115
+ function planRules(askCalls) {
116
+ return `Reading the user, fresh from EACH message -- the same user hands you a spec, then a fragment, then delegates:
117
+ ${askCalls ? ASK_CALLS_SPEC_RULE : SPEC_RULE}
109
118
  - FRAGMENT ("something with ants", "a cozy game about tea?"): gaps they cannot name yet. Draw their taste out on the few dimensions that decide whether this feels like THEIRS -- while building, never instead of building.
110
119
  - A fragment is not only a whole-game ask. "how about some obstacles?", "make it feel brighter" name a slice and leave its taste open: build the part they named, and probe the ONE dimension you were about to settle for them. Deciding it silently is how a deck becomes yours instead of theirs.
111
120
  - A build turn that was going to carry NO question at all is where a feel question belongs, and on a deck already underway most turns are that: they name a change, you make it, nothing is asked, and the feel of it was yours by default. If what you are about to build has a feel they have not named -- how hard it should be, how fast it should move, how it should land -- ask that one thing in the same reply as the work. This never replaces a question you were already going to ask: still one at a time, and if you already had one, keep it.
@@ -119,7 +128,7 @@ Probing while you build. A probe is one short plain question plus 2-4 tappable o
119
128
 
120
129
  - Tapping one sends its text as the user's next message; they can ignore it and type anything else, and the build continues either way. Never phrase a probe as if an answer were required.
121
130
  - Spawn the work the answer cannot invalidate AND attach the probe in the same reply -- this supersedes the rules above against pairing a question with task directives. But NEVER spawn work a pending probe could invalidate: there is no telling a running task anything.
122
- - At most ONE probe open at a time; none on spec, delegation, or conversation turns; never re-probe something answered. Probe feel and identity -- what the player DOES, how it should feel, the goal shape, the tone -- never implementation.
131
+ ${askCalls ? ASK_CALLS_PROBE_CAP_RULE : PROBE_CAP_RULE}
123
132
  - Chips NEVER stand on their own: a probe's question is the line right before them, and a probe is the only thing they are for. Alone they read as answers to a question nobody asked.
124
133
  - Praise is where the pull to offer something is strongest and most wrong: "oh nice, that works great" gets one plain sentence and nothing else. Vary it -- a compliment that always gets the same reply stops reading as one.
125
134
 
@@ -153,9 +162,10 @@ now- food-hauling
153
162
  Promotion. Finished tasks leave notes worth keeping, listed above with the id of the task that left each. Promote the keepers by quoting the note itself and citing its task; let the rest go -- they are offered once.
154
163
 
155
164
  If the user asks you to ease off the questions or the plan upkeep, record that with a \`decide+\` quoting the ask, and honor it -- keep \`## Now\` current, quietly.`;
156
- function routerRules(plan, playtest) {
165
+ }
166
+ function routerRules(plan, playtest, askCalls) {
157
167
  const base = baseRouterRules(playtest);
158
- return plan ? `${base}\n\n${PLAN_RULES}` : base;
168
+ return plan ? `${base}\n\n${planRules(askCalls)}` : base;
159
169
  }
160
170
  function renderTranscriptLine(m) {
161
171
  if (m.role === "user")
@@ -862,7 +872,7 @@ export function buildRouterPromptParts(opts) {
862
872
  // does not. `user` holds what changes every turn: the transcript, the plan,
863
873
  // the board and this instruction.
864
874
  return {
865
- system: `${routerRules(opts.plan !== undefined, opts.playtest === true)}
875
+ system: `${routerRules(opts.plan !== undefined, opts.playtest === true, opts.askCalls === true)}
866
876
 
867
877
  == deck ==
868
878
  ${opts.deckLabel}${quickReference}${editorTabs}${deckFiles}`,
@@ -1011,7 +1021,8 @@ phase: wiring the paddle to touch
1011
1021
 
1012
1022
  - \`avatar\` -- what you're doing RIGHT NOW, exactly one of: \`thinking\` (figuring out the plan), \`reading\` (looking through files), \`building\` (writing game logic), \`painting\` (making or editing art/visuals), \`playing\` (trying it in the game).
1013
1023
  - \`phase\` -- a SHORT, plain-language line for this moment ("wiring the paddle to touch", "drawing the flag"). No file or code names. Update \`avatar\` and \`phase\` together each time your stage changes -- a few times across the task, not every turn. (You may also include \`progress: NN\` here, but the progress file above is the primary progress channel.)
1014
- - Before finishing, write ${opts.notesPath}: a tiny test guide for the PLAYER -- AT MOST 2-3 bullets (markdown \`- \` lines), each ONE short phrase: what to try and what should happen. NO code, NO API or "integration contract" detail, and no tour of how you built it -- that part is for you, not them. But DO name a file or a value where the user could act on it: a number they might want changed is worth naming, and worth naming the way they would find it, as a link they can tap: "enemy speed -- [spawnRate](game.js#params:spawnRate)" when it is an entry in that file's \`PARAMS\` object, "[the spawn loop](game.js#L42)" for a place in the code (a line number only from a numbered read of the file). Occasionally one bullet may run a little longer, but default to terse. Mention a blocker only if you hit one. The user reads this verbatim to check your work.${wrapUp}
1024
+ - Before finishing, write ${opts.notesPath}: a tiny test guide for the PLAYER -- AT MOST 2-3 bullets (markdown \`- \` lines), each ONE short phrase: what to try and what should happen. NO code, NO API or "integration contract" detail, and no tour of how you built it -- that part is for you, not them. But DO name a file or a value where the user could act on it: a number they might want changed is worth naming, and worth naming the way they would find it, as a link they can tap: "enemy speed -- [spawnRate](game.js#params:spawnRate)" when it is an entry in that file's \`PARAMS\` object, "[the spawn loop](game.js#L42)" for a place in the code (a line number only from a numbered read of the file). Occasionally one bullet may run a little longer, but default to terse. Mention a blocker only if you hit one. The user reads this verbatim to check your work.
1025
+ - Your final message -- the text after your wrap-up call -- is shown to the user under those notes once the task ends. It is the record of what you did for someone who did not watch the stream, so make it a short plain account: what changed and where (files as tappable links, the same forms as above), the mechanism you chose and why, and any call you made where the brief left a choice. A few sentences or a few short bullets. No signal block, no list of the steps you ran, and do not restate the notes.${wrapUp}
1015
1026
  - If you are truly blocked, write the blocker to the notes file and stop rather than guessing wildly.
1016
1027
  - Never touch files under .castle/ other than ${opts.plan ? "those three paths" : "those two paths"}. (The version store lives there too, but you never edit it by hand -- \`castle-web save-version\` writes it for you.)`;
1017
1028
  }
package/dist/agent.d.ts CHANGED
@@ -46,6 +46,7 @@ interface TaskRecord {
46
46
  originMessageId?: string;
47
47
  playtestFrames?: string[];
48
48
  resultSummary?: string;
49
+ account?: string;
49
50
  errorCopy?: string;
50
51
  errorDetail?: string;
51
52
  avatar?: string;
@@ -67,6 +68,7 @@ interface TaskRecord {
67
68
  usage?: TaskUsage;
68
69
  modelUsage?: Record<string, TaskModelUsage>;
69
70
  }
71
+ export declare function askCallsEnabled(deckDir: string): boolean;
70
72
  export interface DepsState {
71
73
  kind: 'ready' | 'waiting' | 'blocked';
72
74
  blockedBy?: string[];
package/dist/agent.js CHANGED
@@ -27,6 +27,8 @@ import * as path from 'path';
27
27
  import { nanoid } from 'nanoid';
28
28
  import { WebSocketServer } from 'ws';
29
29
  import { rawDataToString } from './rawData.js';
30
+ import { extractDirectives, meansAll, parseTaskFenceBody, resolveTargets, taskFenceRegex, } from './routerFences.js';
31
+ import { accountForRun, closingMessageOf } from './taskAccount.js';
30
32
  import { atomicWriteFileSync } from './atomicFile.js';
31
33
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
32
34
  import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, planOpenQuestionLines, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
@@ -528,90 +530,6 @@ function visibleLength(raw) {
528
530
  }
529
531
  return raw.length;
530
532
  }
531
- // Parse one ```castle-task fence's body (title line, optional "after:" and
532
- // "item:" lines in either order, then the prompt) into a directive. Shared by
533
- // the settle-time full-text extraction below and the mid-stream incremental
534
- // scanner (runRouterTurnIn), so a fence spawned early behaves identically to
535
- // one spawned at settle.
536
- function parseTaskFenceBody(body) {
537
- const lines = body.replace(/\r/g, '').split('\n');
538
- const title = (lines.shift() ?? '').trim();
539
- if (!title)
540
- return null;
541
- const after = [];
542
- let item;
543
- while (lines.length > 0) {
544
- const headerMatch = /^(after|item):\s*(.*)$/i.exec((lines[0] ?? '').trim());
545
- if (!headerMatch)
546
- break;
547
- lines.shift();
548
- if (headerMatch[1].toLowerCase() === 'item') {
549
- const label = headerMatch[2].trim();
550
- // `item: -` is the fence saying "chore, no plan item" -- an answer, not
551
- // an omission, so it lands the same as no line at all.
552
- if (label && label !== '-')
553
- item = label;
554
- continue;
555
- }
556
- after.push(...headerMatch[2]
557
- .split(',')
558
- .map((s) => s.trim())
559
- .filter(Boolean));
560
- }
561
- return { title, after, item, prompt: lines.join('\n').trim() };
562
- }
563
- // A fresh RegExp per call -- this is matched with manual .exec() loops in
564
- // TWO independent call sites (settle-time extractDirectives via .replace, and
565
- // the mid-stream scanNewTaskFences via a lastIndex-seeded loop) that must
566
- // never share mutable lastIndex state.
567
- function taskFenceRegex() {
568
- return /```castle-task[ \t]*\r?\n([\s\S]*?)```/g;
569
- }
570
- // Take the body of a ```castle-plan fence out of a router reply: the ops it
571
- // wants applied to plan.md. A reply emitting more than one is stating more ops,
572
- // so the bodies concatenate in order. Returns the reply with every such fence
573
- // removed.
574
- function takePlanFence(source) {
575
- const bodies = [];
576
- const rest = source.replace(/```castle-plan[ \t]*\r?\n([\s\S]*?)```/g, (_match, body) => {
577
- bodies.push(String(body));
578
- return '';
579
- });
580
- return { plan: bodies.length > 0 ? bodies.join('\n') : undefined, rest };
581
- }
582
- // Pull ```castle-task fenced directives out of a finished router reply.
583
- // Block format: title line, then an optional "after:" line, then the prompt.
584
- function extractDirectives(full) {
585
- const directives = [];
586
- const checkoffs = [];
587
- const stops = [];
588
- const listFence = (source, name, into) => {
589
- const re = new RegExp('```' + name + '[ \\t]*\\r?\\n([\\s\\S]*?)```', 'g');
590
- return source.replace(re, (_match, body) => {
591
- for (const token of String(body).split(/[,\n]/)) {
592
- const trimmed = token.trim();
593
- if (trimmed)
594
- into.push(trimmed);
595
- }
596
- return '';
597
- });
598
- };
599
- const { plan, rest } = takePlanFence(full);
600
- const withoutDone = listFence(listFence(rest, 'castle-done', checkoffs), 'castle-stop', stops);
601
- const cleaned = withoutDone.replace(taskFenceRegex(), (_match, body) => {
602
- const directive = parseTaskFenceBody(String(body));
603
- if (directive)
604
- directives.push(directive);
605
- return '';
606
- });
607
- return {
608
- cleaned: cleaned.replace(/\n{3,}/g, '\n\n').trim(),
609
- directives,
610
- checkoffs,
611
- stops,
612
- plan,
613
- };
614
- }
615
533
  const planSessions = new Map();
616
534
  // What a deck that says nothing gets. On unless the serve was explicitly told
617
535
  // otherwise -- `CASTLE_AGENT_PLAN=off` is what the agent-qa harness uses to keep
@@ -640,6 +558,23 @@ function planSession(deckDir) {
640
558
  planSessions.set(deckDir, session);
641
559
  return session;
642
560
  }
561
+ const askCallsSessions = new Map();
562
+ // The inverse of planDefault: dormant until someone asks for it.
563
+ function askCallsDefault() {
564
+ return process.env.CASTLE_AGENT_ASK_CALLS === 'on';
565
+ }
566
+ // Resolved once per deck and cached for the reason planSession is: it decides
567
+ // what sits in the prompt's cached prefix, so honoring a mid-session change
568
+ // would split the prompt cache. Changing it takes a serve restart.
569
+ export function askCallsEnabled(deckDir) {
570
+ const cached = askCallsSessions.get(deckDir);
571
+ if (cached !== undefined)
572
+ return cached;
573
+ const declared = readCastleJson(deckDir)?.agent?.askCalls;
574
+ const enabled = declared === 'on' ? true : declared === 'off' ? false : askCallsDefault();
575
+ askCallsSessions.set(deckDir, enabled);
576
+ return enabled;
577
+ }
643
578
  function readPlanSnapshot(deckDir) {
644
579
  let raw;
645
580
  try {
@@ -1118,6 +1053,7 @@ function createAgentStreamState() {
1118
1053
  return {
1119
1054
  accumulated: '',
1120
1055
  finalText: '',
1056
+ finalTextFromResult: false,
1121
1057
  resultIsError: false,
1122
1058
  usage: undefined,
1123
1059
  stats: undefined,
@@ -1304,7 +1240,9 @@ function makeAgentEventHandler(opts, state) {
1304
1240
  // return their blocks as `text, thinking` (gemini through OpenRouter's
1305
1241
  // anthropic-compatible endpoint) end the turn on an empty thinking block,
1306
1242
  // and the CLI reports `result: ""` even though the answer streamed fine.
1307
- state.finalText = typeof ev.result === 'string' && ev.result ? ev.result : state.accumulated;
1243
+ const closing = closingMessageOf(ev.result, state.accumulated);
1244
+ state.finalText = closing.finalText;
1245
+ state.finalTextFromResult = closing.fromResult;
1308
1246
  state.resultIsError = ev.is_error === true;
1309
1247
  state.usage = parseCliUsage(ev.usage);
1310
1248
  state.stats = parseCliRunStats(ev);
@@ -1499,6 +1437,7 @@ function runAgentCli(opts) {
1499
1437
  settle({
1500
1438
  ok,
1501
1439
  finalText: state.finalText || state.accumulated,
1440
+ finalTextFromResult: state.finalTextFromResult,
1502
1441
  usage: state.usage,
1503
1442
  stats: state.stats,
1504
1443
  crashed: !state.sawResult,
@@ -1934,7 +1873,7 @@ function writeTaskIndex(tasksDir, tasks) {
1934
1873
  // board (blockedBy intact) until the router stops it, same as before restart.
1935
1874
  const TASK_STATUSES = ['waiting', 'running', 'blocked', 'done', 'failed', 'interrupted'];
1936
1875
  const TASK_OPTIONAL_STRINGS = [
1937
- 'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'errorCopy',
1876
+ 'item', 'startedAt', 'finishedAt', 'originMessageId', 'resultSummary', 'account', 'errorCopy',
1938
1877
  'errorDetail', 'avatar', 'phase', 'durable', 'what', 'model', 'backend',
1939
1878
  ];
1940
1879
  const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns'];
@@ -2106,24 +2045,6 @@ function refreshTaskFiles(tasksDir, task) {
2106
2045
  changed = true;
2107
2046
  return changed;
2108
2047
  }
2109
- // "after:" entries may reference task ids or titles -- including titles of
2110
- // tasks spawned earlier in the same reply (spawn order follows block order).
2111
- function resolveDeps(tasks, tokens) {
2112
- const resolved = [];
2113
- for (const token of tokens) {
2114
- if (tasks.has(token)) {
2115
- resolved.push(token);
2116
- continue;
2117
- }
2118
- const byTitle = [...tasks.values()]
2119
- .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
2120
- .filter((t) => t.title.toLowerCase() === token.toLowerCase());
2121
- const last = byTitle[byTitle.length - 1];
2122
- if (last)
2123
- resolved.push(last.id);
2124
- }
2125
- return [...new Set(resolved)];
2126
- }
2127
2048
  export function classifyDeps(tasks, task) {
2128
2049
  const blockedBy = [];
2129
2050
  let waiting = false;
@@ -2399,6 +2320,12 @@ function startTask(ctx, task) {
2399
2320
  : result.ok
2400
2321
  ? result.finalText.slice(-RESULT_SUMMARY_CHARS)
2401
2322
  : `${result.error ?? 'failed'}\n${result.finalText.slice(-RESULT_SUMMARY_CHARS)}`;
2323
+ task.account = accountForRun({
2324
+ ok: result.ok,
2325
+ stopped: wasStopped,
2326
+ finalText: result.finalText,
2327
+ finalTextFromResult: result.finalTextFromResult === true,
2328
+ });
2402
2329
  if (!wasStopped && !result.ok) {
2403
2330
  const failure = resolveFailure(result);
2404
2331
  // spawnedTasks/willRetry are router-turn concepts; a task card has
@@ -2567,7 +2494,7 @@ function createTaskStore(opts) {
2567
2494
  id: nanoid(8),
2568
2495
  title: directive.title,
2569
2496
  prompt: directive.prompt,
2570
- after: resolveDeps(tasks, directive.after),
2497
+ after: resolveTargets(tasks, directive.after),
2571
2498
  item: directive.item,
2572
2499
  status: 'waiting',
2573
2500
  progress: 0,
@@ -2628,17 +2555,12 @@ function createTaskStore(opts) {
2628
2555
  }
2629
2556
  writeTaskIndex(tasksDir, tasks);
2630
2557
  }
2631
- // True when a fence body is the special token "all" / "*" (clear/stop
2632
- // everything, no per-task enumeration).
2633
- function meansAll(tokens) {
2634
- return tokens.some((t) => t.toLowerCase() === 'all' || t === '*');
2635
- }
2636
2558
  // The router checks finished tasks off by title or id (castle-done fence),
2637
2559
  // or "all" to clear every finished row off the board at once.
2638
2560
  function checkOff(tokens) {
2639
2561
  const ids = meansAll(tokens)
2640
2562
  ? [...tasks.values()].filter((t) => isTerminal(t.status) && !t.acknowledged).map((t) => t.id)
2641
- : resolveDeps(tasks, tokens);
2563
+ : resolveTargets(tasks, tokens);
2642
2564
  for (const id of ids)
2643
2565
  acknowledge(id, false);
2644
2566
  }
@@ -2652,7 +2574,7 @@ function createTaskStore(opts) {
2652
2574
  ? [...tasks.values()]
2653
2575
  .filter((t) => t.status === 'running' || t.status === 'waiting' || t.status === 'blocked')
2654
2576
  .map((t) => t.id)
2655
- : resolveDeps(tasks, tokens);
2577
+ : resolveTargets(tasks, tokens);
2656
2578
  for (const id of ids) {
2657
2579
  const task = tasks.get(id);
2658
2580
  if (task)
@@ -2860,6 +2782,7 @@ function asClientTask(task, signPath) {
2860
2782
  startedAt: task.startedAt,
2861
2783
  finishedAt: task.finishedAt,
2862
2784
  resultSummary: task.resultSummary,
2785
+ account: task.account,
2863
2786
  avatar: task.avatar,
2864
2787
  phase: task.phase,
2865
2788
  acknowledged: task.acknowledged,
@@ -3088,6 +3011,7 @@ function routerTurnPrompt(ctx, instruction, selfMessageId, plan) {
3088
3011
  editorTabs: editorTabsFor(ctx.deckDir),
3089
3012
  deckTree: buildDeckTree(ctx.deckDir),
3090
3013
  playtest: playtestSteering(),
3014
+ askCalls: askCallsEnabled(ctx.deckDir),
3091
3015
  messages: ctx.log.messages
3092
3016
  .filter((m) => m.role !== 'log' && m.id !== selfMessageId && m.status !== 'streaming')
3093
3017
  .map((m) => ({
@@ -4012,9 +3936,10 @@ export function createAgentServer(opts) {
4012
3936
  const attachmentsDir = path.join(agentDir, 'attachments');
4013
3937
  const messagesPath = path.join(agentDir, 'messages.json');
4014
3938
  fs.mkdirSync(tasksDir, { recursive: true });
4015
- // Read the plan opt-out now so the whole serve shares one answer -- see
4016
- // planSession.
3939
+ // Read the prompt switches this deck declares now, so the whole serve shares
3940
+ // one answer for each -- see planSession and askCallsEnabled.
4017
3941
  planSession(deckDir);
3942
+ askCallsEnabled(deckDir);
4018
3943
  // Warm the OpenRouter catalog now so the first pre-flight and the first
4019
3944
  // popover open read a cache instead of paying for the fetch. Fire-and-forget
4020
3945
  // by design -- nothing here depends on it, and it falls open if it fails.
@@ -4144,7 +4069,7 @@ export function createAgentServer(opts) {
4144
4069
  function handleTaskAck(id, rejected) {
4145
4070
  taskStore.acknowledge(id, rejected);
4146
4071
  }
4147
- // `after` goes through the same resolveDeps the router's fences use, so a
4072
+ // `after` goes through the same resolveTargets the router's fences use, so a
4148
4073
  // caller may name an upstream by id or by title and gets the real dependency
4149
4074
  // path -- waiting, blocked, and the upstream summaries in the task prompt.
4150
4075
  function handleSpawnTask(socket, msg) {
@@ -20,6 +20,7 @@ export interface CastleJson {
20
20
  main?: string;
21
21
  agent?: {
22
22
  plan?: 'on' | 'off';
23
+ askCalls?: 'on' | 'off';
23
24
  };
24
25
  server?: {
25
26
  main?: string;
@@ -0,0 +1,22 @@
1
+ export interface TaskDirective {
2
+ title: string;
3
+ after: string[];
4
+ item?: string;
5
+ prompt: string;
6
+ }
7
+ export interface BoardTask {
8
+ id: string;
9
+ title: string;
10
+ createdAt: string;
11
+ }
12
+ export declare function parseTaskFenceBody(body: string): TaskDirective | null;
13
+ export declare function taskFenceRegex(): RegExp;
14
+ export declare function extractDirectives(full: string): {
15
+ cleaned: string;
16
+ directives: TaskDirective[];
17
+ checkoffs: string[];
18
+ stops: string[];
19
+ plan?: string;
20
+ };
21
+ export declare function meansAll(lines: string[]): boolean;
22
+ export declare function resolveTargets<T extends BoardTask>(tasks: Map<string, T>, lines: string[]): string[];
@@ -0,0 +1,139 @@
1
+ // Parse one ```castle-task fence's body (title line, optional "after:" and
2
+ // "item:" lines in either order, then the prompt) into a directive. Shared by
3
+ // the settle-time full-text extraction below and the mid-stream incremental
4
+ // scanner (runRouterTurnIn), so a fence spawned early behaves identically to
5
+ // one spawned at settle.
6
+ export function parseTaskFenceBody(body) {
7
+ const lines = body.replace(/\r/g, '').split('\n');
8
+ const title = (lines.shift() ?? '').trim();
9
+ if (!title)
10
+ return null;
11
+ const after = [];
12
+ let item;
13
+ while (lines.length > 0) {
14
+ const headerMatch = /^(after|item):\s*(.*)$/i.exec((lines[0] ?? '').trim());
15
+ if (!headerMatch)
16
+ break;
17
+ lines.shift();
18
+ if (headerMatch[1].toLowerCase() === 'item') {
19
+ const label = headerMatch[2].trim();
20
+ // `item: -` is the fence saying "chore, no plan item" -- an answer, not
21
+ // an omission, so it lands the same as no line at all.
22
+ if (label && label !== '-')
23
+ item = label;
24
+ continue;
25
+ }
26
+ const line = headerMatch[2].trim();
27
+ if (line)
28
+ after.push(line);
29
+ }
30
+ return { title, after, item, prompt: lines.join('\n').trim() };
31
+ }
32
+ // A fresh RegExp per call -- this is matched with manual .exec() loops in
33
+ // TWO independent call sites (settle-time extractDirectives via .replace, and
34
+ // the mid-stream scanNewTaskFences via a lastIndex-seeded loop) that must
35
+ // never share mutable lastIndex state.
36
+ export function taskFenceRegex() {
37
+ return /```castle-task[ \t]*\r?\n([\s\S]*?)```/g;
38
+ }
39
+ // Take the body of a ```castle-plan fence out of a router reply: the ops it
40
+ // wants applied to plan.md. A reply emitting more than one is stating more ops,
41
+ // so the bodies concatenate in order. Returns the reply with every such fence
42
+ // removed.
43
+ function takePlanFence(source) {
44
+ const bodies = [];
45
+ const rest = source.replace(/```castle-plan[ \t]*\r?\n([\s\S]*?)```/g, (_match, body) => {
46
+ bodies.push(String(body));
47
+ return '';
48
+ });
49
+ return { plan: bodies.length > 0 ? bodies.join('\n') : undefined, rest };
50
+ }
51
+ // Pull ```castle-task fenced directives out of a finished router reply.
52
+ // Block format: title line, then an optional "after:" line, then the prompt.
53
+ // castle-done / castle-stop bodies come back one entry per line, still
54
+ // comma-joined -- see resolveTargets.
55
+ export function extractDirectives(full) {
56
+ const directives = [];
57
+ const checkoffs = [];
58
+ const stops = [];
59
+ const listFence = (source, name, into) => {
60
+ const re = new RegExp('```' + name + '[ \\t]*\\r?\\n([\\s\\S]*?)```', 'g');
61
+ return source.replace(re, (_match, body) => {
62
+ for (const line of String(body).split('\n')) {
63
+ const trimmed = line.trim();
64
+ if (trimmed)
65
+ into.push(trimmed);
66
+ }
67
+ return '';
68
+ });
69
+ };
70
+ const { plan, rest } = takePlanFence(full);
71
+ const withoutDone = listFence(listFence(rest, 'castle-done', checkoffs), 'castle-stop', stops);
72
+ const cleaned = withoutDone.replace(taskFenceRegex(), (_match, body) => {
73
+ const directive = parseTaskFenceBody(String(body));
74
+ if (directive)
75
+ directives.push(directive);
76
+ return '';
77
+ });
78
+ return {
79
+ cleaned: cleaned.replace(/\n{3,}/g, '\n\n').trim(),
80
+ directives,
81
+ checkoffs,
82
+ stops,
83
+ plan,
84
+ };
85
+ }
86
+ // True when a fence names the special token "all" / "*" (clear/stop
87
+ // everything, no per-task enumeration).
88
+ export function meansAll(lines) {
89
+ return lines
90
+ .flatMap((line) => line.split(','))
91
+ .some((t) => t.trim().toLowerCase() === 'all' || t.trim() === '*');
92
+ }
93
+ // The router respaces commas when it copies a title ("a , b", "a,b").
94
+ function titleKey(title) {
95
+ return title.replace(/\s*,\s*/g, ', ').toLowerCase();
96
+ }
97
+ function resolveOne(tasks, token) {
98
+ if (tasks.has(token))
99
+ return token;
100
+ const key = titleKey(token);
101
+ const byTitle = [...tasks.values()]
102
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
103
+ .filter((t) => titleKey(t.title) === key);
104
+ return byTitle[byTitle.length - 1]?.id;
105
+ }
106
+ function longestRunFrom(tasks, fragments, start) {
107
+ for (let end = fragments.length; end > start; end--) {
108
+ const candidate = fragments.slice(start, end).join(',').trim();
109
+ const id = candidate ? resolveOne(tasks, candidate) : undefined;
110
+ if (id)
111
+ return { id, end };
112
+ }
113
+ return undefined;
114
+ }
115
+ // Fences name targets as comma-separated titles or ids, but a title may itself
116
+ // contain a comma. So a line is first tried whole; otherwise it is split on
117
+ // commas and, from each fragment, the longest run of adjacent fragments that
118
+ // names a task on the board wins. "after:" entries may also name tasks spawned
119
+ // earlier in the same reply (spawn order follows block order). A fragment that
120
+ // names nothing is dropped.
121
+ export function resolveTargets(tasks, lines) {
122
+ const resolved = [];
123
+ for (const line of lines) {
124
+ const whole = resolveOne(tasks, line.trim());
125
+ if (whole) {
126
+ resolved.push(whole);
127
+ continue;
128
+ }
129
+ const fragments = line.split(',');
130
+ let start = 0;
131
+ while (start < fragments.length) {
132
+ const match = longestRunFrom(tasks, fragments, start);
133
+ if (match)
134
+ resolved.push(match.id);
135
+ start = match ? match.end : start + 1;
136
+ }
137
+ }
138
+ return [...new Set(resolved)];
139
+ }