zelari-code 2.33.1 → 2.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30994,31 +30994,6 @@ You are the sole implementer this run. Advisors already analyzed \u2014 implemen
30994
30994
  }
30995
30995
  });
30996
30996
 
30997
- // packages/core/dist/council/modeBanners.js
30998
- function councilModeBanner(runMode, opts) {
30999
- if (runMode === "design-phase")
31000
- return DESIGN_PHASE_MODE_BANNER;
31001
- if (opts?.isImplementer === true)
31002
- return IMPLEMENTATION_IMPLEMENTER_BANNER;
31003
- if (opts?.isImplementer === false)
31004
- return IMPLEMENTATION_ADVISOR_BANNER;
31005
- return IMPLEMENTATION_MODE_BANNER;
31006
- }
31007
- var DESIGN_PHASE_MODE_BANNER, IMPLEMENTATION_MODE_BANNER, IMPLEMENTATION_IMPLEMENTER_BANNER, IMPLEMENTATION_ADVISOR_BANNER;
31008
- var init_modeBanners = __esm({
31009
- "packages/core/dist/council/modeBanners.js"() {
31010
- "use strict";
31011
- DESIGN_PHASE_MODE_BANNER = `COUNCIL RUN MODE: design-phase.
31012
- Workspace tool emissions described in your role prompt are MANDATORY in this run \u2014 prose alone does not count as a deliverable. Persist artifacts via the workspace tools listed in your AVAILABLE TOOLS section.`;
31013
- IMPLEMENTATION_MODE_BANNER = `COUNCIL RUN MODE: implementation.
31014
- Prefer write_file, edit_file, and bash for code changes. Design-phase mandatory workspace blocks in your role prompt are INACTIVE \u2014 .zelari/docs and draft plans are hypotheses, not product law. Ground work in the real source tree. Only call workspace tools when they add durable project value.`;
31015
- IMPLEMENTATION_IMPLEMENTER_BANNER = `COUNCIL RUN MODE: implementation \u2014 you are the IMPLEMENTER.
31016
- You are the only member that writes code this run. Implement the solution with write_file / edit_file and verify with bash. Reconcile specialists' analysis and Minosse's critique into working, verified changes. Design vault (.zelari/docs, draft plans) is HYPOTHESIS only \u2014 product truth is the source tree. Design-phase mandatory workspace blocks are INACTIVE.`;
31017
- IMPLEMENTATION_ADVISOR_BANNER = `COUNCIL RUN MODE: implementation \u2014 you are an ADVISOR.
31018
- Do NOT write or edit project files (not via write_file/edit_file, and not via bash) \u2014 Lucifero is the sole implementer. Inspect the real codebase (read_file, grep_content, list_files). Treat prior design prose and .zelari/docs as hypotheses. Flag contradictions with package.json / the tree. Design-phase mandatory workspace blocks are INACTIVE.`;
31019
- }
31020
- });
31021
-
31022
30997
  // packages/core/dist/council/runMode.js
31023
30998
  function resolveCouncilRunMode(input) {
31024
30999
  if (input.forceMode) {
@@ -31880,54 +31855,6 @@ var init_microGate = __esm({
31880
31855
  }
31881
31856
  });
31882
31857
 
31883
- // packages/core/dist/council/verification/completion.js
31884
- function isVerifyToolCheckSkipped() {
31885
- return process.env.ZELARI_VERIFY_SKIP_TOOL === "1";
31886
- }
31887
- function checkImplementationCompletion(emittedToolNames) {
31888
- if (isVerifyToolCheckSkipped()) {
31889
- return { ok: true, missing: [] };
31890
- }
31891
- let lastWriteIdx = -1;
31892
- for (let i = 0; i < emittedToolNames.length; i++) {
31893
- if (WRITE_TOOLS.has(emittedToolNames[i])) {
31894
- lastWriteIdx = i;
31895
- }
31896
- }
31897
- if (lastWriteIdx === -1) {
31898
- return { ok: true, missing: [] };
31899
- }
31900
- const afterWrite = emittedToolNames.slice(lastWriteIdx + 1);
31901
- if (afterWrite.some((t) => VERIFY_TOOLS.has(t))) {
31902
- return { ok: true, missing: [] };
31903
- }
31904
- return {
31905
- ok: false,
31906
- missing: ["grep_content"],
31907
- reason: "No grep_content or bash after last write_file/edit_file"
31908
- };
31909
- }
31910
- function resolveVerifyRetryTool(executableTools) {
31911
- if (!executableTools)
31912
- return "grep_content";
31913
- if (executableTools.has("grep_content"))
31914
- return "grep_content";
31915
- if (executableTools.has("bash"))
31916
- return "bash";
31917
- return null;
31918
- }
31919
- function buildImplementationVerifyRetryPrompt(toolName) {
31920
- return `You wrote files but did not run ${toolName} or bash to verify them. Call ${toolName} NOW on your changed HTML (search @keyframes, transition, classList.add). No prose.`;
31921
- }
31922
- var WRITE_TOOLS, VERIFY_TOOLS;
31923
- var init_completion = __esm({
31924
- "packages/core/dist/council/verification/completion.js"() {
31925
- "use strict";
31926
- WRITE_TOOLS = /* @__PURE__ */ new Set(["write_file", "edit_file"]);
31927
- VERIFY_TOOLS = /* @__PURE__ */ new Set(["grep_content", "bash"]);
31928
- }
31929
- });
31930
-
31931
31858
  // packages/core/dist/council/scope/extractTaskScope.js
31932
31859
  function normalizePath(p3) {
31933
31860
  return p3.replace(/\\/g, "/").replace(/^\.\//, "");
@@ -32178,13 +32105,13 @@ ${hints.map((h) => `- ${h}`).join("\n")}
32178
32105
  ` : "") + `Use read_file then edit_file on the listed files. No verification table \u2014 tool calls only.`;
32179
32106
  }
32180
32107
  function countEmittedWriteTools(emittedToolNames) {
32181
- return emittedToolNames.filter((t) => WRITE_TOOLS2.has(t)).length;
32108
+ return emittedToolNames.filter((t) => WRITE_TOOLS.has(t)).length;
32182
32109
  }
32183
- var WRITE_TOOLS2, IMPLEMENTATION_WRITE_REQUIREMENTS;
32110
+ var WRITE_TOOLS, IMPLEMENTATION_WRITE_REQUIREMENTS;
32184
32111
  var init_implementationDelivery = __esm({
32185
32112
  "packages/core/dist/council/verification/implementationDelivery.js"() {
32186
32113
  "use strict";
32187
- WRITE_TOOLS2 = /* @__PURE__ */ new Set(["write_file", "edit_file"]);
32114
+ WRITE_TOOLS = /* @__PURE__ */ new Set(["write_file", "edit_file"]);
32188
32115
  IMPLEMENTATION_WRITE_REQUIREMENTS = [
32189
32116
  { name: "write_file", min: 1 },
32190
32117
  { name: "edit_file", min: 1 }
@@ -32192,6 +32119,256 @@ var init_implementationDelivery = __esm({
32192
32119
  }
32193
32120
  });
32194
32121
 
32122
+ // packages/core/dist/agents/council/types.js
32123
+ var NON_RETRY_AGENTS;
32124
+ var init_types7 = __esm({
32125
+ "packages/core/dist/agents/council/types.js"() {
32126
+ "use strict";
32127
+ NON_RETRY_AGENTS = /* @__PURE__ */ new Set([]);
32128
+ }
32129
+ });
32130
+
32131
+ // packages/core/dist/agents/council/outputCleaning.js
32132
+ function extractBalancedJsonObject(s) {
32133
+ const start = s.indexOf("{");
32134
+ if (start < 0)
32135
+ return null;
32136
+ let depth = 0;
32137
+ let inString = false;
32138
+ let escape = false;
32139
+ for (let i = start; i < s.length; i++) {
32140
+ const ch = s[i];
32141
+ if (inString) {
32142
+ if (escape) {
32143
+ escape = false;
32144
+ continue;
32145
+ }
32146
+ if (ch === "\\") {
32147
+ escape = true;
32148
+ continue;
32149
+ }
32150
+ if (ch === '"')
32151
+ inString = false;
32152
+ continue;
32153
+ }
32154
+ if (ch === '"') {
32155
+ inString = true;
32156
+ continue;
32157
+ }
32158
+ if (ch === "{")
32159
+ depth++;
32160
+ else if (ch === "}") {
32161
+ depth--;
32162
+ if (depth === 0)
32163
+ return s.slice(start, i + 1);
32164
+ }
32165
+ }
32166
+ return null;
32167
+ }
32168
+ function parseClarificationRequest(text) {
32169
+ const start = text.indexOf(QUESTION_MARKER);
32170
+ if (start < 0)
32171
+ return null;
32172
+ const rest = text.slice(start + QUESTION_MARKER.length);
32173
+ const end = rest.indexOf(QUESTION_END_MARKER);
32174
+ const block = end >= 0 ? rest.slice(0, end) : rest;
32175
+ const cleaned = block.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
32176
+ const jsonText = extractBalancedJsonObject(cleaned) ?? (() => {
32177
+ const objStart = cleaned.indexOf("{");
32178
+ const objEnd = cleaned.lastIndexOf("}");
32179
+ return objStart >= 0 && objEnd > objStart ? cleaned.slice(objStart, objEnd + 1) : cleaned;
32180
+ })();
32181
+ try {
32182
+ const parsed = JSON.parse(jsonText);
32183
+ if (typeof parsed.question !== "string" || !parsed.question.trim())
32184
+ return null;
32185
+ return {
32186
+ question: parsed.question.trim(),
32187
+ choices: Array.isArray(parsed.choices) ? parsed.choices.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : void 0,
32188
+ context: typeof parsed.context === "string" ? parsed.context.trim() : void 0
32189
+ };
32190
+ } catch {
32191
+ return null;
32192
+ }
32193
+ }
32194
+ function hasInteractiveClarification(text) {
32195
+ const c = parseClarificationRequest(text);
32196
+ return !!(c && c.choices && c.choices.length >= 2);
32197
+ }
32198
+ function parseThinking(text) {
32199
+ const complete = text.match(/<think(?:ing)?>([\s\S]*?)<\/think(?:ing)?>/i);
32200
+ if (complete)
32201
+ return complete[1].trim();
32202
+ const open2 = text.match(/<think(?:ing)?>([\s\S]*)$/i);
32203
+ return open2 ? open2[1].trim() : "";
32204
+ }
32205
+ function cleanAgentContent(text, opts = {}) {
32206
+ const stripQuestion = opts.stripQuestion !== false;
32207
+ const stripThink = opts.stripThink !== false;
32208
+ let out = text;
32209
+ if (stripThink) {
32210
+ out = out.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, "").replace(/<think(?:ing)?>[\s\S]*$/gi, "").replace(/<\/think(?:ing)?>/gi, "");
32211
+ }
32212
+ out = out.replace(/<minimax:tool_call>[\s\S]*?<\/minimax:tool_call>/gi, "").replace(/<\/?minimax:tool_call>/gi, "").replace(/<tool_call>[\s\S]*?<\/tool_call>/gi, "").replace(/<\/?tool_call>/gi, "").replace(/<function_call>[\s\S]*?<\/function_call>/gi, "").replace(/<\/?function_call>/gi, "").replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "").replace(/<\/invoke>/gi, "").replace(/<parameter\b[^>]*>[\s\S]*?<\/parameter>/gi, "").replace(/<\/parameter>/gi, "").replace(/\]\s*<\]\s*minimax\s*\[>\s*\[?<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "").replace(/<minimax:tool_call>[\s\S]*$/gi, "").replace(/<tool_call>[\s\S]*$/gi, "").replace(/<function_call>[\s\S]*$/gi, "").replace(/<invoke\b[^>]*>[\s\S]*$/gi, "").replace(/\]\s*<\]\s*minimax\s*\[>[\s\S]*$/gi, "").replace(/^\s*\]\s*<\]\s*minimax\s*\[>.*$/gim, "").replace(/^\s*<\/?(?:tool_call|function_call|invoke|parameter|minimax:tool_call)\b[^>]*>\s*$/gim, "");
32213
+ if (stripQuestion) {
32214
+ out = out.replace(/---QUESTION---[\s\S]*?---END---/g, "").replace(/---QUESTION---[\s\S]*$/g, "");
32215
+ }
32216
+ out = out.replace(/\n{3,}/g, "\n\n").trim();
32217
+ return scrubProprietaryLeak(out);
32218
+ }
32219
+ var QUESTION_MARKER, QUESTION_END_MARKER;
32220
+ var init_outputCleaning = __esm({
32221
+ "packages/core/dist/agents/council/outputCleaning.js"() {
32222
+ "use strict";
32223
+ init_secrecyPolicy();
32224
+ QUESTION_MARKER = "---QUESTION---";
32225
+ QUESTION_END_MARKER = "---END---";
32226
+ }
32227
+ });
32228
+
32229
+ // packages/core/dist/council/modeBanners.js
32230
+ function councilModeBanner(runMode, opts) {
32231
+ if (runMode === "design-phase")
32232
+ return DESIGN_PHASE_MODE_BANNER;
32233
+ if (opts?.isImplementer === true)
32234
+ return IMPLEMENTATION_IMPLEMENTER_BANNER;
32235
+ if (opts?.isImplementer === false)
32236
+ return IMPLEMENTATION_ADVISOR_BANNER;
32237
+ return IMPLEMENTATION_MODE_BANNER;
32238
+ }
32239
+ var DESIGN_PHASE_MODE_BANNER, IMPLEMENTATION_MODE_BANNER, IMPLEMENTATION_IMPLEMENTER_BANNER, IMPLEMENTATION_ADVISOR_BANNER;
32240
+ var init_modeBanners = __esm({
32241
+ "packages/core/dist/council/modeBanners.js"() {
32242
+ "use strict";
32243
+ DESIGN_PHASE_MODE_BANNER = `COUNCIL RUN MODE: design-phase.
32244
+ Workspace tool emissions described in your role prompt are MANDATORY in this run \u2014 prose alone does not count as a deliverable. Persist artifacts via the workspace tools listed in your AVAILABLE TOOLS section.`;
32245
+ IMPLEMENTATION_MODE_BANNER = `COUNCIL RUN MODE: implementation.
32246
+ Prefer write_file, edit_file, and bash for code changes. Design-phase mandatory workspace blocks in your role prompt are INACTIVE \u2014 .zelari/docs and draft plans are hypotheses, not product law. Ground work in the real source tree. Only call workspace tools when they add durable project value.`;
32247
+ IMPLEMENTATION_IMPLEMENTER_BANNER = `COUNCIL RUN MODE: implementation \u2014 you are the IMPLEMENTER.
32248
+ You are the only member that writes code this run. Implement the solution with write_file / edit_file and verify with bash. Reconcile specialists' analysis and Minosse's critique into working, verified changes. Design vault (.zelari/docs, draft plans) is HYPOTHESIS only \u2014 product truth is the source tree. Design-phase mandatory workspace blocks are INACTIVE.`;
32249
+ IMPLEMENTATION_ADVISOR_BANNER = `COUNCIL RUN MODE: implementation \u2014 you are an ADVISOR.
32250
+ Do NOT write or edit project files (not via write_file/edit_file, and not via bash) \u2014 Lucifero is the sole implementer. Inspect the real codebase (read_file, grep_content, list_files). Treat prior design prose and .zelari/docs as hypotheses. Flag contradictions with package.json / the tree. Design-phase mandatory workspace blocks are INACTIVE.`;
32251
+ }
32252
+ });
32253
+
32254
+ // packages/core/dist/agents/council/memberMessages.js
32255
+ function restrictImplementationWrites(toolNames, opts) {
32256
+ if (opts.runMode !== "implementation" || opts.isImplementer)
32257
+ return toolNames;
32258
+ return toolNames.filter((t) => !MUTATING_PROJECT_TOOLS.includes(t));
32259
+ }
32260
+ function buildAgentMessages(agent, userMessage, ragContext, workspaceContext, priorOutputs, aiConfig, executableTools, runMode = "implementation", languageModule) {
32261
+ const allToolNames = computeAgentTools(agent, aiConfig);
32262
+ const toolNames = executableTools ? allToolNames.filter((n) => executableTools.has(n)) : allToolNames;
32263
+ const mergedAiConfig = languageModule ? {
32264
+ enabledSkills: aiConfig?.enabledSkills ?? [],
32265
+ enabledTools: aiConfig?.enabledTools ?? [],
32266
+ agentSkillConfigs: aiConfig?.agentSkillConfigs ?? [],
32267
+ customSkills: aiConfig?.customSkills,
32268
+ customPromptModules: [
32269
+ ...aiConfig?.customPromptModules ?? [],
32270
+ languageModule
32271
+ ]
32272
+ } : aiConfig;
32273
+ const modeAwareAgent = {
32274
+ ...agent,
32275
+ systemPrompt: resolveRoleSystemPrompt(agent, runMode)
32276
+ };
32277
+ const split = buildSystemPromptSplit(modeAwareAgent, {
32278
+ tools: getAllTools(),
32279
+ toolNames,
32280
+ aiConfig: mergedAiConfig,
32281
+ workspaceContext,
32282
+ ragContext,
32283
+ mode: "council",
32284
+ includeWorkspaceInPrompt: true
32285
+ });
32286
+ const messages = [
32287
+ { role: "system", content: split.stable }
32288
+ ];
32289
+ if (split.volatile.trim()) {
32290
+ messages.push({ role: "system", content: split.volatile });
32291
+ }
32292
+ messages.push({ role: "system", content: councilModeBanner(runMode, { isImplementer: agent.id === "lucifer" }) }, { role: "system", content: "IMPORTANT: Before making any tool calls or expensive operations, check if the information already exists in the shared context from previous agents. Avoid redundant work." });
32293
+ if (priorOutputs.length > 0) {
32294
+ const MAX_PRIOR_CHARS = 2800;
32295
+ const summary = priorOutputs.map((o) => {
32296
+ const body = o.content.length > MAX_PRIOR_CHARS ? `${o.content.slice(0, MAX_PRIOR_CHARS)}
32297
+ \u2026 [truncated ${o.content.length}\u2192${MAX_PRIOR_CHARS} chars; treat as hypothesis]` : o.content;
32298
+ return `[${o.name} - ${o.role}]: ${body}`;
32299
+ }).join("\n\n");
32300
+ messages.push({
32301
+ role: "user",
32302
+ content: `Previous council members have said (hypotheses \u2014 prefer product files on disk if they conflict):
32303
+ ${summary}
32304
+
32305
+ Original user request: ${userMessage}`
32306
+ });
32307
+ } else {
32308
+ messages.push({ role: "user", content: userMessage });
32309
+ }
32310
+ return messages;
32311
+ }
32312
+ var MUTATING_PROJECT_TOOLS;
32313
+ var init_memberMessages = __esm({
32314
+ "packages/core/dist/agents/council/memberMessages.js"() {
32315
+ "use strict";
32316
+ init_roles();
32317
+ init_systemPromptBuilder();
32318
+ init_tools();
32319
+ init_modeBanners();
32320
+ MUTATING_PROJECT_TOOLS = ["write_file", "edit_file"];
32321
+ }
32322
+ });
32323
+
32324
+ // packages/core/dist/council/verification/completion.js
32325
+ function isVerifyToolCheckSkipped() {
32326
+ return process.env.ZELARI_VERIFY_SKIP_TOOL === "1";
32327
+ }
32328
+ function checkImplementationCompletion(emittedToolNames) {
32329
+ if (isVerifyToolCheckSkipped()) {
32330
+ return { ok: true, missing: [] };
32331
+ }
32332
+ let lastWriteIdx = -1;
32333
+ for (let i = 0; i < emittedToolNames.length; i++) {
32334
+ if (WRITE_TOOLS2.has(emittedToolNames[i])) {
32335
+ lastWriteIdx = i;
32336
+ }
32337
+ }
32338
+ if (lastWriteIdx === -1) {
32339
+ return { ok: true, missing: [] };
32340
+ }
32341
+ const afterWrite = emittedToolNames.slice(lastWriteIdx + 1);
32342
+ if (afterWrite.some((t) => VERIFY_TOOLS.has(t))) {
32343
+ return { ok: true, missing: [] };
32344
+ }
32345
+ return {
32346
+ ok: false,
32347
+ missing: ["grep_content"],
32348
+ reason: "No grep_content or bash after last write_file/edit_file"
32349
+ };
32350
+ }
32351
+ function resolveVerifyRetryTool(executableTools) {
32352
+ if (!executableTools)
32353
+ return "grep_content";
32354
+ if (executableTools.has("grep_content"))
32355
+ return "grep_content";
32356
+ if (executableTools.has("bash"))
32357
+ return "bash";
32358
+ return null;
32359
+ }
32360
+ function buildImplementationVerifyRetryPrompt(toolName) {
32361
+ return `You wrote files but did not run ${toolName} or bash to verify them. Call ${toolName} NOW on your changed HTML (search @keyframes, transition, classList.add). No prose.`;
32362
+ }
32363
+ var WRITE_TOOLS2, VERIFY_TOOLS;
32364
+ var init_completion = __esm({
32365
+ "packages/core/dist/council/verification/completion.js"() {
32366
+ "use strict";
32367
+ WRITE_TOOLS2 = /* @__PURE__ */ new Set(["write_file", "edit_file"]);
32368
+ VERIFY_TOOLS = /* @__PURE__ */ new Set(["grep_content", "bash"]);
32369
+ }
32370
+ });
32371
+
32195
32372
  // packages/core/dist/council/verification/inlineJsAutofix.js
32196
32373
  import { readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "node:fs";
32197
32374
  import { join as join7 } from "node:path";
@@ -32272,153 +32449,498 @@ var init_inlineJsAutofix = __esm({
32272
32449
  }
32273
32450
  });
32274
32451
 
32275
- // packages/core/dist/agents/councilApi.js
32276
- import { existsSync as existsSync12 } from "node:fs";
32277
- import { join as join8 } from "node:path";
32278
- function extractBalancedJsonObject(s) {
32279
- const start = s.indexOf("{");
32280
- if (start < 0)
32281
- return null;
32282
- let depth = 0;
32283
- let inString = false;
32284
- let escape = false;
32285
- for (let i = start; i < s.length; i++) {
32286
- const ch = s[i];
32287
- if (inString) {
32288
- if (escape) {
32289
- escape = false;
32290
- continue;
32291
- }
32292
- if (ch === "\\") {
32293
- escape = true;
32294
- continue;
32295
- }
32296
- if (ch === '"')
32297
- inString = false;
32298
- continue;
32299
- }
32300
- if (ch === '"') {
32301
- inString = true;
32302
- continue;
32303
- }
32304
- if (ch === "{")
32305
- depth++;
32306
- else if (ch === "}") {
32307
- depth--;
32308
- if (depth === 0)
32309
- return s.slice(start, i + 1);
32452
+ // packages/core/dist/agents/council/toolEmission.js
32453
+ function checkMemberToolEmissions(_memberId, emittedToolNames, requirements) {
32454
+ if (requirements.length === 0) {
32455
+ return { ok: true, missing: [] };
32456
+ }
32457
+ const counts = /* @__PURE__ */ new Map();
32458
+ for (const name of emittedToolNames) {
32459
+ counts.set(name, (counts.get(name) ?? 0) + 1);
32460
+ }
32461
+ const missing = [];
32462
+ for (const req of requirements) {
32463
+ const got = counts.get(req.name) ?? 0;
32464
+ if (got < req.min) {
32465
+ missing.push(`${req.name} (got ${got}, need >= ${req.min})`);
32310
32466
  }
32311
32467
  }
32312
- return null;
32468
+ return { ok: missing.length === 0, missing };
32313
32469
  }
32314
- function parseClarificationRequest(text) {
32315
- const start = text.indexOf(QUESTION_MARKER);
32316
- if (start < 0)
32317
- return null;
32318
- const rest = text.slice(start + QUESTION_MARKER.length);
32319
- const end = rest.indexOf(QUESTION_END_MARKER);
32320
- const block = end >= 0 ? rest.slice(0, end) : rest;
32321
- const cleaned = block.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
32322
- const jsonText = extractBalancedJsonObject(cleaned) ?? (() => {
32323
- const objStart = cleaned.indexOf("{");
32324
- const objEnd = cleaned.lastIndexOf("}");
32325
- return objStart >= 0 && objEnd > objStart ? cleaned.slice(objStart, objEnd + 1) : cleaned;
32326
- })();
32327
- try {
32328
- const parsed = JSON.parse(jsonText);
32329
- if (typeof parsed.question !== "string" || !parsed.question.trim())
32330
- return null;
32331
- return {
32332
- question: parsed.question.trim(),
32333
- choices: Array.isArray(parsed.choices) ? parsed.choices.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : void 0,
32334
- context: typeof parsed.context === "string" ? parsed.context.trim() : void 0
32470
+ function checkMemberToolEmissionSets(memberId, emittedToolNames, sets) {
32471
+ if (sets.length === 0) {
32472
+ return { ok: true, missing: [] };
32473
+ }
32474
+ const results = sets.map((set2) => checkMemberToolEmissions(memberId, emittedToolNames, set2));
32475
+ if (results.some((r) => r.ok)) {
32476
+ return { ok: true, missing: [] };
32477
+ }
32478
+ return results[0];
32479
+ }
32480
+ function enforceDesignPhaseToolEmissions(memberId, emittedToolNames) {
32481
+ const sets = DESIGN_PHASE_REQUIREMENT_SETS[memberId];
32482
+ if (!sets || sets.length === 0) {
32483
+ return { ok: true, missing: [] };
32484
+ }
32485
+ const result = checkMemberToolEmissionSets(memberId, emittedToolNames, sets);
32486
+ if (!result.ok) {
32487
+ console.warn(`[council] member "${memberId}" did not emit required tools: ${result.missing.join(", ")}. The downstream .zelari/ deliverable may be incomplete. (A forced retry turn scoped to the missing tools follows; the deterministic complete-design fallback covers any remaining gap.)`);
32488
+ }
32489
+ return result;
32490
+ }
32491
+ var DESIGN_PHASE_REQUIREMENT_SETS, DESIGN_PHASE_REQUIREMENTS;
32492
+ var init_toolEmission = __esm({
32493
+ "packages/core/dist/agents/council/toolEmission.js"() {
32494
+ "use strict";
32495
+ DESIGN_PHASE_REQUIREMENT_SETS = {
32496
+ nettun: [
32497
+ [{ name: "createPlan", min: 1 }],
32498
+ [
32499
+ { name: "createPhase", min: 3 },
32500
+ { name: "createTask", min: 6 },
32501
+ { name: "createMilestone", min: 1 }
32502
+ ]
32503
+ ],
32504
+ geryon: [
32505
+ [{ name: "createDocument", min: 3 }]
32506
+ ],
32507
+ pluton: [
32508
+ [{ name: "createDocument", min: 1 }]
32509
+ ],
32510
+ minos: [
32511
+ [{ name: "createDocument", min: 1 }]
32512
+ ],
32513
+ lucifer: [
32514
+ [{ name: "createDocument", min: 1 }]
32515
+ ]
32335
32516
  };
32336
- } catch {
32337
- return null;
32517
+ DESIGN_PHASE_REQUIREMENTS = Object.fromEntries(Object.entries(DESIGN_PHASE_REQUIREMENT_SETS).map(([id3, sets]) => [id3, sets[0]]));
32338
32518
  }
32519
+ });
32520
+
32521
+ // packages/core/dist/agents/council/retryTurn.js
32522
+ function shouldRetryMember(missingToolNames, attemptsSoFar) {
32523
+ if (missingToolNames.length === 0)
32524
+ return false;
32525
+ if (attemptsSoFar >= MAX_RETRY_PER_MEMBER)
32526
+ return false;
32527
+ return true;
32339
32528
  }
32340
- function hasInteractiveClarification(text) {
32341
- const c = parseClarificationRequest(text);
32342
- return !!(c && c.choices && c.choices.length >= 2);
32529
+ function buildRetryPrompt(missingToolNames) {
32530
+ const names = missingToolNames.join(", ");
32531
+ return `You did not emit the required workspace tools: ${names}. Call ${names} NOW with concrete arguments. No prose. No search.`;
32343
32532
  }
32344
- function parseThinking(text) {
32345
- const complete = text.match(/<think(?:ing)?>([\s\S]*?)<\/think(?:ing)?>/i);
32346
- if (complete)
32347
- return complete[1].trim();
32348
- const open2 = text.match(/<think(?:ing)?>([\s\S]*)$/i);
32349
- return open2 ? open2[1].trim() : "";
32533
+ async function* runRetryTurnForMember(args) {
32534
+ const executableMissing = args.executableTools ? args.missingToolNames.filter((n) => args.executableTools.has(n)) : args.missingToolNames;
32535
+ if (executableMissing.length === 0) {
32536
+ return [];
32537
+ }
32538
+ const retryToolNames = executableMissing;
32539
+ const retryToolSpecs = getProviderTools(retryToolNames).map((t) => ({
32540
+ name: t.function.name,
32541
+ description: t.function.description,
32542
+ parameters: t.function.parameters
32543
+ }));
32544
+ const baseMessages = buildAgentMessages(args.agent, args.userMessage, args.ragContext, args.workspaceContext, args.priorOutputs, args.aiConfig, args.executableTools, args.runMode ?? "implementation", args.languageModule);
32545
+ const retryMessages = [
32546
+ ...baseMessages,
32547
+ {
32548
+ role: "user",
32549
+ content: args.retryPrompt ?? buildRetryPrompt(executableMissing)
32550
+ }
32551
+ ];
32552
+ const maxToolCalls = args.minPerTool !== void 0 ? Object.entries(args.minPerTool).filter(([name]) => executableMissing.includes(name)).reduce((sum, [, min]) => sum + min, 0) : retryToolNames.length;
32553
+ const retryHarness = new AgentHarness({
32554
+ model: args.effectiveModel,
32555
+ provider: args.effectiveProvider,
32556
+ sessionId: args.sessionId,
32557
+ messages: retryMessages,
32558
+ tools: retryToolSpecs,
32559
+ eventBus: args.eventBus,
32560
+ toolRegistry: args.toolRegistry,
32561
+ // Budget the retry so the model can satisfy every requirement in
32562
+ // ONE tool_calls turn. For createTask min:12 this needs 12 calls.
32563
+ maxToolCallsPerTurn: maxToolCalls,
32564
+ memberId: args.agent.id,
32565
+ memberName: args.agent.name,
32566
+ providerStream: (params) => args.providerStream(params)
32567
+ });
32568
+ const retryEmitted = [];
32569
+ for await (const event of retryHarness.run()) {
32570
+ if (event.type === "tool_execution_start") {
32571
+ retryEmitted.push(event.toolName);
32572
+ }
32573
+ yield event;
32574
+ }
32575
+ return retryEmitted;
32350
32576
  }
32351
- function cleanAgentContent(text, opts = {}) {
32352
- const stripQuestion = opts.stripQuestion !== false;
32353
- const stripThink = opts.stripThink !== false;
32354
- let out = text;
32355
- if (stripThink) {
32356
- out = out.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, "").replace(/<think(?:ing)?>[\s\S]*$/gi, "").replace(/<\/think(?:ing)?>/gi, "");
32577
+ async function* applyRetryIfMissing(args) {
32578
+ if (args.check.ok)
32579
+ return;
32580
+ const missingToolNames = args.check.missing.map((m) => m.split(" ")[0]);
32581
+ if (!shouldRetryMember(missingToolNames, 0))
32582
+ return;
32583
+ console.warn(`[council] ${args.agent.id} retrying missing tools: ${missingToolNames.join(", ")}`);
32584
+ const minPerTool = {};
32585
+ if (args.requirements) {
32586
+ for (const req of args.requirements) {
32587
+ if (missingToolNames.includes(req.name)) {
32588
+ minPerTool[req.name] = req.min;
32589
+ }
32590
+ }
32357
32591
  }
32358
- out = out.replace(/<minimax:tool_call>[\s\S]*?<\/minimax:tool_call>/gi, "").replace(/<\/?minimax:tool_call>/gi, "").replace(/<tool_call>[\s\S]*?<\/tool_call>/gi, "").replace(/<\/?tool_call>/gi, "").replace(/<function_call>[\s\S]*?<\/function_call>/gi, "").replace(/<\/?function_call>/gi, "").replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "").replace(/<\/invoke>/gi, "").replace(/<parameter\b[^>]*>[\s\S]*?<\/parameter>/gi, "").replace(/<\/parameter>/gi, "").replace(/\]\s*<\]\s*minimax\s*\[>\s*\[?<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "").replace(/<minimax:tool_call>[\s\S]*$/gi, "").replace(/<tool_call>[\s\S]*$/gi, "").replace(/<function_call>[\s\S]*$/gi, "").replace(/<invoke\b[^>]*>[\s\S]*$/gi, "").replace(/\]\s*<\]\s*minimax\s*\[>[\s\S]*$/gi, "").replace(/^\s*\]\s*<\]\s*minimax\s*\[>.*$/gim, "").replace(/^\s*<\/?(?:tool_call|function_call|invoke|parameter|minimax:tool_call)\b[^>]*>\s*$/gim, "");
32359
- if (stripQuestion) {
32360
- out = out.replace(/---QUESTION---[\s\S]*?---END---/g, "").replace(/---QUESTION---[\s\S]*$/g, "");
32592
+ try {
32593
+ const retryGenerator = runRetryTurnForMember({
32594
+ agent: args.agent,
32595
+ missingToolNames,
32596
+ minPerTool,
32597
+ executableTools: args.executableNames,
32598
+ userMessage: args.userMessage,
32599
+ ragContext: args.config.ragContext,
32600
+ workspaceContext: args.config.workspaceContext,
32601
+ priorOutputs: args.agentOutputs,
32602
+ aiConfig: args.config.aiConfig,
32603
+ sessionId: args.sessionId,
32604
+ effectiveModel: args.effectiveModel,
32605
+ effectiveProvider: args.effectiveProvider,
32606
+ eventBus: args.config.eventBus,
32607
+ toolRegistry: args.config.tools,
32608
+ providerStream: args.config.providerStream,
32609
+ runMode: args.config.runMode,
32610
+ languageModule: args.languageModule
32611
+ });
32612
+ for await (const event of retryGenerator) {
32613
+ if (event.type === "tool_execution_start") {
32614
+ args.onToolCall();
32615
+ args.emittedToolNames.push(event.toolName);
32616
+ }
32617
+ yield event;
32618
+ }
32619
+ } catch (retryErr) {
32620
+ console.error(`[council] ${args.agent.id} retry failed:`, retryErr);
32361
32621
  }
32362
- out = out.replace(/\n{3,}/g, "\n\n").trim();
32363
- return scrubProprietaryLeak(out);
32622
+ enforceDesignPhaseToolEmissions(args.agent.id, args.emittedToolNames);
32364
32623
  }
32365
- function restrictImplementationWrites(toolNames, opts) {
32366
- if (opts.runMode !== "implementation" || opts.isImplementer)
32367
- return toolNames;
32368
- return toolNames.filter((t) => !MUTATING_PROJECT_TOOLS.includes(t));
32624
+ var MAX_RETRY_PER_MEMBER;
32625
+ var init_retryTurn = __esm({
32626
+ "packages/core/dist/agents/council/retryTurn.js"() {
32627
+ "use strict";
32628
+ init_AgentHarness();
32629
+ init_toolSchemas();
32630
+ init_memberMessages();
32631
+ init_toolEmission();
32632
+ MAX_RETRY_PER_MEMBER = 1;
32633
+ }
32634
+ });
32635
+
32636
+ // packages/core/dist/agents/council/chairmanDelivery.js
32637
+ async function* applyCompletionRetry(args) {
32638
+ const check2 = checkImplementationCompletion(args.emittedToolNames);
32639
+ if (check2.ok)
32640
+ return;
32641
+ const retryTool = resolveVerifyRetryTool(args.executableNames);
32642
+ if (!retryTool) {
32643
+ console.warn("[council] implementation verify retry skipped \u2014 no grep_content/bash in registry");
32644
+ return;
32645
+ }
32646
+ if (!shouldRetryMember([retryTool], 0))
32647
+ return;
32648
+ console.warn(`[council] ${args.agent.id} retrying missing verify tool: ${retryTool}`);
32649
+ try {
32650
+ const retryGenerator = runRetryTurnForMember({
32651
+ agent: args.agent,
32652
+ missingToolNames: [retryTool],
32653
+ executableTools: args.executableNames,
32654
+ userMessage: args.userMessage,
32655
+ ragContext: args.config.ragContext,
32656
+ workspaceContext: args.config.workspaceContext,
32657
+ priorOutputs: args.agentOutputs,
32658
+ aiConfig: args.config.aiConfig,
32659
+ sessionId: args.sessionId,
32660
+ effectiveModel: args.effectiveModel,
32661
+ effectiveProvider: args.effectiveProvider,
32662
+ eventBus: args.config.eventBus,
32663
+ toolRegistry: args.config.tools,
32664
+ providerStream: args.config.providerStream,
32665
+ runMode: args.config.runMode,
32666
+ retryPrompt: buildImplementationVerifyRetryPrompt(retryTool),
32667
+ languageModule: args.languageModule
32668
+ });
32669
+ for await (const event of retryGenerator) {
32670
+ if (event.type === "tool_execution_start") {
32671
+ args.onToolCall();
32672
+ args.emittedToolNames.push(event.toolName);
32673
+ }
32674
+ yield event;
32675
+ }
32676
+ } catch (retryErr) {
32677
+ console.error(`[council] ${args.agent.id} verify retry failed:`, retryErr);
32678
+ }
32679
+ const after = checkImplementationCompletion(args.emittedToolNames);
32680
+ if (!after.ok) {
32681
+ console.warn(`[council] ${args.agent.id} still missing verify after retry: ${after.reason}`);
32682
+ }
32369
32683
  }
32370
- function buildAgentMessages(agent, userMessage, ragContext, workspaceContext, priorOutputs, aiConfig, executableTools, runMode = "implementation", languageModule) {
32371
- const allToolNames = computeAgentTools(agent, aiConfig);
32372
- const toolNames = executableTools ? allToolNames.filter((n) => executableTools.has(n)) : allToolNames;
32373
- const mergedAiConfig = languageModule ? {
32374
- enabledSkills: aiConfig?.enabledSkills ?? [],
32375
- enabledTools: aiConfig?.enabledTools ?? [],
32376
- agentSkillConfigs: aiConfig?.agentSkillConfigs ?? [],
32377
- customSkills: aiConfig?.customSkills,
32378
- customPromptModules: [
32379
- ...aiConfig?.customPromptModules ?? [],
32380
- languageModule
32381
- ]
32382
- } : aiConfig;
32383
- const modeAwareAgent = {
32384
- ...agent,
32385
- systemPrompt: resolveRoleSystemPrompt(agent, runMode)
32386
- };
32387
- const split = buildSystemPromptSplit(modeAwareAgent, {
32388
- tools: getAllTools(),
32389
- toolNames,
32390
- aiConfig: mergedAiConfig,
32391
- workspaceContext,
32392
- ragContext,
32393
- mode: "council",
32394
- includeWorkspaceInPrompt: true
32684
+ function buildMotionFixPrompt(violations) {
32685
+ const byFile = /* @__PURE__ */ new Map();
32686
+ for (const v of violations) {
32687
+ const file2 = v.file || "index.html";
32688
+ const loc = v.line ? `${file2}:L${v.line}` : file2;
32689
+ const list = byFile.get(file2) ?? [];
32690
+ list.push(` - ${loc}: ${v.message}`);
32691
+ byFile.set(file2, list);
32692
+ }
32693
+ const blocks = Array.from(byFile.values()).map((lines) => lines.join("\n")).join("\n");
32694
+ return `Deterministic verification found ${violations.length} motion violation(s) in the file(s) you just edited. Fix ONLY these \u2014 do not add features, do not rewrite sections, do not touch anything else:
32695
+ ${blocks}
32696
+
32697
+ Rules: animate ONLY transform and opacity. Replace any box-shadow / background / background-position / filter / color / border-color / width / height / grid-template-rows used in @keyframes or transitions with transform/opacity equivalents (e.g. render a glow via a pseudo-element that scales and fades). For every classList.add('x') in the script, add a matching '.x' CSS rule. Use read_file to see the exact lines, then edit_file. When the listed items are fixed, stop \u2014 no summary.`;
32698
+ }
32699
+ async function* applyImplementationWriteRetry(args) {
32700
+ if (args.check.ok)
32701
+ return;
32702
+ if (!shouldRetryMember(["write_file"], 0))
32703
+ return;
32704
+ const statusMsg = `[council] ${args.chairman.id} implementation write retry: ${args.check.missing.join(", ")}`;
32705
+ args.onCouncilStatus?.(statusMsg);
32706
+ console.warn(statusMsg);
32707
+ try {
32708
+ const retryGenerator = runRetryTurnForMember({
32709
+ agent: args.chairman,
32710
+ missingToolNames: ["read_file", "write_file", "edit_file"],
32711
+ minPerTool: { read_file: 3, edit_file: 8, write_file: 1 },
32712
+ executableTools: args.executableNames,
32713
+ userMessage: args.userMessage,
32714
+ ragContext: args.config.ragContext,
32715
+ workspaceContext: args.config.workspaceContext,
32716
+ priorOutputs: args.agentOutputs,
32717
+ aiConfig: args.config.aiConfig,
32718
+ sessionId: args.sessionId,
32719
+ effectiveModel: args.effectiveModel,
32720
+ effectiveProvider: args.effectiveProvider,
32721
+ eventBus: args.config.eventBus,
32722
+ toolRegistry: args.config.tools,
32723
+ providerStream: args.config.providerStream,
32724
+ runMode: "implementation",
32725
+ retryPrompt: buildImplementationWriteRetryPrompt(args.userMessage),
32726
+ languageModule: args.languageModule
32727
+ });
32728
+ for await (const event of retryGenerator) {
32729
+ if (event.type === "tool_execution_start")
32730
+ args.onToolCall?.();
32731
+ if (event.type === "tool_execution_end" && !event.isError && typeof event.result === "string") {
32732
+ try {
32733
+ const parsed = JSON.parse(event.result);
32734
+ if ((parsed.bytesWritten ?? 0) > 0 || (parsed.occurrencesReplaced ?? 0) > 0) {
32735
+ args.onSuccessfulWrite?.();
32736
+ }
32737
+ } catch {
32738
+ if (event.result.includes("bytesWritten") || event.result.includes("occurrencesReplaced")) {
32739
+ args.onSuccessfulWrite?.();
32740
+ }
32741
+ }
32742
+ }
32743
+ yield event;
32744
+ }
32745
+ } catch (retryErr) {
32746
+ console.error(`[council] ${args.chairman.id} implementation write retry failed:`, retryErr);
32747
+ }
32748
+ }
32749
+ async function* runChairmanDeliveryLoop(args) {
32750
+ const maxAttempts = args.maxAttempts ?? MAX_DELIVERY_ATTEMPTS;
32751
+ const zelariRoot = `${args.projectRoot}/.zelari`;
32752
+ let attempt = 0;
32753
+ while (attempt < maxAttempts) {
32754
+ const report = runImplementationVerification({
32755
+ projectRoot: args.projectRoot,
32756
+ zelariRoot
32757
+ });
32758
+ const blocking = filterDeliveryBlockingFails(report.results);
32759
+ if (blocking.length === 0)
32760
+ return true;
32761
+ if (blocking.some((b) => b.id === "inline-js.budget")) {
32762
+ const jsFix = applyInlineJsAutofix(args.projectRoot, report);
32763
+ if (jsFix.applied) {
32764
+ args.onCouncilStatus?.(`[council] ${args.chairman.id} inline-js autofix: ${jsFix.fixes.join("; ")}`);
32765
+ const afterJs = runImplementationVerification({
32766
+ projectRoot: args.projectRoot,
32767
+ zelariRoot
32768
+ });
32769
+ if (filterDeliveryBlockingFails(afterJs.results).length === 0)
32770
+ return true;
32771
+ }
32772
+ }
32773
+ attempt++;
32774
+ const statusMsg = `[council] ${args.chairman.id} delivery pass ${attempt}/${maxAttempts}: ${blocking.map((b) => b.id).join(", ")}`;
32775
+ args.onCouncilStatus?.(statusMsg);
32776
+ console.warn(statusMsg);
32777
+ try {
32778
+ const fixGenerator = runRetryTurnForMember({
32779
+ agent: args.chairman,
32780
+ missingToolNames: ["read_file", "edit_file"],
32781
+ minPerTool: { read_file: 3, edit_file: 10 },
32782
+ executableTools: args.executableNames,
32783
+ userMessage: args.userMessage,
32784
+ ragContext: args.config.ragContext,
32785
+ workspaceContext: args.config.workspaceContext,
32786
+ priorOutputs: args.agentOutputs,
32787
+ aiConfig: args.config.aiConfig,
32788
+ sessionId: args.sessionId,
32789
+ effectiveModel: args.effectiveModel,
32790
+ effectiveProvider: args.effectiveProvider,
32791
+ eventBus: args.config.eventBus,
32792
+ toolRegistry: args.config.tools,
32793
+ providerStream: args.config.providerStream,
32794
+ runMode: "implementation",
32795
+ retryPrompt: buildDeliveryFixPrompt(blocking, args.userMessage),
32796
+ languageModule: args.languageModule
32797
+ });
32798
+ for await (const event of fixGenerator) {
32799
+ if (event.type === "tool_execution_start")
32800
+ args.onToolCall?.();
32801
+ yield event;
32802
+ }
32803
+ } catch (deliveryErr) {
32804
+ console.error(`[council] ${args.chairman.id} delivery pass ${attempt} failed:`, deliveryErr);
32805
+ break;
32806
+ }
32807
+ for (const rel2 of args.changedFiles) {
32808
+ for (const w of runChairmanMicroGate({ projectRoot: args.projectRoot, relPath: rel2, zelariRoot })) {
32809
+ args.changedFiles.add(w.file ?? rel2);
32810
+ }
32811
+ }
32812
+ }
32813
+ const finalReport = runImplementationVerification({
32814
+ projectRoot: args.projectRoot,
32815
+ zelariRoot
32395
32816
  });
32396
- const messages = [
32397
- { role: "system", content: split.stable }
32398
- ];
32399
- if (split.volatile.trim()) {
32400
- messages.push({ role: "system", content: split.volatile });
32817
+ return filterDeliveryBlockingFails(finalReport.results).length === 0;
32818
+ }
32819
+ var MAX_DELIVERY_ATTEMPTS;
32820
+ var init_chairmanDelivery = __esm({
32821
+ "packages/core/dist/agents/council/chairmanDelivery.js"() {
32822
+ "use strict";
32823
+ init_microGate();
32824
+ init_completion();
32825
+ init_implementationDelivery();
32826
+ init_runChecks();
32827
+ init_inlineJsAutofix();
32828
+ init_retryTurn();
32829
+ MAX_DELIVERY_ATTEMPTS = 2;
32401
32830
  }
32402
- messages.push({ role: "system", content: councilModeBanner(runMode, { isImplementer: agent.id === "lucifer" }) }, { role: "system", content: "IMPORTANT: Before making any tool calls or expensive operations, check if the information already exists in the shared context from previous agents. Avoid redundant work." });
32403
- if (priorOutputs.length > 0) {
32404
- const MAX_PRIOR_CHARS = 2800;
32405
- const summary = priorOutputs.map((o) => {
32406
- const body = o.content.length > MAX_PRIOR_CHARS ? `${o.content.slice(0, MAX_PRIOR_CHARS)}
32407
- \u2026 [truncated ${o.content.length}\u2192${MAX_PRIOR_CHARS} chars; treat as hypothesis]` : o.content;
32408
- return `[${o.name} - ${o.role}]: ${body}`;
32409
- }).join("\n\n");
32410
- messages.push({
32411
- role: "user",
32412
- content: `Previous council members have said (hypotheses \u2014 prefer product files on disk if they conflict):
32413
- ${summary}
32831
+ });
32414
32832
 
32415
- Original user request: ${userMessage}`
32833
+ // packages/core/dist/agents/council/chairmanFixLoop.js
32834
+ async function* replayChairmanTextTools(args) {
32835
+ const tools = parseTextToolCalls(args.synthesisText);
32836
+ if (tools.length === 0)
32837
+ return 0;
32838
+ let applied = 0;
32839
+ for (const tt of tools) {
32840
+ if (tt.name !== "edit_file" && tt.name !== "write_file")
32841
+ continue;
32842
+ const normalized = normalizeTextToolArgs(tt.name, tt.args);
32843
+ const toolCallId = `replay-${crypto.randomUUID().slice(0, 8)}`;
32844
+ yield createBrainEvent("tool_execution_start", args.sessionId, {
32845
+ toolCallId,
32846
+ toolName: tt.name,
32847
+ args: normalized,
32848
+ ...args.memberId ? { memberId: args.memberId } : {}
32849
+ });
32850
+ const startMs = Date.now();
32851
+ let resultStr = "";
32852
+ let isError = false;
32853
+ try {
32854
+ const result = await args.toolRegistry.invoke(tt.name, normalized, {
32855
+ cwd: args.projectRoot,
32856
+ sessionId: args.sessionId
32857
+ });
32858
+ if (result.ok) {
32859
+ const val = result.value;
32860
+ if (tt.name === "edit_file" && val.occurrencesReplaced === 0) {
32861
+ resultStr = `edit_file: no match for oldString (replay)`;
32862
+ isError = true;
32863
+ } else {
32864
+ resultStr = typeof result.value === "string" ? result.value : JSON.stringify(result.value, null, 2);
32865
+ applied += 1;
32866
+ }
32867
+ } else {
32868
+ resultStr = result.error;
32869
+ isError = true;
32870
+ }
32871
+ } catch (err) {
32872
+ resultStr = err instanceof Error ? err.message : String(err);
32873
+ isError = true;
32874
+ }
32875
+ yield createBrainEvent("tool_execution_end", args.sessionId, {
32876
+ toolCallId,
32877
+ result: resultStr,
32878
+ isError,
32879
+ durationMs: Date.now() - startMs
32416
32880
  });
32417
- } else {
32418
- messages.push({ role: "user", content: userMessage });
32419
32881
  }
32420
- return messages;
32882
+ return applied;
32883
+ }
32884
+ async function* runChairmanFixLoop(args) {
32885
+ const maxAttempts = args.maxAttempts ?? 3;
32886
+ const zelariRoot = `${args.projectRoot}/.zelari`;
32887
+ let current = Array.from(args.violations.values());
32888
+ let attempt = 0;
32889
+ while (current.length > 0 && attempt < maxAttempts) {
32890
+ attempt++;
32891
+ try {
32892
+ const fixGenerator = runRetryTurnForMember({
32893
+ agent: args.chairman,
32894
+ missingToolNames: ["read_file", "edit_file"],
32895
+ minPerTool: { read_file: 2, edit_file: 8 },
32896
+ executableTools: args.executableNames,
32897
+ userMessage: args.userMessage,
32898
+ ragContext: args.config.ragContext,
32899
+ workspaceContext: args.config.workspaceContext,
32900
+ priorOutputs: args.agentOutputs,
32901
+ aiConfig: args.config.aiConfig,
32902
+ sessionId: args.sessionId,
32903
+ effectiveModel: args.effectiveModel,
32904
+ effectiveProvider: args.effectiveProvider,
32905
+ eventBus: args.config.eventBus,
32906
+ toolRegistry: args.config.tools,
32907
+ providerStream: args.config.providerStream,
32908
+ runMode: "implementation",
32909
+ retryPrompt: buildMotionFixPrompt(current),
32910
+ languageModule: args.languageModule
32911
+ });
32912
+ for await (const event of fixGenerator) {
32913
+ if (event.type === "tool_execution_start")
32914
+ args.onToolCall?.();
32915
+ yield event;
32916
+ }
32917
+ } catch (fixErr) {
32918
+ console.error(`[council] chairman fix pass ${attempt} failed:`, fixErr);
32919
+ break;
32920
+ }
32921
+ const rescanned = /* @__PURE__ */ new Map();
32922
+ for (const relPath of args.changedFiles) {
32923
+ for (const w of runChairmanMicroGate({ projectRoot: args.projectRoot, relPath, zelariRoot })) {
32924
+ rescanned.set(`${w.id}|${w.file}|${w.line ?? ""}`, w);
32925
+ }
32926
+ }
32927
+ current = Array.from(rescanned.values());
32928
+ }
32421
32929
  }
32930
+ var init_chairmanFixLoop = __esm({
32931
+ "packages/core/dist/agents/council/chairmanFixLoop.js"() {
32932
+ "use strict";
32933
+ init_AgentHarness();
32934
+ init_events();
32935
+ init_microGate();
32936
+ init_chairmanDelivery();
32937
+ init_retryTurn();
32938
+ }
32939
+ });
32940
+
32941
+ // packages/core/dist/agents/councilApi.js
32942
+ import { existsSync as existsSync12 } from "node:fs";
32943
+ import { join as join8 } from "node:path";
32422
32944
  async function* runCouncilPure(userMessage, config2, callbacks = {}) {
32423
32945
  const baseAgents = getCouncilAgents(config2.councilSize);
32424
32946
  const agents = swapMembers(baseAgents, config2.memberSwap ?? {});
@@ -33029,473 +33551,34 @@ async function* runCouncilPure(userMessage, config2, callbacks = {}) {
33029
33551
  durationMs: 0
33030
33552
  };
33031
33553
  }
33032
- async function* applyCompletionRetry(args) {
33033
- const check2 = checkImplementationCompletion(args.emittedToolNames);
33034
- if (check2.ok)
33035
- return;
33036
- const retryTool = resolveVerifyRetryTool(args.executableNames);
33037
- if (!retryTool) {
33038
- console.warn("[council] implementation verify retry skipped \u2014 no grep_content/bash in registry");
33039
- return;
33040
- }
33041
- if (!shouldRetryMember([retryTool], 0))
33042
- return;
33043
- console.warn(`[council] ${args.agent.id} retrying missing verify tool: ${retryTool}`);
33044
- try {
33045
- const retryGenerator = runRetryTurnForMember({
33046
- agent: args.agent,
33047
- missingToolNames: [retryTool],
33048
- executableTools: args.executableNames,
33049
- userMessage: args.userMessage,
33050
- ragContext: args.config.ragContext,
33051
- workspaceContext: args.config.workspaceContext,
33052
- priorOutputs: args.agentOutputs,
33053
- aiConfig: args.config.aiConfig,
33054
- sessionId: args.sessionId,
33055
- effectiveModel: args.effectiveModel,
33056
- effectiveProvider: args.effectiveProvider,
33057
- eventBus: args.config.eventBus,
33058
- toolRegistry: args.config.tools,
33059
- providerStream: args.config.providerStream,
33060
- runMode: args.config.runMode,
33061
- retryPrompt: buildImplementationVerifyRetryPrompt(retryTool),
33062
- languageModule: args.languageModule
33063
- });
33064
- for await (const event of retryGenerator) {
33065
- if (event.type === "tool_execution_start") {
33066
- args.onToolCall();
33067
- args.emittedToolNames.push(event.toolName);
33068
- }
33069
- yield event;
33070
- }
33071
- } catch (retryErr) {
33072
- console.error(`[council] ${args.agent.id} verify retry failed:`, retryErr);
33073
- }
33074
- const after = checkImplementationCompletion(args.emittedToolNames);
33075
- if (!after.ok) {
33076
- console.warn(`[council] ${args.agent.id} still missing verify after retry: ${after.reason}`);
33077
- }
33078
- }
33079
- function buildMotionFixPrompt(violations) {
33080
- const byFile = /* @__PURE__ */ new Map();
33081
- for (const v of violations) {
33082
- const file2 = v.file || "index.html";
33083
- const loc = v.line ? `${file2}:L${v.line}` : file2;
33084
- const list = byFile.get(file2) ?? [];
33085
- list.push(` - ${loc}: ${v.message}`);
33086
- byFile.set(file2, list);
33087
- }
33088
- const blocks = Array.from(byFile.values()).map((lines) => lines.join("\n")).join("\n");
33089
- return `Deterministic verification found ${violations.length} motion violation(s) in the file(s) you just edited. Fix ONLY these \u2014 do not add features, do not rewrite sections, do not touch anything else:
33090
- ${blocks}
33091
-
33092
- Rules: animate ONLY transform and opacity. Replace any box-shadow / background / background-position / filter / color / border-color / width / height / grid-template-rows used in @keyframes or transitions with transform/opacity equivalents (e.g. render a glow via a pseudo-element that scales and fades). For every classList.add('x') in the script, add a matching '.x' CSS rule. Use read_file to see the exact lines, then edit_file. When the listed items are fixed, stop \u2014 no summary.`;
33093
- }
33094
- async function* applyImplementationWriteRetry(args) {
33095
- if (args.check.ok)
33096
- return;
33097
- if (!shouldRetryMember(["write_file"], 0))
33098
- return;
33099
- const statusMsg = `[council] ${args.chairman.id} implementation write retry: ${args.check.missing.join(", ")}`;
33100
- args.onCouncilStatus?.(statusMsg);
33101
- console.warn(statusMsg);
33102
- try {
33103
- const retryGenerator = runRetryTurnForMember({
33104
- agent: args.chairman,
33105
- missingToolNames: ["read_file", "write_file", "edit_file"],
33106
- minPerTool: { read_file: 3, edit_file: 8, write_file: 1 },
33107
- executableTools: args.executableNames,
33108
- userMessage: args.userMessage,
33109
- ragContext: args.config.ragContext,
33110
- workspaceContext: args.config.workspaceContext,
33111
- priorOutputs: args.agentOutputs,
33112
- aiConfig: args.config.aiConfig,
33113
- sessionId: args.sessionId,
33114
- effectiveModel: args.effectiveModel,
33115
- effectiveProvider: args.effectiveProvider,
33116
- eventBus: args.config.eventBus,
33117
- toolRegistry: args.config.tools,
33118
- providerStream: args.config.providerStream,
33119
- runMode: "implementation",
33120
- retryPrompt: buildImplementationWriteRetryPrompt(args.userMessage),
33121
- languageModule: args.languageModule
33122
- });
33123
- for await (const event of retryGenerator) {
33124
- if (event.type === "tool_execution_start")
33125
- args.onToolCall?.();
33126
- if (event.type === "tool_execution_end" && !event.isError && typeof event.result === "string") {
33127
- try {
33128
- const parsed = JSON.parse(event.result);
33129
- if ((parsed.bytesWritten ?? 0) > 0 || (parsed.occurrencesReplaced ?? 0) > 0) {
33130
- args.onSuccessfulWrite?.();
33131
- }
33132
- } catch {
33133
- if (event.result.includes("bytesWritten") || event.result.includes("occurrencesReplaced")) {
33134
- args.onSuccessfulWrite?.();
33135
- }
33136
- }
33137
- }
33138
- yield event;
33139
- }
33140
- } catch (retryErr) {
33141
- console.error(`[council] ${args.chairman.id} implementation write retry failed:`, retryErr);
33142
- }
33143
- }
33144
- async function* runChairmanDeliveryLoop(args) {
33145
- const maxAttempts = args.maxAttempts ?? MAX_DELIVERY_ATTEMPTS;
33146
- const zelariRoot = `${args.projectRoot}/.zelari`;
33147
- let attempt = 0;
33148
- while (attempt < maxAttempts) {
33149
- const report = runImplementationVerification({
33150
- projectRoot: args.projectRoot,
33151
- zelariRoot
33152
- });
33153
- const blocking = filterDeliveryBlockingFails(report.results);
33154
- if (blocking.length === 0)
33155
- return true;
33156
- if (blocking.some((b) => b.id === "inline-js.budget")) {
33157
- const jsFix = applyInlineJsAutofix(args.projectRoot, report);
33158
- if (jsFix.applied) {
33159
- args.onCouncilStatus?.(`[council] ${args.chairman.id} inline-js autofix: ${jsFix.fixes.join("; ")}`);
33160
- const afterJs = runImplementationVerification({
33161
- projectRoot: args.projectRoot,
33162
- zelariRoot
33163
- });
33164
- if (filterDeliveryBlockingFails(afterJs.results).length === 0)
33165
- return true;
33166
- }
33167
- }
33168
- attempt++;
33169
- const statusMsg = `[council] ${args.chairman.id} delivery pass ${attempt}/${maxAttempts}: ${blocking.map((b) => b.id).join(", ")}`;
33170
- args.onCouncilStatus?.(statusMsg);
33171
- console.warn(statusMsg);
33172
- try {
33173
- const fixGenerator = runRetryTurnForMember({
33174
- agent: args.chairman,
33175
- missingToolNames: ["read_file", "edit_file"],
33176
- minPerTool: { read_file: 3, edit_file: 10 },
33177
- executableTools: args.executableNames,
33178
- userMessage: args.userMessage,
33179
- ragContext: args.config.ragContext,
33180
- workspaceContext: args.config.workspaceContext,
33181
- priorOutputs: args.agentOutputs,
33182
- aiConfig: args.config.aiConfig,
33183
- sessionId: args.sessionId,
33184
- effectiveModel: args.effectiveModel,
33185
- effectiveProvider: args.effectiveProvider,
33186
- eventBus: args.config.eventBus,
33187
- toolRegistry: args.config.tools,
33188
- providerStream: args.config.providerStream,
33189
- runMode: "implementation",
33190
- retryPrompt: buildDeliveryFixPrompt(blocking, args.userMessage),
33191
- languageModule: args.languageModule
33192
- });
33193
- for await (const event of fixGenerator) {
33194
- if (event.type === "tool_execution_start")
33195
- args.onToolCall?.();
33196
- yield event;
33197
- }
33198
- } catch (deliveryErr) {
33199
- console.error(`[council] ${args.chairman.id} delivery pass ${attempt} failed:`, deliveryErr);
33200
- break;
33201
- }
33202
- for (const rel2 of args.changedFiles) {
33203
- for (const w of runChairmanMicroGate({ projectRoot: args.projectRoot, relPath: rel2, zelariRoot })) {
33204
- args.changedFiles.add(w.file ?? rel2);
33205
- }
33206
- }
33207
- }
33208
- const finalReport = runImplementationVerification({
33209
- projectRoot: args.projectRoot,
33210
- zelariRoot
33211
- });
33212
- return filterDeliveryBlockingFails(finalReport.results).length === 0;
33213
- }
33214
- async function* replayChairmanTextTools(args) {
33215
- const tools = parseTextToolCalls(args.synthesisText);
33216
- if (tools.length === 0)
33217
- return 0;
33218
- let applied = 0;
33219
- for (const tt of tools) {
33220
- if (tt.name !== "edit_file" && tt.name !== "write_file")
33221
- continue;
33222
- const normalized = normalizeTextToolArgs(tt.name, tt.args);
33223
- const toolCallId = `replay-${crypto.randomUUID().slice(0, 8)}`;
33224
- yield createBrainEvent("tool_execution_start", args.sessionId, {
33225
- toolCallId,
33226
- toolName: tt.name,
33227
- args: normalized,
33228
- ...args.memberId ? { memberId: args.memberId } : {}
33229
- });
33230
- const startMs = Date.now();
33231
- let resultStr = "";
33232
- let isError = false;
33233
- try {
33234
- const result = await args.toolRegistry.invoke(tt.name, normalized, {
33235
- cwd: args.projectRoot,
33236
- sessionId: args.sessionId
33237
- });
33238
- if (result.ok) {
33239
- const val = result.value;
33240
- if (tt.name === "edit_file" && val.occurrencesReplaced === 0) {
33241
- resultStr = `edit_file: no match for oldString (replay)`;
33242
- isError = true;
33243
- } else {
33244
- resultStr = typeof result.value === "string" ? result.value : JSON.stringify(result.value, null, 2);
33245
- applied += 1;
33246
- }
33247
- } else {
33248
- resultStr = result.error;
33249
- isError = true;
33250
- }
33251
- } catch (err) {
33252
- resultStr = err instanceof Error ? err.message : String(err);
33253
- isError = true;
33254
- }
33255
- yield createBrainEvent("tool_execution_end", args.sessionId, {
33256
- toolCallId,
33257
- result: resultStr,
33258
- isError,
33259
- durationMs: Date.now() - startMs
33260
- });
33261
- }
33262
- return applied;
33263
- }
33264
- async function* runChairmanFixLoop(args) {
33265
- const maxAttempts = args.maxAttempts ?? 3;
33266
- const zelariRoot = `${args.projectRoot}/.zelari`;
33267
- let current = Array.from(args.violations.values());
33268
- let attempt = 0;
33269
- while (current.length > 0 && attempt < maxAttempts) {
33270
- attempt++;
33271
- try {
33272
- const fixGenerator = runRetryTurnForMember({
33273
- agent: args.chairman,
33274
- missingToolNames: ["read_file", "edit_file"],
33275
- minPerTool: { read_file: 2, edit_file: 8 },
33276
- executableTools: args.executableNames,
33277
- userMessage: args.userMessage,
33278
- ragContext: args.config.ragContext,
33279
- workspaceContext: args.config.workspaceContext,
33280
- priorOutputs: args.agentOutputs,
33281
- aiConfig: args.config.aiConfig,
33282
- sessionId: args.sessionId,
33283
- effectiveModel: args.effectiveModel,
33284
- effectiveProvider: args.effectiveProvider,
33285
- eventBus: args.config.eventBus,
33286
- toolRegistry: args.config.tools,
33287
- providerStream: args.config.providerStream,
33288
- runMode: "implementation",
33289
- retryPrompt: buildMotionFixPrompt(current),
33290
- languageModule: args.languageModule
33291
- });
33292
- for await (const event of fixGenerator) {
33293
- if (event.type === "tool_execution_start")
33294
- args.onToolCall?.();
33295
- yield event;
33296
- }
33297
- } catch (fixErr) {
33298
- console.error(`[council] chairman fix pass ${attempt} failed:`, fixErr);
33299
- break;
33300
- }
33301
- const rescanned = /* @__PURE__ */ new Map();
33302
- for (const relPath of args.changedFiles) {
33303
- for (const w of runChairmanMicroGate({ projectRoot: args.projectRoot, relPath, zelariRoot })) {
33304
- rescanned.set(`${w.id}|${w.file}|${w.line ?? ""}`, w);
33305
- }
33306
- }
33307
- current = Array.from(rescanned.values());
33308
- }
33309
- }
33310
- function checkMemberToolEmissions(_memberId, emittedToolNames, requirements) {
33311
- if (requirements.length === 0) {
33312
- return { ok: true, missing: [] };
33313
- }
33314
- const counts = /* @__PURE__ */ new Map();
33315
- for (const name of emittedToolNames) {
33316
- counts.set(name, (counts.get(name) ?? 0) + 1);
33317
- }
33318
- const missing = [];
33319
- for (const req of requirements) {
33320
- const got = counts.get(req.name) ?? 0;
33321
- if (got < req.min) {
33322
- missing.push(`${req.name} (got ${got}, need >= ${req.min})`);
33323
- }
33324
- }
33325
- return { ok: missing.length === 0, missing };
33326
- }
33327
- function checkMemberToolEmissionSets(memberId, emittedToolNames, sets) {
33328
- if (sets.length === 0) {
33329
- return { ok: true, missing: [] };
33330
- }
33331
- const results = sets.map((set2) => checkMemberToolEmissions(memberId, emittedToolNames, set2));
33332
- if (results.some((r) => r.ok)) {
33333
- return { ok: true, missing: [] };
33334
- }
33335
- return results[0];
33336
- }
33337
- function enforceDesignPhaseToolEmissions(memberId, emittedToolNames) {
33338
- const sets = DESIGN_PHASE_REQUIREMENT_SETS[memberId];
33339
- if (!sets || sets.length === 0) {
33340
- return { ok: true, missing: [] };
33341
- }
33342
- const result = checkMemberToolEmissionSets(memberId, emittedToolNames, sets);
33343
- if (!result.ok) {
33344
- console.warn(`[council] member "${memberId}" did not emit required tools: ${result.missing.join(", ")}. The downstream .zelari/ deliverable may be incomplete. (A forced retry turn scoped to the missing tools follows; the deterministic complete-design fallback covers any remaining gap.)`);
33345
- }
33346
- return result;
33347
- }
33348
- function shouldRetryMember(missingToolNames, attemptsSoFar) {
33349
- if (missingToolNames.length === 0)
33350
- return false;
33351
- if (attemptsSoFar >= MAX_RETRY_PER_MEMBER)
33352
- return false;
33353
- return true;
33354
- }
33355
- function buildRetryPrompt(missingToolNames) {
33356
- const names = missingToolNames.join(", ");
33357
- return `You did not emit the required workspace tools: ${names}. Call ${names} NOW with concrete arguments. No prose. No search.`;
33358
- }
33359
- async function* runRetryTurnForMember(args) {
33360
- const executableMissing = args.executableTools ? args.missingToolNames.filter((n) => args.executableTools.has(n)) : args.missingToolNames;
33361
- if (executableMissing.length === 0) {
33362
- return [];
33363
- }
33364
- const retryToolNames = executableMissing;
33365
- const retryToolSpecs = getProviderTools(retryToolNames).map((t) => ({
33366
- name: t.function.name,
33367
- description: t.function.description,
33368
- parameters: t.function.parameters
33369
- }));
33370
- const baseMessages = buildAgentMessages(args.agent, args.userMessage, args.ragContext, args.workspaceContext, args.priorOutputs, args.aiConfig, args.executableTools, args.runMode ?? "implementation", args.languageModule);
33371
- const retryMessages = [
33372
- ...baseMessages,
33373
- {
33374
- role: "user",
33375
- content: args.retryPrompt ?? buildRetryPrompt(executableMissing)
33376
- }
33377
- ];
33378
- const maxToolCalls = args.minPerTool !== void 0 ? Object.entries(args.minPerTool).filter(([name]) => executableMissing.includes(name)).reduce((sum, [, min]) => sum + min, 0) : retryToolNames.length;
33379
- const retryHarness = new AgentHarness({
33380
- model: args.effectiveModel,
33381
- provider: args.effectiveProvider,
33382
- sessionId: args.sessionId,
33383
- messages: retryMessages,
33384
- tools: retryToolSpecs,
33385
- eventBus: args.eventBus,
33386
- toolRegistry: args.toolRegistry,
33387
- // Budget the retry so the model can satisfy every requirement in
33388
- // ONE tool_calls turn. For createTask min:12 this needs 12 calls.
33389
- maxToolCallsPerTurn: maxToolCalls,
33390
- memberId: args.agent.id,
33391
- memberName: args.agent.name,
33392
- providerStream: (params) => args.providerStream(params)
33393
- });
33394
- const retryEmitted = [];
33395
- for await (const event of retryHarness.run()) {
33396
- if (event.type === "tool_execution_start") {
33397
- retryEmitted.push(event.toolName);
33398
- }
33399
- yield event;
33400
- }
33401
- return retryEmitted;
33402
- }
33403
- async function* applyRetryIfMissing(args) {
33404
- if (args.check.ok)
33405
- return;
33406
- const missingToolNames = args.check.missing.map((m) => m.split(" ")[0]);
33407
- if (!shouldRetryMember(missingToolNames, 0))
33408
- return;
33409
- console.warn(`[council] ${args.agent.id} retrying missing tools: ${missingToolNames.join(", ")}`);
33410
- const minPerTool = {};
33411
- if (args.requirements) {
33412
- for (const req of args.requirements) {
33413
- if (missingToolNames.includes(req.name)) {
33414
- minPerTool[req.name] = req.min;
33415
- }
33416
- }
33417
- }
33418
- try {
33419
- const retryGenerator = runRetryTurnForMember({
33420
- agent: args.agent,
33421
- missingToolNames,
33422
- minPerTool,
33423
- executableTools: args.executableNames,
33424
- userMessage: args.userMessage,
33425
- ragContext: args.config.ragContext,
33426
- workspaceContext: args.config.workspaceContext,
33427
- priorOutputs: args.agentOutputs,
33428
- aiConfig: args.config.aiConfig,
33429
- sessionId: args.sessionId,
33430
- effectiveModel: args.effectiveModel,
33431
- effectiveProvider: args.effectiveProvider,
33432
- eventBus: args.config.eventBus,
33433
- toolRegistry: args.config.tools,
33434
- providerStream: args.config.providerStream,
33435
- runMode: args.config.runMode,
33436
- languageModule: args.languageModule
33437
- });
33438
- for await (const event of retryGenerator) {
33439
- if (event.type === "tool_execution_start") {
33440
- args.onToolCall();
33441
- args.emittedToolNames.push(event.toolName);
33442
- }
33443
- yield event;
33444
- }
33445
- } catch (retryErr) {
33446
- console.error(`[council] ${args.agent.id} retry failed:`, retryErr);
33447
- }
33448
- enforceDesignPhaseToolEmissions(args.agent.id, args.emittedToolNames);
33449
- }
33450
- var NON_RETRY_AGENTS, QUESTION_MARKER, QUESTION_END_MARKER, MUTATING_PROJECT_TOOLS, MAX_DELIVERY_ATTEMPTS, DESIGN_PHASE_REQUIREMENT_SETS, DESIGN_PHASE_REQUIREMENTS, MAX_RETRY_PER_MEMBER;
33451
33554
  var init_councilApi = __esm({
33452
33555
  "packages/core/dist/agents/councilApi.js"() {
33453
33556
  "use strict";
33454
33557
  init_roles();
33455
33558
  init_toolSchemas();
33456
33559
  init_systemPromptBuilder();
33457
- init_tools();
33458
33560
  init_languagePolicy();
33459
- init_secrecyPolicy();
33460
33561
  init_events();
33461
33562
  init_AgentHarness();
33462
- init_modeBanners();
33463
33563
  init_runMode();
33464
33564
  init_microGate();
33465
- init_completion();
33466
33565
  init_nfrSpecWarn();
33467
33566
  init_runChecks();
33468
33567
  init_implementationDelivery();
33469
- init_inlineJsAutofix();
33470
- NON_RETRY_AGENTS = /* @__PURE__ */ new Set([]);
33471
- QUESTION_MARKER = "---QUESTION---";
33472
- QUESTION_END_MARKER = "---END---";
33473
- MUTATING_PROJECT_TOOLS = ["write_file", "edit_file"];
33474
- MAX_DELIVERY_ATTEMPTS = 2;
33475
- DESIGN_PHASE_REQUIREMENT_SETS = {
33476
- nettun: [
33477
- [{ name: "createPlan", min: 1 }],
33478
- [
33479
- { name: "createPhase", min: 3 },
33480
- { name: "createTask", min: 6 },
33481
- { name: "createMilestone", min: 1 }
33482
- ]
33483
- ],
33484
- geryon: [
33485
- [{ name: "createDocument", min: 3 }]
33486
- ],
33487
- pluton: [
33488
- [{ name: "createDocument", min: 1 }]
33489
- ],
33490
- minos: [
33491
- [{ name: "createDocument", min: 1 }]
33492
- ],
33493
- lucifer: [
33494
- [{ name: "createDocument", min: 1 }]
33495
- ]
33496
- };
33497
- DESIGN_PHASE_REQUIREMENTS = Object.fromEntries(Object.entries(DESIGN_PHASE_REQUIREMENT_SETS).map(([id3, sets]) => [id3, sets[0]]));
33498
- MAX_RETRY_PER_MEMBER = 1;
33568
+ init_types7();
33569
+ init_types7();
33570
+ init_outputCleaning();
33571
+ init_outputCleaning();
33572
+ init_memberMessages();
33573
+ init_memberMessages();
33574
+ init_chairmanDelivery();
33575
+ init_chairmanDelivery();
33576
+ init_chairmanFixLoop();
33577
+ init_chairmanFixLoop();
33578
+ init_toolEmission();
33579
+ init_toolEmission();
33580
+ init_retryTurn();
33581
+ init_retryTurn();
33499
33582
  }
33500
33583
  });
33501
33584
 
@@ -33632,7 +33715,7 @@ var init_missionBrief = __esm({
33632
33715
  });
33633
33716
 
33634
33717
  // packages/core/dist/council/verification/types.js
33635
- var init_types7 = __esm({
33718
+ var init_types8 = __esm({
33636
33719
  "packages/core/dist/council/verification/types.js"() {
33637
33720
  "use strict";
33638
33721
  }
@@ -33836,7 +33919,7 @@ var init_autofix = __esm({
33836
33919
  var init_verification2 = __esm({
33837
33920
  "packages/core/dist/council/verification/index.js"() {
33838
33921
  "use strict";
33839
- init_types7();
33922
+ init_types8();
33840
33923
  init_runChecks();
33841
33924
  init_honesty();
33842
33925
  init_parseCssMotion();
@@ -33854,7 +33937,7 @@ var init_verification2 = __esm({
33854
33937
  });
33855
33938
 
33856
33939
  // packages/core/dist/council/lessons/types.js
33857
- var init_types8 = __esm({
33940
+ var init_types9 = __esm({
33858
33941
  "packages/core/dist/council/lessons/types.js"() {
33859
33942
  "use strict";
33860
33943
  }
@@ -34107,7 +34190,7 @@ var init_recallLessons = __esm({
34107
34190
  var init_lessons = __esm({
34108
34191
  "packages/core/dist/council/lessons/index.js"() {
34109
34192
  "use strict";
34110
- init_types8();
34193
+ init_types9();
34111
34194
  init_io();
34112
34195
  init_isAnswerLeak();
34113
34196
  init_signatures();
@@ -34117,7 +34200,7 @@ var init_lessons = __esm({
34117
34200
  });
34118
34201
 
34119
34202
  // packages/core/dist/council/completion/types.js
34120
- var init_types9 = __esm({
34203
+ var init_types10 = __esm({
34121
34204
  "packages/core/dist/council/completion/types.js"() {
34122
34205
  "use strict";
34123
34206
  }
@@ -34198,7 +34281,7 @@ var init_buildCompletion = __esm({
34198
34281
  var init_completion2 = __esm({
34199
34282
  "packages/core/dist/council/completion/index.js"() {
34200
34283
  "use strict";
34201
- init_types9();
34284
+ init_types10();
34202
34285
  init_buildCompletion();
34203
34286
  }
34204
34287
  });
@@ -34521,7 +34604,7 @@ var init_council = __esm({
34521
34604
 
34522
34605
  // packages/core/dist/memory/types.js
34523
34606
  var MEMORY_SCHEMA_VERSION, MEMORY_KINDS, MEMORY_STATUSES, MEMORY_RELATIONS, MEMORY_VISIBILITIES;
34524
- var init_types10 = __esm({
34607
+ var init_types11 = __esm({
34525
34608
  "packages/core/dist/memory/types.js"() {
34526
34609
  "use strict";
34527
34610
  MEMORY_SCHEMA_VERSION = 1;
@@ -34572,7 +34655,7 @@ var init_schemas3 = __esm({
34572
34655
  "packages/core/dist/memory/schemas.js"() {
34573
34656
  "use strict";
34574
34657
  init_zod();
34575
- init_types10();
34658
+ init_types11();
34576
34659
  isoDate = external_exports.string().datetime({ offset: true });
34577
34660
  unit = external_exports.number().finite().min(0).max(1);
34578
34661
  metadata = external_exports.record(external_exports.string(), external_exports.unknown()).refine((value) => {
@@ -35864,7 +35947,7 @@ var init_noop = __esm({
35864
35947
  var init_memory = __esm({
35865
35948
  "packages/core/dist/memory/index.js"() {
35866
35949
  "use strict";
35867
- init_types10();
35950
+ init_types11();
35868
35951
  init_schemas3();
35869
35952
  init_scoring();
35870
35953
  init_policies();
@@ -36586,7 +36669,7 @@ var init_personas = __esm({
36586
36669
 
36587
36670
  // packages/core/dist/kraken/runtime/types.js
36588
36671
  var PlanError;
36589
- var init_types11 = __esm({
36672
+ var init_types12 = __esm({
36590
36673
  "packages/core/dist/kraken/runtime/types.js"() {
36591
36674
  "use strict";
36592
36675
  PlanError = class extends Error {
@@ -36684,7 +36767,7 @@ var MAX_BUNDLE_BYTES, FORBIDDEN_TOKENS;
36684
36767
  var init_sandbox = __esm({
36685
36768
  "packages/core/dist/kraken/runtime/sandbox.js"() {
36686
36769
  "use strict";
36687
- init_types11();
36770
+ init_types12();
36688
36771
  MAX_BUNDLE_BYTES = 256 * 1024;
36689
36772
  FORBIDDEN_TOKENS = [
36690
36773
  /\bprocess\b/,
@@ -36747,7 +36830,7 @@ var init_runner = __esm({
36747
36830
  "use strict";
36748
36831
  init_verdict();
36749
36832
  init_personas();
36750
- init_types11();
36833
+ init_types12();
36751
36834
  DEFAULT_MAX_TENTACLES = 200;
36752
36835
  DEFAULT_PLAN_TIMEOUT_MS = 30 * 6e4;
36753
36836
  ScriptRunner = class {
@@ -36931,7 +37014,7 @@ var init_runner = __esm({
36931
37014
  var init_runtime2 = __esm({
36932
37015
  "packages/core/dist/kraken/runtime/index.js"() {
36933
37016
  "use strict";
36934
- init_types11();
37017
+ init_types12();
36935
37018
  init_sandbox();
36936
37019
  init_runner();
36937
37020
  }
@@ -38031,7 +38114,7 @@ var CORE_VERSION;
38031
38114
  var init_version = __esm({
38032
38115
  "packages/core/dist/version.js"() {
38033
38116
  "use strict";
38034
- CORE_VERSION = "2.33.1";
38117
+ CORE_VERSION = "2.34.0";
38035
38118
  }
38036
38119
  });
38037
38120
 
@@ -46009,6 +46092,27 @@ ${findings || "(the reviewer reported FAIL without detail)"}`;
46009
46092
  async function runAutoVerifyAfterGeneral(opts) {
46010
46093
  const g = globalThis;
46011
46094
  g.__zelariGeneralVerifyDebt = { description: opts.original.description };
46095
+ const emitVerifyPhase = (detail2, ok) => {
46096
+ const agentId = opts.general.agentId;
46097
+ if (agentId) {
46098
+ opts.deps.onTentacleEvent?.({
46099
+ type: "agent_status",
46100
+ agentId,
46101
+ status: "running",
46102
+ message: detail2,
46103
+ id: randomUUID4(),
46104
+ sessionId: opts.sessionId,
46105
+ ts: Date.now()
46106
+ });
46107
+ }
46108
+ appendKrakenRadio(opts.parentCwd, opts.sessionId, {
46109
+ kind: "progress",
46110
+ agent: "verify",
46111
+ description: `verify: ${opts.original.description}`,
46112
+ detail: detail2,
46113
+ ...ok === void 0 ? {} : { ok }
46114
+ });
46115
+ };
46012
46116
  const inheritedCwd = opts.general.worktreePath && existsSync26(opts.general.worktreePath) ? opts.general.worktreePath : void 0;
46013
46117
  const runVerify = (label) => runTentacle({
46014
46118
  deps: opts.deps,
@@ -46025,6 +46129,7 @@ async function runAutoVerifyAfterGeneral(opts) {
46025
46129
  sessionId: opts.sessionId,
46026
46130
  ...opts.signal ? { signal: opts.signal } : {}
46027
46131
  });
46132
+ emitVerifyPhase("verifying\u2026");
46028
46133
  let verify = await runVerify(`verify: ${opts.original.description}`);
46029
46134
  let verdict = verify.ok ? parseVerifyVerdict(verify.result).verdict : "unknown";
46030
46135
  let findings = verify.ok ? parseVerifyVerdict(verify.result).findings : "";
@@ -46072,10 +46177,15 @@ async function runAutoVerifyAfterGeneral(opts) {
46072
46177
  }
46073
46178
  if (verdict === "pass") {
46074
46179
  g.__zelariGeneralVerifyDebt = null;
46180
+ emitVerifyPhase("verify PASS", true);
46075
46181
  return `
46076
46182
 
46077
46183
  [kraken:auto-verify] verify PASS \u2014 general\u21D2verify obligation satisfied.`;
46078
46184
  }
46185
+ emitVerifyPhase(
46186
+ verdict === "fail" ? "verify FAIL" : verify.ok ? "verify unknown" : "verify failed",
46187
+ verdict === "fail" || !verify.ok ? false : void 0
46188
+ );
46079
46189
  const detail = verdict === "fail" ? `verify FAIL unresolved (rework budget spent): ${findings || "no findings reported"}` : verify.ok ? "verify produced no parseable VERDICT \u2014 unverified" : `verify tentacle failed: ${verify.error}`;
46080
46190
  g.__zelariGeneralVerifyDebt = { description: opts.original.description, detail };
46081
46191
  appendKrakenRadio(opts.parentCwd, opts.sessionId, {
@@ -46231,6 +46341,11 @@ async function runSubAgent(harness, opts = {}) {
46231
46341
  signal?.removeEventListener("abort", onAbort);
46232
46342
  }
46233
46343
  }
46344
+ function shortWorktreeCaption(p3) {
46345
+ const parts = p3.split(/[\\/]/).filter(Boolean);
46346
+ const short2 = parts.length > 2 ? `.../${parts.slice(-2).join("/")}` : p3;
46347
+ return short2.length > 50 ? `...${short2.slice(-47)}` : short2;
46348
+ }
46234
46349
  async function runTentacle(opts) {
46235
46350
  const { deps, args, agent, thoroughness, parentCwd, sessionId: sessionId2 } = opts;
46236
46351
  const started = Date.now();
@@ -46327,6 +46442,18 @@ async function runTentacle(opts) {
46327
46442
  ts: Date.now()
46328
46443
  });
46329
46444
  emitActivity({ type: "agent_status", agentId: liveId, status: "running", ts: Date.now() });
46445
+ const emitPhase = (message) => {
46446
+ emitActivity({ type: "agent_status", agentId: liveId, status: "running", message, ts: Date.now() });
46447
+ appendKrakenRadio(parentCwd, sessionId2, {
46448
+ kind: "progress",
46449
+ agent,
46450
+ thoroughness,
46451
+ description: args.description,
46452
+ detail: message
46453
+ });
46454
+ };
46455
+ emitPhase(`phase: ${agent}`);
46456
+ if (worktree) emitPhase(`worktree: ${shortWorktreeCaption(worktree.path)}`);
46330
46457
  const taskUserContent = buildTaskUserPrompt({
46331
46458
  prompt: args.prompt,
46332
46459
  scope: args.scope,
@@ -46441,6 +46568,7 @@ worktree deferred: branch=${worktree.branch} path=${worktree.path} (executor mer
46441
46568
  } else if (worktree) {
46442
46569
  let merge2 = null;
46443
46570
  if (!kept && isKrakenWorktreeAutoMergeEnabled()) {
46571
+ emitPhase("merging\u2026");
46444
46572
  try {
46445
46573
  merge2 = await mergeKrakenWorktree(
46446
46574
  worktree,
@@ -46454,6 +46582,7 @@ worktree deferred: branch=${worktree.branch} path=${worktree.path} (executor mer
46454
46582
  message: `merge threw: ${err instanceof Error ? err.message : String(err)}`
46455
46583
  };
46456
46584
  }
46585
+ emitPhase(merge2.ok ? "merge ok" : "merge failed");
46457
46586
  } else if (!kept) {
46458
46587
  await cleanupKrakenWorktree(worktree);
46459
46588
  }
@@ -46517,6 +46646,7 @@ ${verifyHintForGeneral(args.acceptance)}`;
46517
46646
  ok: true,
46518
46647
  agent,
46519
46648
  thoroughness,
46649
+ agentId: liveId,
46520
46650
  model: sub.model,
46521
46651
  result,
46522
46652
  footer,
@@ -78577,6 +78707,7 @@ async function runZelariMissionInTui(userMessage, deps, emit) {
78577
78707
  const hook = await runPostCouncilHook2(workspaceCtx, {
78578
78708
  runMode: "implementation",
78579
78709
  userMessage,
78710
+ sessionId: deps.sessionId,
78580
78711
  synthesisText: synthesisText || void 0,
78581
78712
  degradedRun: d.degraded,
78582
78713
  degradedReasons: d.reasons