import {
  checkLaneLock
} from "./chunk-JONWQUB5.js";
import {
  TEST_METHODOLOGY_HINTS,
  classifyWork,
  generateCodeCraftGuidance,
  generateDesignContextSection,
  generateEnforcementSummary,
  generateMandatoryStandards,
  generatePolicyBasedTestGuidance,
  generateReadBeforeWriteDiscipline,
  generateSelfReviewDirective
} from "./chunk-NMG736UR.js";
import {
  INVARIANT_TYPES,
  loadInvariants
} from "./chunk-EZ6ZBYBM.js";
import {
  BRANCHES,
  DIRECTORIES,
  LUMENFLOW_PATHS,
  REMOTES
} from "./chunk-DWMLTXKQ.js";
import {
  WORKSPACE_CONFIG_FILE_NAME,
  WORKSPACE_V2_KEYS,
  WU_STATUS,
  getConfig,
  getDefaultConfig,
  resolvePolicy
} from "./chunk-V6OJGLBA.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../core/dist/wu-spawn-helpers.js
import { Command } from "commander";

// ../core/dist/delegation-registry-store.js
import fs from "fs/promises";
import path from "path";

// ../core/dist/delegation-registry-schema.js
import crypto from "crypto";
import { z } from "zod";
var DelegationStatus = {
  PENDING: "pending",
  COMPLETED: WU_STATUS.COMPLETED,
  TIMEOUT: "timeout",
  CRASHED: "crashed",
  ESCALATED: "escalated"
};
var DELEGATION_STATUSES = [
  DelegationStatus.PENDING,
  DelegationStatus.COMPLETED,
  DelegationStatus.TIMEOUT,
  DelegationStatus.CRASHED,
  DelegationStatus.ESCALATED
];
var DelegationIntent = {
  DELEGATION: "delegation",
  LEGACY_SPAWN: "legacy-spawn"
};
var DELEGATION_INTENTS = [
  DelegationIntent.DELEGATION,
  DelegationIntent.LEGACY_SPAWN
];
var DELEGATION_PATTERNS = {
  DELEGATION_ID: /^dlg-[0-9a-f]{4}$/,
  WU_ID: /^WU-\d+$/
};
var ERROR_MESSAGES = {
  DELEGATION_ID: "Delegation ID must match pattern dlg-XXXX (e.g., dlg-a1b2)",
  WU_ID: "WU ID must match pattern WU-XXX (e.g., WU-1000)",
  LANE_REQUIRED: "Lane is required",
  STATUS: `Status must be one of: ${DELEGATION_STATUSES.join(", ")}`,
  INTENT: `Intent must be one of: ${DELEGATION_INTENTS.join(", ")}`,
  TIMESTAMP_REQUIRED: "Timestamp is required",
  PICKUP_BY_REQUIRED: "pickedUpBy must be a non-empty string when pickup is recorded",
  BRIEF_HASH: "briefAttestation.promptHash must be a 64-character lowercase sha256 hex digest",
  BRIEF_ALGORITHM: "briefAttestation.algorithm must be sha256",
  BRIEF_CLIENT_REQUIRED: "briefAttestation.clientName must be a non-empty string"
};
var SHA256_HEX_256_REGEX = /^[a-f0-9]{64}$/;
var DelegationBriefAttestationSchema = z.object({
  algorithm: z.literal("sha256", { error: ERROR_MESSAGES.BRIEF_ALGORITHM }),
  promptHash: z.string().regex(SHA256_HEX_256_REGEX, { message: ERROR_MESSAGES.BRIEF_HASH }),
  promptLength: z.number().int().nonnegative(),
  generatedAt: z.string().datetime({ message: ERROR_MESSAGES.TIMESTAMP_REQUIRED }),
  clientName: z.string().min(1, { message: ERROR_MESSAGES.BRIEF_CLIENT_REQUIRED })
});
var DelegationEventSchema = z.object({
  id: z.string().regex(DELEGATION_PATTERNS.DELEGATION_ID, {
    message: ERROR_MESSAGES.DELEGATION_ID
  }),
  parentWuId: z.string().regex(DELEGATION_PATTERNS.WU_ID, { message: ERROR_MESSAGES.WU_ID }),
  targetWuId: z.string().regex(DELEGATION_PATTERNS.WU_ID, { message: ERROR_MESSAGES.WU_ID }),
  lane: z.string().min(1, { message: ERROR_MESSAGES.LANE_REQUIRED }),
  intent: z.enum(DELEGATION_INTENTS, { error: ERROR_MESSAGES.INTENT }).optional(),
  delegatedAt: z.string().datetime({ message: ERROR_MESSAGES.TIMESTAMP_REQUIRED }),
  status: z.enum(DELEGATION_STATUSES, { error: ERROR_MESSAGES.STATUS }),
  completedAt: z.string().datetime().nullable(),
  pickedUpAt: z.string().datetime().optional(),
  pickedUpBy: z.string().min(1, { message: ERROR_MESSAGES.PICKUP_BY_REQUIRED }).optional(),
  briefAttestation: DelegationBriefAttestationSchema.optional()
});
function validateDelegationEvent(data) {
  return DelegationEventSchema.safeParse(data);
}
function generateDelegationId(parentWuId, targetWuId) {
  const timestamp = Date.now().toString();
  const randomBytes = crypto.randomBytes(4).toString("hex");
  const input = `${parentWuId}:${targetWuId}:${timestamp}:${randomBytes}`;
  const hash = crypto.createHash("sha256").update(input).digest("hex");
  return `dlg-${hash.slice(0, 4)}`;
}

// ../core/dist/delegation-registry-store.js
var DELEGATION_REGISTRY_FILE_NAME = "delegation-registry.jsonl";
var DelegationRegistryStore = class {
  baseDir;
  registryFilePath;
  delegations;
  byParent;
  byTarget;
  /**
   * @param {string} baseDir - Directory containing .lumenflow/state/
   */
  constructor(baseDir) {
    this.baseDir = baseDir;
    this.registryFilePath = path.join(baseDir, DELEGATION_REGISTRY_FILE_NAME);
    this.delegations = /* @__PURE__ */ new Map();
    this.byParent = /* @__PURE__ */ new Map();
    this.byTarget = /* @__PURE__ */ new Map();
  }
  /**
   * Loads and replays events from JSONL file into current state.
   *
   * Handles:
   * - Missing file: returns empty state
   * - Empty file: returns empty state
   * - Empty lines: skipped gracefully
   * - Malformed JSON: throws error with line info
   * - Invalid events: throws validation error
   *
   * @returns {Promise<void>}
   * @throws {Error} If file contains malformed JSON or invalid events
   *
   * @example
   * const store = new DelegationRegistryStore('/path/to/project');
   * await store.load();
   * const pending = store.getPendingDelegations();
   */
  async load() {
    this.delegations.clear();
    this.byParent.clear();
    this.byTarget.clear();
    let content;
    try {
      content = await fs.readFile(this.registryFilePath, "utf-8");
    } catch (error) {
      if (error.code === "ENOENT") {
        return;
      }
      throw error;
    }
    const lines = content.split("\n");
    for (let i = 0; i < lines.length; i++) {
      const rawLine = lines[i];
      if (typeof rawLine !== "string") {
        continue;
      }
      const line = rawLine.trim();
      if (!line) {
        continue;
      }
      let parsed;
      try {
        parsed = JSON.parse(line);
      } catch (error) {
        throw createError(ErrorCodes.PARSE_ERROR, `Malformed JSON on line ${i + 1}: ${error.message}`);
      }
      const validation = validateDelegationEvent(parsed);
      if (!validation.success) {
        const issues = validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
        throw createError(ErrorCodes.VALIDATION_ERROR, `Validation error on line ${i + 1}: ${issues}`);
      }
      const event = validation.data;
      this._applyEvent(event);
    }
  }
  /**
   * Applies an event to the in-memory state.
   * If event for same delegation ID exists, updates it (latest wins).
   *
   * @private
   */
  _applyEvent(event) {
    const { id, parentWuId, targetWuId } = event;
    this.delegations.set(id, event);
    if (!this.byParent.has(parentWuId)) {
      this.byParent.set(parentWuId, []);
    }
    const parentDelegations = this.byParent.get(parentWuId);
    if (!parentDelegations) {
      return;
    }
    if (!parentDelegations.includes(id)) {
      parentDelegations.push(id);
    }
    this.byTarget.set(targetWuId, id);
  }
  /**
   * Appends an event to the registry file.
   *
   * Uses append mode to avoid full file rewrite.
   * Creates file and parent directories if they don't exist.
   * Validates event before appending.
   *
   * @private
   * @throws {Error} If event fails validation
   */
  async _appendEvent(event) {
    const validation = validateDelegationEvent(event);
    if (!validation.success) {
      const issues = validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
      throw createError(ErrorCodes.VALIDATION_ERROR, `Validation error: ${issues}`);
    }
    const line = JSON.stringify(event) + "\n";
    await fs.mkdir(this.baseDir, { recursive: true });
    await fs.appendFile(this.registryFilePath, line, "utf-8");
  }
  /**
   * Records a new delegation event with pending status.
   *
   * @param {string} parentWuId - Parent WU ID (orchestrator)
   * @param {string} targetWuId - Target WU ID (delegated work)
   * @param {string} lane - Lane for the delegated work
   * @param {DelegationIntentValue} [intent] - Optional intent source (e.g., delegation)
   * @returns {Promise<string>} The generated delegation ID
   * @throws {Error} If validation fails
   *
   * @example
   * const delegationId = await store.record('WU-1000', 'WU-1001', 'Operations: Tooling');
   */
  async record(parentWuId, targetWuId, lane, intent, briefAttestation) {
    const id = generateDelegationId(parentWuId, targetWuId);
    const event = {
      id,
      parentWuId,
      targetWuId,
      lane,
      ...intent ? { intent } : {},
      delegatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      status: DelegationStatus.PENDING,
      completedAt: null,
      ...briefAttestation ? { briefAttestation } : {}
    };
    await this._appendEvent(event);
    this._applyEvent(event);
    return id;
  }
  /**
   * Updates the status of a delegation.
   *
   * @param {string} delegationId - Delegation ID to update
   * @param {string} status - New status
   * @returns {Promise<void>}
   * @throws {Error} If delegation ID not found
   *
   * @example
   * await store.updateStatus('dlg-a1b2', 'completed');
   */
  async updateStatus(delegationId, status) {
    const existing = this.delegations.get(delegationId);
    if (!existing) {
      throw createError(ErrorCodes.DELEGATION_NOT_FOUND, `Delegation ID ${delegationId} not found`);
    }
    const event = {
      ...existing,
      status,
      completedAt: (/* @__PURE__ */ new Date()).toISOString()
    };
    await this._appendEvent(event);
    this._applyEvent(event);
  }
  /**
   * Records claim-time pickup evidence for a delegation entry.
   *
   * WU-1605: This distinguishes intent-only delegation records from
   * delegated work that was actually picked up via wu:claim.
   *
   * @param {string} delegationId - Delegation ID to update
   * @param {string} pickedUpBy - Agent identity that claimed the target WU
   * @param {string} [pickedUpAt] - Optional ISO timestamp (defaults to now)
   * @returns {Promise<void>}
   * @throws {Error} If delegation ID not found
   */
  async recordPickup(delegationId, pickedUpBy, pickedUpAt) {
    const existing = this.delegations.get(delegationId);
    if (!existing) {
      throw createError(ErrorCodes.DELEGATION_NOT_FOUND, `Delegation ID ${delegationId} not found`);
    }
    const event = {
      ...existing,
      pickedUpBy,
      pickedUpAt: pickedUpAt ?? (/* @__PURE__ */ new Date()).toISOString()
    };
    await this._appendEvent(event);
    this._applyEvent(event);
  }
  /**
   * Gets all delegations for a parent WU.
   *
   * @param {string} parentWuId - Parent WU ID
   * @returns {DelegationEvent[]} Array of delegation events
   *
   * @example
   * const delegations = store.getByParent('WU-1000');
   */
  getByParent(parentWuId) {
    const delegationIds = this.byParent.get(parentWuId) ?? [];
    return delegationIds.map((id) => this.delegations.get(id)).filter((event) => event !== void 0);
  }
  /**
   * Gets delegation for a target WU.
   *
   * @param {string} targetWuId - Target WU ID
   * @returns {DelegationEvent | null} Delegation event or null
   *
   * @example
   * const delegation = store.getByTarget('WU-1001');
   */
  getByTarget(targetWuId) {
    const delegationId = this.byTarget.get(targetWuId);
    if (!delegationId) {
      return null;
    }
    return this.delegations.get(delegationId) ?? null;
  }
  /**
   * Gets all pending delegations.
   *
   * @returns {DelegationEvent[]} Array of pending delegation events
   *
   * @example
   * const pending = store.getPendingDelegations();
   */
  getPendingDelegations() {
    return Array.from(this.delegations.values()).filter((delegation) => delegation.status === DelegationStatus.PENDING);
  }
  /**
   * Gets all delegations as an array.
   *
   * @returns {DelegationEvent[]} Array of all delegation events
   *
   * @example
   * const allDelegations = store.getAllDelegations();
   */
  getAllDelegations() {
    return Array.from(this.delegations.values());
  }
  /**
   * Gets delegation by ID.
   *
   * @param {string} delegationId - Delegation ID
   * @returns {DelegationEvent | null} Delegation event or null
   *
   * @example
   * const delegation = store.getById('dlg-a1b2');
   */
  getById(delegationId) {
    return this.delegations.get(delegationId) ?? null;
  }
};

// ../core/dist/wu-spawn-helpers.js
function validateSpawnArgs(args) {
  if (args.thinking && args.noThinking) {
    throw createError(ErrorCodes.INVALID_ARGUMENT, "--thinking and --no-thinking are mutually exclusive");
  }
  if (args.budget && !args.thinking) {
    throw createError(ErrorCodes.INVALID_ARGUMENT, "--budget requires --thinking flag");
  }
  if (args.budget) {
    const budgetNum = parseInt(args.budget, 10);
    if (isNaN(budgetNum) || budgetNum <= 0 || !Number.isInteger(budgetNum)) {
      throw createError(ErrorCodes.INVALID_ARGUMENT, "--budget must be a positive integer");
    }
  }
}
function generateExecutionModeSection(options) {
  const { thinking, noThinking, budget } = options;
  if (!thinking && !noThinking) {
    return "";
  }
  const lines = ["## Execution Mode", ""];
  if (thinking) {
    lines.push("Extended thinking: **enabled**");
    if (budget) {
      lines.push(`Token budget: **${budget}**`);
    }
    lines.push("");
    lines.push("The sub-agent will use extended thinking for complex reasoning tasks.");
  } else if (noThinking) {
    lines.push("Extended thinking: **disabled**");
    lines.push("");
    lines.push("The sub-agent will execute without extended thinking mode.");
  }
  return lines.join("\n");
}
function generateThinkToolGuidance(options) {
  const { thinking, noThinking } = options;
  if (!thinking || noThinking) {
    return "";
  }
  return `## Think Tool Guidance

When extended thinking is enabled, use the think tool strategically for:

1. **Complex Decision Points**: Before making architectural decisions or choosing between approaches
2. **Multi-Step Reasoning**: When planning long tool-call chains or multi-file edits
3. **Mid-Execution Reflection**: After gathering information, before implementing changes
4. **Error Analysis**: When troubleshooting failures or unexpected behavior

### Best Practices

- Use think blocks to reason through acceptance criteria before implementation
- Document your reasoning for complex logic decisions
- Break down large tasks into thought-through steps
- Reflect on test results before proceeding with fixes

### When NOT to Use Think Blocks

- Simple file reads or writes with clear outcomes
- Routine git operations
- Running predefined commands like \`pnpm gates\`
- When the next action is obvious and low-risk`;
}
var LOG_PREFIX = "[wu:spawn]";
async function recordSpawnToRegistry(options) {
  const { parentWuId, targetWuId, lane, baseDir = LUMENFLOW_PATHS.STATE_DIR, briefAttestation } = options;
  try {
    const store = new DelegationRegistryStore(baseDir);
    await store.load();
    const spawnId = await store.record(parentWuId, targetWuId, lane, void 0, briefAttestation);
    return {
      success: true,
      spawnId
    };
  } catch (error) {
    return {
      success: false,
      spawnId: null,
      error: error.message
    };
  }
}
function formatSpawnRecordedMessage(spawnId, errorMessage = void 0) {
  if (spawnId) {
    return `${LOG_PREFIX} Spawn recorded ${spawnId}`;
  }
  if (errorMessage) {
    return `${LOG_PREFIX} Warning: Registry write skipped (${errorMessage})`;
  }
  return `${LOG_PREFIX} Warning: Registry unavailable`;
}

// ../core/dist/wu-spawn-skills.js
import { existsSync } from "fs";
var DEFAULT_CONFIG = getDefaultConfig();
var KNOWN_SKILLS_DIRS = [
  LUMENFLOW_PATHS.SKILLS_DIR,
  DEFAULT_CONFIG.directories.skillsDir,
  ".codex/skills",
  ".gemini/skills"
];
var KNOWN_AGENTS_DIRS = [
  LUMENFLOW_PATHS.AGENTS_DIR,
  DEFAULT_CONFIG.directories.agentsDir,
  ".codex/agents",
  ".gemini/agents"
];
var SECTION = {
  skillsSelection: "## Skills Selection",
  skillsCatalog: "### Skills Catalog",
  softPolicy: "### Soft Policy (baselines for this WU)",
  additionalSkills: "### Additional Skills (load if needed)",
  gracefulDegradation: "### Graceful Degradation",
  clientSkills: "### Client Skills Guidance"
};
var MESSAGES = {
  skillsIntro: "**IMPORTANT**: Before starting work, select and load relevant skills.",
  catalogMissing: `No skills directories configured or found. Set \`directories.skillsDir\` or \`agents.clients.<client>.skillsDir\` in ${WORKSPACE_CONFIG_FILE_NAME} ${WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY}.`,
  baselineFallback: "- Load baseline skills: `/skill wu-lifecycle`, `/skill tdd-workflow` (for features)\n- Continue with implementation using Mandatory Standards below"
};
var CONTEXT_HINTS = {
  wuLifecycle: "- `wu-lifecycle` \u2014 ALL WUs need workflow automation",
  worktreeDiscipline: "- `worktree-discipline` \u2014 ALL WUs need path safety",
  tddWorkflow: "- `tdd-workflow` \u2014 TDD is mandatory for feature/enhancement WUs",
  bugClassification: "- `bug-classification` \u2014 Bug severity assessment",
  lumenflowGates: "- `lumenflow-gates` \u2014 Tooling often affects gates",
  llmCompliance: "- `llm-compliance` \u2014 Intelligence lane requires LLM validation",
  promptManagement: "- `prompt-management` \u2014 For prompt template work",
  frontendDesign: "- `frontend-design` \u2014 For UI component work"
};
var ADDITIONAL_SKILLS_TABLE = `| Skill | Use When |
|-------|----------|
| lumenflow-gates | Gates fail, debugging format/lint/typecheck errors |
| bug-classification | Bug discovered mid-WU, need priority classification |
| llm-compliance | Code touches LLM, prompts, classification |
| prompt-management | Working with prompt templates, golden datasets |
| frontend-design | Building UI components, pages |
| initiative-management | Multi-phase projects, INIT-XXX coordination |
| multi-agent-coordination | Spawning sub-agents, parallel WU work |
| orchestration | Agent coordination, mandatory agent checks |
| ops-maintenance | Metrics, validation, health checks |`;
function resolveClientConfig(config, clientName) {
  const clients = config?.agents?.clients || {};
  if (!clientName)
    return void 0;
  if (clients[clientName])
    return clients[clientName];
  const matchKey = Object.keys(clients).find((key) => key.toLowerCase() === clientName.toLowerCase());
  return matchKey ? clients[matchKey] : void 0;
}
function uniqueNonEmpty(values) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  for (const value of values) {
    if (!value)
      continue;
    if (seen.has(value))
      continue;
    seen.add(value);
    result.push(value);
  }
  return result;
}
function resolveSkillsPaths(config, clientName) {
  const clientConfig = resolveClientConfig(config, clientName);
  const configuredSkillsDir = clientConfig?.skillsDir || config?.directories?.skillsDir;
  const configuredAgentsDir = config?.directories?.agentsDir;
  const skillsCandidates = uniqueNonEmpty([configuredSkillsDir, ...KNOWN_SKILLS_DIRS]);
  const agentsCandidates = uniqueNonEmpty([configuredAgentsDir, ...KNOWN_AGENTS_DIRS]);
  const skillsDir = skillsCandidates.find((candidate) => existsSync(candidate));
  const agentsDir = agentsCandidates.find((candidate) => existsSync(candidate));
  const configuredSkillsMissing = Boolean(configuredSkillsDir && !existsSync(configuredSkillsDir));
  const configuredAgentsMissing = Boolean(configuredAgentsDir && !existsSync(configuredAgentsDir));
  return {
    clientConfig,
    configuredSkillsDir,
    configuredAgentsDir,
    skillsDir,
    agentsDir,
    configuredSkillsMissing,
    configuredAgentsMissing
  };
}
function generateSkillsCatalogGuidance(config, clientName) {
  const resolution = resolveSkillsPaths(config, clientName);
  const lines = [];
  if (resolution.skillsDir) {
    lines.push(`- Check \`${resolution.skillsDir}\` for available skills.`);
  }
  if (resolution.agentsDir) {
    lines.push(`- Check \`${resolution.agentsDir}\` for agent configs (optional).`);
  }
  if (lines.length > 0) {
    return `${SECTION.skillsCatalog}

${lines.join("\n")}
`;
  }
  const configuredHint = resolution.configuredSkillsDir ? `Configured skillsDir \`${resolution.configuredSkillsDir}\` was not found. ` : "";
  const clientHint = clientName ? `agents.clients.${clientName}.skillsDir` : "agents.clients.<client>.skillsDir";
  return `${SECTION.skillsCatalog}

${configuredHint}No skills directories configured or found. Set \`directories.skillsDir\` or \`${clientHint}\` in ${WORKSPACE_CONFIG_FILE_NAME} ${WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY}.
`;
}
function getByLaneSkills(clientContext, lane) {
  const byLane = clientContext?.config?.skills?.byLane;
  if (!byLane || !lane)
    return [];
  return byLane[lane] || [];
}
function generateClientSkillsGuidance(clientContext, lane) {
  const skills = clientContext?.config?.skills;
  if (!skills) {
    return "";
  }
  const byLaneSkills = lane ? getByLaneSkills(clientContext, lane) : [];
  const hasRecommended = skills.recommended && skills.recommended.length > 0;
  const hasByLane = byLaneSkills.length > 0;
  const hasInstructions = Boolean(skills.instructions);
  if (!hasInstructions && !hasRecommended && !hasByLane) {
    return "";
  }
  const instructions = skills.instructions ? `${skills.instructions.trim()}

` : "";
  const recommendedSection = hasRecommended || hasByLane ? `Recommended skills:
${[...skills.recommended || [], ...byLaneSkills].filter((s, i, arr) => arr.indexOf(s) === i).map((s) => `- \`${s}\``).join("\n")}
` : "";
  return `${SECTION.clientSkills} (${clientContext?.name})

${instructions}${recommendedSection}`;
}
function resolveCapabilitySkills(capabilities, clientConfig) {
  const capMap = clientConfig?.capabilities_map;
  if (!capMap || capabilities.length === 0)
    return [];
  const skills = [];
  for (const capability of capabilities) {
    const skillName = capMap[capability];
    if (skillName) {
      skills.push(skillName);
    }
  }
  return skills;
}
function generateSkillsSelectionSection(doc, config, clientName) {
  const lane = doc.lane || "";
  const type = doc.type || "feature";
  const laneParent = lane.split(":")[0].trim();
  const classificationConfig = config?.methodology?.work_classification;
  const classification = classifyWork({
    code_paths: doc.code_paths,
    lane: doc.lane,
    type: doc.type,
    description: doc.description
  }, classificationConfig);
  const contextHints = [];
  contextHints.push(CONTEXT_HINTS.wuLifecycle);
  contextHints.push(CONTEXT_HINTS.worktreeDiscipline);
  if (type === "feature" || type === "enhancement") {
    contextHints.push(CONTEXT_HINTS.tddWorkflow);
  }
  if (type === "bug") {
    contextHints.push(CONTEXT_HINTS.bugClassification);
  }
  if (laneParent === "Operations" && lane.includes("Tooling")) {
    contextHints.push(CONTEXT_HINTS.lumenflowGates);
  }
  if (laneParent === "Intelligence") {
    contextHints.push(CONTEXT_HINTS.llmCompliance);
    contextHints.push(CONTEXT_HINTS.promptManagement);
  }
  if (classification.domain === "ui" || laneParent === "Experience") {
    contextHints.push(CONTEXT_HINTS.frontendDesign);
  }
  const clientConfig = resolveClientConfig(config, clientName);
  const capabilitySkills = resolveCapabilitySkills(classification.capabilities, clientConfig);
  const capabilityHints = capabilitySkills.map((skill) => `- \`${skill}\` \u2014 Suggested by work classifier (${classification.domain} domain)`);
  const softPolicySection = `${SECTION.softPolicy}

Based on WU context, consider loading:

${contextHints.join("\n")}${capabilityHints.length > 0 ? "\n" + capabilityHints.join("\n") : ""}

`;
  const catalogGuidance = generateSkillsCatalogGuidance(config, clientName);
  return `${SECTION.skillsSelection}

${MESSAGES.skillsIntro}

${catalogGuidance}${softPolicySection}${SECTION.additionalSkills}

${ADDITIONAL_SKILLS_TABLE}

${SECTION.gracefulDegradation}

If the skill catalogue is missing or invalid:
${MESSAGES.baselineFallback}
`;
}

// ../core/dist/template-loader.js
import { existsSync as existsSync2, readFileSync, readdirSync } from "fs";
import { join } from "path";
import matter from "gray-matter";
import yaml from "yaml";
var MANIFEST_PATH = LUMENFLOW_PATHS.TEMPLATE_MANIFEST;
var TEMPLATES_DIR = LUMENFLOW_PATHS.SPAWN_PROMPT_DIR;
var TEMPLATE_SUBDIR = "spawn-prompt";
var CLIENT_ALIAS_MAP = {
  "claude-code": "claude",
  "codex-cli": "codex",
  "gemini-cli": "gemini"
};
function resolveClientAlias(clientName) {
  const normalizedName = clientName.trim().toLowerCase();
  const mappedAlias = CLIENT_ALIAS_MAP[normalizedName];
  if (mappedAlias) {
    return mappedAlias;
  }
  return normalizedName.replace(/-cli$/, "");
}
function loadTemplate(templatePath) {
  if (!existsSync2(templatePath)) {
    throw createError(ErrorCodes.FILE_NOT_FOUND, `Template not found: ${templatePath}`, {
      path: templatePath
    });
  }
  const fileContent = readFileSync(templatePath, "utf-8");
  const { data, content } = matter(fileContent, {
    engines: {
      yaml: {
        parse: yaml.parse.bind(yaml),
        stringify: yaml.stringify.bind(yaml)
      }
    }
  });
  const frontmatter = data;
  if (!frontmatter.id || typeof frontmatter.id !== "string") {
    throw createError(ErrorCodes.VALIDATION_ERROR, `Template ${templatePath}: 'id' field is required in frontmatter`, { path: templatePath });
  }
  if (!frontmatter.name || typeof frontmatter.name !== "string") {
    throw createError(ErrorCodes.VALIDATION_ERROR, `Template ${templatePath}: 'name' field is required in frontmatter`, { path: templatePath });
  }
  if (typeof frontmatter.required !== "boolean") {
    throw createError(ErrorCodes.VALIDATION_ERROR, `Template ${templatePath}: 'required' field must be a boolean`, { path: templatePath });
  }
  if (typeof frontmatter.order !== "number") {
    throw createError(ErrorCodes.VALIDATION_ERROR, `Template ${templatePath}: 'order' field must be a number`, { path: templatePath });
  }
  return {
    frontmatter: {
      id: frontmatter.id,
      name: frontmatter.name,
      required: frontmatter.required,
      order: frontmatter.order,
      tokens: Array.isArray(frontmatter.tokens) ? frontmatter.tokens : void 0,
      condition: typeof frontmatter.condition === "string" ? frontmatter.condition : void 0
    },
    content: content.trim(),
    sourcePath: templatePath
  };
}
function loadTemplatesWithOverrides(baseDir, clientName) {
  const templates = /* @__PURE__ */ new Map();
  const baseTemplatesDir = join(baseDir, TEMPLATES_DIR);
  const clientAlias = resolveClientAlias(clientName);
  const clientTemplatesDir = join(baseDir, `${LUMENFLOW_PATHS.BASE}/templates.${clientAlias}/${TEMPLATE_SUBDIR}`);
  if (existsSync2(baseTemplatesDir)) {
    loadTemplatesFromDir(baseTemplatesDir, templates);
  }
  if (existsSync2(clientTemplatesDir)) {
    loadTemplatesFromDir(clientTemplatesDir, templates);
  }
  return templates;
}
function loadTemplatesFromDir(dirPath, templates) {
  const entries = readdirSync(dirPath, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = join(dirPath, entry.name);
    if (entry.isDirectory()) {
      loadTemplatesFromDir(fullPath, templates);
    } else if (entry.name.endsWith(".md")) {
      try {
        const template = loadTemplate(fullPath);
        templates.set(template.frontmatter.id, template);
      } catch {
      }
    }
  }
}
function replaceTokens(content, tokens) {
  let result = content;
  for (const [key, value] of Object.entries(tokens)) {
    if (value !== void 0) {
      const pattern = new RegExp(`\\{${escapeRegex(key)}\\}`, "g");
      result = result.replace(pattern, value);
    }
  }
  return result;
}
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getNestedValue(obj, path3) {
  if (path3 in obj) {
    return obj[path3];
  }
  const parts = path3.split(".");
  let current = obj;
  for (const part of parts) {
    if (current === null || current === void 0 || typeof current !== "object") {
      return void 0;
    }
    current = current[part];
  }
  return current;
}
function evaluateCondition(condition, context) {
  if (!condition || condition.trim() === "") {
    return true;
  }
  if (condition.includes("||")) {
    const parts = condition.split("||").map((p) => p.trim());
    return parts.some((part) => evaluateCondition(part, context));
  }
  if (condition.includes("&&")) {
    const parts = condition.split("&&").map((p) => p.trim());
    return parts.every((part) => evaluateCondition(part, context));
  }
  const eqRegex = /^([\w.]+)\s*===\s*['"](.+)['"]$/;
  const eqMatch = eqRegex.exec(condition);
  if (eqMatch) {
    const key = eqMatch[1];
    const value = eqMatch[2];
    if (!key)
      return true;
    return getNestedValue(context, key) === value;
  }
  const neqRegex = /^([\w.]+)\s*!==\s*['"](.+)['"]$/;
  const neqMatch = neqRegex.exec(condition);
  if (neqMatch) {
    const key = neqMatch[1];
    const value = neqMatch[2];
    if (!key)
      return true;
    return getNestedValue(context, key) !== value;
  }
  const truthyRegex = /^([\w.]+)$/;
  const truthyMatch = truthyRegex.exec(condition);
  if (truthyMatch) {
    const key = truthyMatch[1];
    if (!key)
      return false;
    return Boolean(getNestedValue(context, key));
  }
  return true;
}

// ../core/dist/spawn-template-assembler.js
var TRUNCATION_WARNING_BANNER = `<!-- LUMENFLOW_TRUNCATION_WARNING -->
<!--
  \u26A0\uFE0F CRITICAL: DO NOT TRUNCATE THIS OUTPUT

  This spawn prompt MUST be copied verbatim. Truncation causes:
  - Missing constraints (agents ignore safety rules)
  - Missing TDD directives (agents skip tests)
  - Degraded agent performance

  VERIFICATION: The output MUST end with: <!-- LUMENFLOW_SPAWN_END -->
  If you don't see that sentinel at the end, the output was truncated.
-->
`;
var SPAWN_END_SENTINEL = "<!-- LUMENFLOW_SPAWN_END -->";

// ../core/dist/spawn-constraints-generator.js
var DEFAULT_MAIN_REF = `${REMOTES.ORIGIN}/${BRANCHES.MAIN}`;
var DEFAULT_WORKTREES_DIR_SEGMENT = DIRECTORIES.WORKTREES.replace(/\/+$/g, "");
function normalizeWorktreesDirSegment(value) {
  const normalized = (value ?? "").replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
  return normalized.length > 0 ? normalized : DEFAULT_WORKTREES_DIR_SEGMENT;
}
function generateConstraints(id, options) {
  const includeTdd = options?.includeTddCheckpoint !== false;
  const mainRef = options?.mainRef ?? DEFAULT_MAIN_REF;
  const worktreesDirSegment = normalizeWorktreesDirSegment(options?.worktreesDirSegment);
  const tddCheckpointBlock = includeTdd ? `
1. TDD CHECKPOINT (VERIFY BEFORE IMPLEMENTATION)
   - Did you write tests BEFORE implementation?
   - Is there at least one failing test for each acceptance criterion?
   - Never skip the RED phase \u2014 failing tests prove the test works

` : "";
  const antiLoopNum = includeTdd ? 2 : 1;
  const stopAskNum = includeTdd ? 3 : 2;
  const verifyNum = includeTdd ? 4 : 3;
  const neverFabNum = includeTdd ? 5 : 4;
  const gitNum = includeTdd ? 6 : 5;
  const memNum = includeTdd ? 7 : 6;
  const skipGatesNum = includeTdd ? 8 : 7;
  const worktreeNum = includeTdd ? 9 : 8;
  return `---

<constraints>
CRITICAL RULES - ENFORCE BEFORE EVERY ACTION:
${tddCheckpointBlock}${antiLoopNum}. ANTI-LOOP GUARD (LumenFlow \xA77.3)
   - Max 3 attempts per unique error before escalating
   - If same error repeats 3x, STOP and report with full context
   - Retry with different approach, not same command

${stopAskNum}. STOP-AND-ASK TRIGGERS (LumenFlow \xA77.2 - narrow scope)
   - Policy changes, auth/permissions modifications
   - PII/safety issues, cloud spend, secrets, backups
   - Same error repeats 3x
   - For ordinary errors: fix and retry autonomously (up to 3 attempts)

${verifyNum}. VERIFY COMPLETION before reporting success
   - Run: node packages/@lumenflow/agent/verification ${id} (from shared checkout)
   - Exit 0 = passed, Exit 1 = INCOMPLETE
   - Never report "done" if verification fails

${neverFabNum}. NEVER FABRICATE COMPLETION
   - If blockers remain, report INCOMPLETE
   - If verification fails, summarize failures
   - Honesty over false completion

${gitNum}. GIT WORKFLOW (CRITICAL - GitHub rules reject merge commits)
   - GitHub REJECTS merge commits on main
   - ALWAYS use \`git rebase ${mainRef}\` before push
   - Push to main via \`git push origin lane/...:main\` (fast-forward only)
   - NEVER use \`git merge\` on main branch
   - Use \`pnpm wu:prep\` from worktree, then \`pnpm wu:done\` from main (WU-1223)

${memNum}. MEMORY LAYER COORDINATION (INIT-007)
   - Use \`pnpm mem:checkpoint --wu ${id}\` to save progress before risky operations
   - Check \`pnpm mem:inbox --wu ${id}\` periodically for parallel signals from other agents
   - Checkpoint triggers (WU-1943): checkpoint after each acceptance criterion completed, checkpoint before gates, checkpoint every 30 tool calls

${skipGatesNum}. SKIP-GATES AUTONOMY (WU-1142)
   - If gates fail, first check if failure is pre-existing on main: \`git checkout main && pnpm gates\`
   - If failure exists on main (not your change), use: \`pnpm wu:done --id ${id} --skip-gates --reason "pre-existing on main" --fix-wu WU-XXXX\`
   - Do NOT ask for approval - autonomous skip-gates for pre-existing failures is correct
   - This prevents getting stuck on infrastructure debt

${worktreeNum}. WORKTREE DISCIPLINE (WU-1282)
   - CRITICAL: PreToolUse hooks do not propagate to sub-agents spawned via Task tool
   - BEFORE UnsafeAny Write/Edit operation, manually verify you are in a worktree:
   - Run: \`pwd\` and confirm output contains \`${worktreesDirSegment}/\`
   - If not in worktree, STOP and navigate: \`cd ${worktreesDirSegment}/<lane>-wu-xxx\`
   - Use RELATIVE paths only (never full absolute paths starting with root directory)
   - This constraint exists because Claude Code does not inherit settings.json hooks in sub-agent sessions
</constraints>

${SPAWN_END_SENTINEL}`;
}
function generateCodexConstraints(id, options) {
  const includeTdd = options?.includeTddCheckpoint !== false;
  const worktreesDirSegment = normalizeWorktreesDirSegment(options?.worktreesDirSegment);
  const tddLine = includeTdd ? "1. **TDD checkpoint**: tests BEFORE implementation; never skip RED" : "";
  const stopNum = includeTdd ? 2 : 1;
  const verifyNum = includeTdd ? 3 : 2;
  const fabricateNum = includeTdd ? 4 : 3;
  const gitNum = includeTdd ? 5 : 4;
  const scopeNum = includeTdd ? 6 : 5;
  const worktreeNum = includeTdd ? 7 : 6;
  return `## Constraints (Critical)

${tddLine}${tddLine ? "\n" : ""}${stopNum}. **Stop on errors**: if UnsafeAny command fails, report BLOCKED (never DONE) with the error
${verifyNum}. **Verify before success**: run \`pnpm gates\` in the worktree, then run \`node packages/@lumenflow/agent/verification ${id}\` (from the shared checkout)
${fabricateNum}. **No fabrication**: if blockers remain or verification fails, report INCOMPLETE
${gitNum}. **Git workflow**: avoid merge commits; use \`wu:prep\` from worktree, then \`wu:done\` from main
${scopeNum}. **Scope discipline**: stay within \`code_paths\`; capture out-of-scope issues via \`pnpm mem:create\`
${worktreeNum}. **Worktree discipline (WU-1282)**: BEFORE UnsafeAny Write/Edit, verify \`pwd\` shows \`${worktreesDirSegment}/\`; hooks do not propagate to sub-agents`;
}

// ../core/dist/spawn-agent-guidance.js
var DEFAULT_WORKTREES_DIR_SEGMENT2 = DIRECTORIES.WORKTREES.replace(/\/+$/g, "");
function normalizeDirectorySegment(value) {
  return value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
}
function resolveWorktreesDirSegment(config) {
  const normalized = normalizeDirectorySegment(config.directories.worktrees);
  return normalized.length > 0 ? normalized : DEFAULT_WORKTREES_DIR_SEGMENT2;
}
function generateEffortScalingRules() {
  return `## Effort Scaling (When to Spawn Sub-Agents)

Use this heuristic to decide complexity:

| Complexity | Approach | Tool Calls |
|------------|----------|------------|
| **Simple** (single file, <50 lines) | Handle inline | 3-10 |
| **Moderate** (2-3 files, clear scope) | Handle inline | 10-20 |
| **Complex** (4+ files, exploration needed) | Spawn Explore agent first | 20+ |
| **Multi-domain** (cross-cutting concerns) | Spawn specialized sub-agents | Varies |

**Rule**: If you need >30 tool calls for a subtask, consider spawning a sub-agent with a focused scope.`;
}
function generateParallelToolCallGuidance() {
  return `## Parallel Tool Calls (Performance)

**IMPORTANT**: Make 3+ tool calls in parallel when operations are independent.

Good examples:
- Reading multiple files simultaneously
- Running independent grep searches
- Spawning multiple Explore agents for different areas

Bad examples:
- Reading a file then editing it (sequential dependency)
- Running tests then checking results (sequential)

Parallelism reduces latency by 50-90% for complex tasks.`;
}
function generateIterativeSearchHeuristics() {
  return `## Search Strategy (Broad to Narrow)

When exploring the codebase:

1. **Start broad**: Use Explore agent or glob patterns to understand structure
2. **Evaluate findings**: What patterns exist? What's relevant?
3. **Narrow focus**: Target specific files/functions based on findings
4. **Iterate**: Refine if initial approach misses the target

Avoid: Jumping directly to specific file edits without understanding context.`;
}
function generateTokenBudgetAwareness(id) {
  return `## Token Budget Awareness

Context limit is ~200K tokens. Monitor your usage:

- **At 50+ tool calls**: Create a checkpoint (\`pnpm mem:checkpoint --wu ${id}\`)
- **At 100+ tool calls**: Consider spawning fresh sub-agent with focused scope
- **Before risky operations**: Always checkpoint first

If approaching limits, summarize progress and spawn continuation agent.`;
}
function generateCompletionFormat(_id) {
  return `## Completion Report Format

When finishing, provide structured output:

\`\`\`
## Summary
<1-3 sentences describing what was accomplished>

## Artifacts
- Files modified: <list>
- Tests added: <list>
- Documentation updated: <list>

## Verification
- Gates: <pass/fail>
- Tests: <X passing, Y failing>

## Blockers (if UnsafeAny)
- <blocker description>

## Follow-up (if needed)
- <suggested next WU or action>
\`\`\`

This format enables orchestrator to track progress across waves.`;
}
function generateAgentCoordinationSection(id) {
  const config = getConfig();
  const progressSignals = config.memory?.progress_signals;
  const isEnabled = progressSignals?.enabled ?? true;
  const generateMilestoneTriggers = () => {
    if (!isEnabled) {
      return `For long-running work, send progress signals at milestones:

\`\`\`bash
pnpm mem:signal "50% complete: tests passing, implementing adapter" --wu ${id}
pnpm mem:signal "Blocked: waiting for WU-XXX dependency" --wu ${id}
\`\`\``;
    }
    const triggers = [];
    if ((progressSignals?.on_milestone ?? true) !== false) {
      triggers.push("**After each acceptance criterion completed** - helps track progress");
    }
    if ((progressSignals?.on_tests_pass ?? true) !== false) {
      triggers.push("**When tests first pass** - indicates implementation is working");
    }
    if ((progressSignals?.before_gates ?? true) !== false) {
      triggers.push("**Before running gates** - signals imminent completion");
    }
    if ((progressSignals?.on_blocked ?? true) !== false) {
      triggers.push("**When blocked** - allows orchestrator to re-allocate or assist");
    }
    const frequency = progressSignals?.frequency ?? 0;
    let frequencyGuidance = "";
    if (frequency > 0) {
      frequencyGuidance = `
5. **Every ${frequency} tool calls** - periodic progress update`;
    }
    const triggerList = triggers.length > 0 ? triggers.map((t, i) => `${i + 1}. ${t}`).join("\n") + frequencyGuidance : "Signal at key milestones to enable orchestrator visibility.";
    return `**Signal at these milestones** to enable orchestrator visibility:

${triggerList}

\`\`\`bash
pnpm mem:signal "AC1 complete: tests passing for feature X" --wu ${id}
pnpm mem:signal "All tests passing, running gates" --wu ${id}
pnpm mem:signal "Blocked: waiting for WU-XXX dependency" --wu ${id}
\`\`\``;
  };
  const progressSectionTitle = isEnabled ? "### Progress Signals (Required at Milestones)" : "### Progress Signals (Optional)";
  return `## Agent Coordination (Parallel Work)

### \u26A0\uFE0F CRITICAL: Use mem:signal, NOT TaskOutput

**DO NOT** use TaskOutput to check agent progress - it returns full transcripts
and causes "prompt too long" errors. Always use the memory layer instead:

\`\`\`bash
# \u2705 CORRECT: Compact signals (~6 lines)
pnpm mem:inbox --since 30m

# \u274C WRONG: Full transcripts (context explosion)
# TaskOutput with block=false  <-- NEVER DO THIS FOR MONITORING
\`\`\`

### Automatic Completion Signals

\`wu:done\` automatically broadcasts completion signals. You do not need to
manually signal completion - just run \`wu:done\` and orchestrators will
see your signal via \`mem:inbox\`.

${progressSectionTitle}

${generateMilestoneTriggers()}

### Checking Status

\`\`\`bash
pnpm orchestrate:init-status -i INIT-XXX  # Initiative progress (compact)
pnpm mem:inbox --since 1h                  # Recent signals from all agents
pnpm mem:inbox --lane "Experience: Web"    # Lane-specific signals
\`\`\``;
}
function generateQuickFixCommands() {
  return `## Quick Fix Commands

If gates fail, try these before investigating:

\`\`\`bash
pnpm format      # Auto-fix formatting issues
pnpm lint        # Check linting (use --fix for auto-fix)
pnpm typecheck   # Check TypeScript types
\`\`\`

**Use before gates** to catch simple issues early. These are faster than full \`pnpm gates\`.`;
}
function generateLaneSelectionSection() {
  return `## Lane Selection

When creating new WUs, use the correct lane to enable parallelization:

\`\`\`bash
# Get lane suggestion based on code paths and description
pnpm wu:infer-lane --id WU-XXX

# Or infer from manual inputs
pnpm wu:infer-lane --paths "tools/**" --desc "CLI improvements"
\`\`\`

**Lane source of truth**: See \`workspace.yaml\` \`software_delivery.lanes.definitions\`.
Inference reads configured lane names, descriptions, and \`code_paths\` from that file.

**Why lanes matter**: WIP=1 per lane means correct lane selection enables parallel work across lanes.`;
}
function generateWorktreePathGuidance(worktreePath) {
  if (!worktreePath) {
    return "";
  }
  return `## Worktree Path Guidance (WU-2362)

**Your worktree:** \`${worktreePath}\`

### Finding the Worktree Root

Sub-agents may inherit the parent's cwd (main checkout). To find the actual worktree root:

\`\`\`bash
# Get the worktree root (not main checkout)
git rev-parse --show-toplevel
\`\`\`

### Stamp Creation

When creating \`.lumenflow/\` stamps or other artifacts:

1. **ALWAYS** create stamps in the **worktree**, not main
2. Use \`git rev-parse --show-toplevel\` to get the correct base path
3. Stamps created on main will be lost when the worktree merges

\`\`\`bash
# CORRECT: Create stamp in worktree
WORKTREE_ROOT=$(git rev-parse --show-toplevel)
mkdir -p "$WORKTREE_ROOT/.lumenflow/agent-runs"
touch "$WORKTREE_ROOT/.lumenflow/agent-runs/code-reviewer.stamp"

# WRONG: Hardcoded path to main
# touch /path/to/main/.lumenflow/agent-runs/code-reviewer.stamp
\`\`\`

### Why This Matters

- Stamps on main get overwritten by worktree merge
- \`wu:done\` validates stamps exist in the worktree branch
- Parallel WUs in other lanes won't see your stamps if on main`;
}
function generateBugDiscoverySection(id) {
  return `## Bug Discovery (Mid-WU Issue Capture)

If you discover a bug or issue **outside the scope of this WU**:

1. **Capture it immediately** using:
   \`\`\`bash
   pnpm mem:create 'Bug: <description>' --type discovery --tags bug,scope-creep --wu ${id}
   \`\`\`

2. **Continue with your WU** \u2014 do not fix bugs outside your scope
3. **Reference in notes** \u2014 mention the mem node ID in your completion notes

### NEVER use wu:create for discovered issues

**Do NOT use \`wu:create\` directly for bugs discovered mid-WU.**

- \`mem:create\` = **capture** (immediate, no human approval needed)
- \`wu:create\` = **planned work** (requires human triage and approval)

Discovered issues MUST go through human triage before becoming WUs.
Using \`wu:create\` directly bypasses the triage workflow and creates
unreviewed work items.

### When to Capture

- Found a bug in code NOT in your \`code_paths\`
- Discovered an issue that would require >10 lines to fix
- Encountered broken behaviour unrelated to your acceptance criteria

### Triage Workflow

After WU completion, bugs can be promoted to Bug WUs by humans:
\`\`\`bash
pnpm mem:triage --wu ${id}           # List discoveries for this WU
pnpm mem:triage --promote <node-id> --lane "<lane>"  # Create Bug WU (human action)
\`\`\`

See: https://lumenflow.dev/reference/agent-invocation-guide/ \xA7Bug Discovery`;
}
function generateLaneGuidance(lane) {
  if (!lane)
    return "";
  const laneParent = (lane.split(":")[0] ?? "").trim();
  const guidance = {
    Operations: `## Lane-Specific: Tooling

- Update tool documentation in tools/README.md or relevant docs if adding new CLI commands`,
    Intelligence: `## Lane-Specific: Intelligence

- For prompt/classification work, run the project-specific evaluation command defined by your local templates/config
- Follow prompt versioning guidelines documented for this project`,
    Experience: `## Lane-Specific: Experience

- Follow design system tokens defined in the project
- Ensure accessibility compliance (WCAG 2.1 AA)`,
    Core: `## Lane-Specific: Core

- Maintain hexagonal architecture boundaries
- Update domain model documentation if changing entities`
  };
  return guidance[laneParent] || "";
}
function generateActionSection(doc, id, config) {
  const isAlreadyClaimed = doc.claimed_at && doc.worktree_path;
  const resolvedConfig = config ?? getConfig();
  const worktreesDirSegment = resolveWorktreesDirSegment(resolvedConfig);
  if (isAlreadyClaimed) {
    return `This WU is already claimed. Continue implementation in worktree following all standards above.

cd ${doc.worktree_path}`;
  }
  const laneSlug = (doc.lane || "unknown").toLowerCase().replace(/[:\s]+/g, "-").replace(/-+/g, "-");
  return `**FIRST: Claim this WU before starting work:**

\`\`\`bash
pnpm wu:claim --id ${id} --lane "${doc.lane}"
cd ${worktreesDirSegment}/${laneSlug}-${id.toLowerCase()}
\`\`\`

Then implement following all standards above.

**CRITICAL:** Never use \`git worktree add\` directly. Always use \`pnpm wu:claim\` to ensure:
- Event tracking in ${LUMENFLOW_PATHS.WU_EVENTS}
- Lane lock acquisition (WIP=1 enforcement)
- Session tracking for context recovery`;
}

// ../core/dist/spawn-prompt-helpers.js
import path2 from "path";
import { existsSync as existsSync3 } from "fs";
import { minimatch } from "minimatch";
var MANDATORY_TRIGGERS = {
  // No mandatory triggers for LumenFlow framework development.
};
function formatAcceptance(acceptance) {
  if (!acceptance || acceptance.length === 0) {
    return "- No acceptance criteria defined";
  }
  return acceptance.map((item) => `- [ ] ${item}`).join("\n");
}
function formatSpecRefs(specRefs) {
  if (!specRefs || specRefs.length === 0) {
    return "";
  }
  const formattedRefs = specRefs.map((ref) => {
    if (ref.startsWith("lumenflow://") || ref.startsWith("~/") || ref.startsWith("$LUMENFLOW_HOME") || ref.startsWith("/") && ref.includes(".lumenflow")) {
      return `- ${ref} (external - read with filesystem access)`;
    }
    return `- ${ref}`;
  });
  return formattedRefs.join("\n");
}
function formatRisks(risks) {
  if (!risks || risks.length === 0) {
    return "";
  }
  return risks.map((risk) => `- ${risk}`).join("\n");
}
function formatManualTests(manualTests) {
  if (!manualTests || manualTests.length === 0) {
    return "";
  }
  return manualTests.map((test) => `- [ ] ${test}`).join("\n");
}
function generateImplementationContext(doc) {
  const sections = [];
  const refs = formatSpecRefs(doc.spec_refs);
  if (refs) {
    sections.push(`## References

${refs}`);
  }
  if (doc.notes && doc.notes.trim()) {
    sections.push(`## Implementation Notes

${doc.notes.trim()}`);
  }
  const risks = formatRisks(doc.risks);
  if (risks) {
    sections.push(`## Risks

${risks}`);
  }
  const manualTests = formatManualTests(doc.tests?.manual);
  if (manualTests) {
    sections.push(`## Manual Verification

${manualTests}`);
  }
  if (sections.length === 0) {
    return "";
  }
  return sections.join("\n\n---\n\n");
}
function detectMandatoryAgents(codePaths) {
  if (!codePaths || codePaths.length === 0) {
    return [];
  }
  const triggeredAgents = /* @__PURE__ */ new Set();
  for (const [agentName, patterns] of Object.entries(MANDATORY_TRIGGERS)) {
    const isTriggered = codePaths.some((filePath) => patterns.some((pattern) => minimatch(filePath, pattern)));
    if (isTriggered) {
      triggeredAgents.add(agentName);
    }
  }
  return Array.from(triggeredAgents);
}
function generateMandatoryAgentSection(mandatoryAgents, _id) {
  if (mandatoryAgents.length === 0) {
    return "";
  }
  const agentList = mandatoryAgents.map((agent) => `  - ${agent}`).join("\n");
  return `
## Mandatory Agents (MUST invoke before wu:done)

Based on code_paths, the following agents MUST be invoked:

${agentList}

Run: pnpm orchestrate:monitor to check agent status
`;
}
function generatePreamble(id, strategy) {
  return strategy.getPreamble(id);
}
function generateClientBlocksSection(clientContext) {
  if (!clientContext?.config?.blocks?.length)
    return "";
  const blocks = clientContext.config.blocks.map((block) => `### ${block.title}

${block.content}`).join("\n\n");
  return `## Client Guidance (${clientContext.name})

${blocks}`;
}
function codePathMatchesInvariant(invariant, codePaths) {
  switch (invariant.type) {
    case INVARIANT_TYPES.FORBIDDEN_FILE:
    case INVARIANT_TYPES.REQUIRED_FILE: {
      const invariantPath = invariant.path;
      if (!invariantPath)
        return false;
      return codePaths.some((p) => p === invariantPath || minimatch(p, invariantPath) || minimatch(invariantPath, p));
    }
    case INVARIANT_TYPES.MUTUAL_EXCLUSIVITY: {
      const invariantPaths = invariant.paths ?? [];
      return codePaths.some((p) => invariantPaths.some((invPath) => p === invPath || minimatch(p, invPath)));
    }
    case INVARIANT_TYPES.FORBIDDEN_PATTERN:
    case INVARIANT_TYPES.REQUIRED_PATTERN:
      return invariant.scope?.some((scopePattern) => codePaths.some((p) => minimatch(p, scopePattern))) ?? false;
    case INVARIANT_TYPES.FORBIDDEN_IMPORT: {
      const fromPattern = invariant.from;
      if (!fromPattern)
        return false;
      return codePaths.some((p) => minimatch(p, fromPattern));
    }
    default:
      return false;
  }
}
function formatInvariantForOutput(inv) {
  const lines = [`### ${inv.id} (${inv.type})`, "", inv.description, ""];
  if (inv.message) {
    lines.push(`**Action:** ${inv.message}`, "");
  }
  if (inv.path) {
    lines.push(`**Path:** \`${inv.path}\``);
  }
  if (inv.paths) {
    const formattedPaths = inv.paths.map((p) => `\`${p}\``).join(", ");
    lines.push(`**Paths:** ${formattedPaths}`);
  }
  if (inv.from) {
    lines.push(`**From:** \`${inv.from}\``);
  }
  if (inv.cannot_import && Array.isArray(inv.cannot_import)) {
    const formattedImports = inv.cannot_import.map((m) => `\`${m}\``).join(", ");
    lines.push(`**Cannot Import:** ${formattedImports}`);
  }
  if (inv.pattern && (inv.type === INVARIANT_TYPES.REQUIRED_PATTERN || inv.type === INVARIANT_TYPES.FORBIDDEN_PATTERN)) {
    lines.push(`**Pattern:** \`${inv.pattern}\``);
  }
  if (inv.scope && Array.isArray(inv.scope)) {
    const formattedScope = inv.scope.map((s) => `\`${s}\``).join(", ");
    lines.push(`**Scope:** ${formattedScope}`);
  }
  lines.push("");
  return lines;
}
function generateInvariantsPriorArtSection(codePaths) {
  if (!codePaths || codePaths.length === 0) {
    return "";
  }
  const invariantsPath = path2.resolve("tools/invariants.yml");
  if (!existsSync3(invariantsPath)) {
    return "";
  }
  let invariants;
  try {
    invariants = loadInvariants(invariantsPath);
  } catch {
    return "";
  }
  if (!invariants || invariants.length === 0) {
    return "";
  }
  const relevantInvariants = invariants.filter((inv) => codePathMatchesInvariant(inv, codePaths));
  if (relevantInvariants.length === 0) {
    return "";
  }
  const lines = [
    "## Invariants/Prior-Art (WU-2252)",
    "",
    "The following repo invariants are relevant to your code_paths:",
    "",
    ...relevantInvariants.flatMap(formatInvariantForOutput),
    "**IMPORTANT:** Do not create specs or acceptance criteria that conflict with these invariants."
  ];
  return lines.join("\n");
}

// ../core/dist/spawn-task-builder.js
var DEFAULT_WORKTREES_DIR_SEGMENT3 = DIRECTORIES.WORKTREES.replace(/\/+$/g, "");
function normalizeDirectorySegment2(value) {
  return value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
}
function resolveWorktreesDirSegment2(config) {
  const normalized = normalizeDirectorySegment2(config.directories.worktrees);
  return normalized.length > 0 ? normalized : DEFAULT_WORKTREES_DIR_SEGMENT3;
}
function resolveWorktreePathHint(doc, id, config) {
  if (doc.worktree_path) {
    return doc.worktree_path;
  }
  return `${resolveWorktreesDirSegment2(config)}/<lane>-${id.toLowerCase()}`;
}
function generateTaskInvocation(doc, id, strategy, options = {}) {
  const codePaths = doc.code_paths || [];
  const mandatoryAgents = detectMandatoryAgents(codePaths);
  const preamble = generatePreamble(id, strategy);
  const clientContext = options.client;
  const config = options.config || getConfig();
  const worktreesDirSegment = resolveWorktreesDirSegment2(config);
  const worktreePathHint = resolveWorktreePathHint(doc, id, config);
  const mainRef = `${config.git.defaultRemote}/${config.git.mainBranch}`;
  const policy = resolvePolicy(config);
  const classificationConfig = config?.methodology?.work_classification;
  const classification = classifyWork({
    code_paths: doc.code_paths,
    lane: doc.lane,
    type: doc.type,
    description: doc.description
  }, classificationConfig);
  const testGuidance = generatePolicyBasedTestGuidance(doc.type || "feature", policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const enforcementSummary = generateEnforcementSummary(policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const mandatoryStandards = generateMandatoryStandards(policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const codeCraftGuidance = generateCodeCraftGuidance();
  const readBeforeWrite = generateReadBeforeWriteDiscipline();
  const clientSkillsGuidance = generateClientSkillsGuidance(clientContext);
  const skillsSection = generateSkillsSelectionSection(doc, config, clientContext?.name) + (clientSkillsGuidance ? `
${clientSkillsGuidance}` : "");
  const clientBlocks = generateClientBlocksSection(clientContext);
  const mandatorySection = generateMandatoryAgentSection(mandatoryAgents, id);
  const laneGuidance = generateLaneGuidance(doc.lane);
  const bugDiscoverySection = generateBugDiscoverySection(id);
  const action = generateActionSection(doc, id, config);
  const selfReviewDirective = generateSelfReviewDirective(id);
  const shouldIncludeTddCheckpoint = classification.testMethodologyHint !== TEST_METHODOLOGY_HINTS.SMOKE_TEST && classification.testMethodologyHint !== TEST_METHODOLOGY_HINTS.STRUCTURED_CONTENT && policy.testing !== "none";
  const constraints = generateConstraints(id, {
    includeTddCheckpoint: shouldIncludeTddCheckpoint,
    mainRef,
    worktreesDirSegment
  });
  const designContextSection = generateDesignContextSection(classification);
  const implementationContext = generateImplementationContext(doc);
  const invariantsPriorArt = generateInvariantsPriorArtSection(codePaths);
  const effortScaling = generateEffortScalingRules();
  const parallelToolCalls = generateParallelToolCallGuidance();
  const searchHeuristics = generateIterativeSearchHeuristics();
  const tokenBudget = generateTokenBudgetAwareness(id);
  const completionFormat = generateCompletionFormat(id);
  const agentCoordination = generateAgentCoordinationSection(id);
  const quickFix = generateQuickFixCommands();
  const laneSelection = generateLaneSelectionSection();
  const worktreeGuidance = generateWorktreePathGuidance(doc.worktree_path);
  const shouldIncludeMemoryContext = options.includeMemoryContext && !options.noContext;
  const memoryContextSection = shouldIncludeMemoryContext ? options.memoryContextContent || "" : "";
  const executionModeSection = generateExecutionModeSection(options);
  const thinkToolGuidance = generateThinkToolGuidance(options);
  const thinkingSections = [executionModeSection, thinkToolGuidance].filter((section) => section.length > 0).join("\n\n---\n\n");
  const thinkingBlock = thinkingSections ? `${thinkingSections}

---

` : "";
  const taskPrompt = `${TRUNCATION_WARNING_BANNER}<task>
${preamble}
</task>

---

${testGuidance}

---

# ${id}: ${doc.title || "Untitled"}

## WU Details

- **ID:** ${id}
- **Lane:** ${doc.lane || "Unknown"}
- **Type:** ${doc.type || "feature"}
- **Status:** ${doc.status || "unknown"}
- **Worktree:** ${worktreePathHint}

## Description

${doc.description || "No description provided."}

## Acceptance Criteria

${formatAcceptance(doc.acceptance)}

## Code Paths

${codePaths.length > 0 ? codePaths.map((p) => `- ${p}`).join("\n") : "- No code paths defined"}
${mandatorySection}${invariantsPriorArt ? `---

${invariantsPriorArt}

` : ""}${implementationContext ? `---

${implementationContext}

` : ""}---

${thinkingBlock}${skillsSection}
${memoryContextSection ? `---

${memoryContextSection}

` : ""}---

${mandatoryStandards}

---

${enforcementSummary}

---

${codeCraftGuidance}

---

${readBeforeWrite}

${designContextSection ? `---

${designContextSection}

` : ""}${clientBlocks ? `---

${clientBlocks}

` : ""}${worktreeGuidance ? `---

${worktreeGuidance}

` : ""}---

${bugDiscoverySection}

---

${effortScaling}

---

${parallelToolCalls}

---

${searchHeuristics}

---

${tokenBudget}

---

${completionFormat}

---

${agentCoordination}

---

${quickFix}

---

${laneSelection}

---

${laneGuidance}${laneGuidance ? "\n\n---\n\n" : ""}## Action

${action}

---

${selfReviewDirective}

${constraints}`;
  const escapedPrompt = taskPrompt.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const openTag = '<antml:invoke name="Task">';
  const closeTag = "</antml:invoke>";
  const paramOpen = '<antml:parameter name="';
  const paramClose = "</antml:parameter>";
  const invocation = [
    "<antml:function_calls>",
    openTag,
    `${paramOpen}subagent_type">general-purpose${paramClose}`,
    `${paramOpen}description">Execute ${id}${paramClose}`,
    `${paramOpen}prompt">${escapedPrompt}${paramClose}`,
    closeTag,
    "</antml:function_calls>"
  ].join("\n");
  return invocation;
}
function generateCodexPrompt(doc, id, strategy, options = {}) {
  const codePaths = doc.code_paths || [];
  const mandatoryAgents = detectMandatoryAgents(codePaths);
  const preamble = generatePreamble(id, strategy);
  const mandatorySection = generateMandatoryAgentSection(mandatoryAgents, id);
  const laneGuidance = generateLaneGuidance(doc.lane);
  const bugDiscoverySection = generateBugDiscoverySection(id);
  const implementationContext = generateImplementationContext(doc);
  const clientContext = options.client;
  const config = options.config || getConfig();
  const classificationConfig = config?.methodology?.work_classification;
  const classification = classifyWork({
    code_paths: doc.code_paths,
    lane: doc.lane,
    type: doc.type,
    description: doc.description
  }, classificationConfig);
  const policy = resolvePolicy(config);
  const worktreesDirSegment = resolveWorktreesDirSegment2(config);
  const worktreePathHint = resolveWorktreePathHint(doc, id, config);
  const mainRef = `${config.git.defaultRemote}/${config.git.mainBranch}`;
  const action = generateActionSection(doc, id, config);
  const shouldIncludeTddCheckpoint = classification.testMethodologyHint !== TEST_METHODOLOGY_HINTS.SMOKE_TEST && classification.testMethodologyHint !== TEST_METHODOLOGY_HINTS.STRUCTURED_CONTENT && policy.testing !== "none";
  const constraints = generateCodexConstraints(id, {
    includeTddCheckpoint: shouldIncludeTddCheckpoint,
    mainRef,
    worktreesDirSegment
  });
  const clientSkillsGuidance = generateClientSkillsGuidance(clientContext);
  const skillsSection = generateSkillsSelectionSection(doc, config, clientContext?.name) + (clientSkillsGuidance ? `
${clientSkillsGuidance}` : "");
  const clientBlocks = generateClientBlocksSection(clientContext);
  const testGuidance = generatePolicyBasedTestGuidance(doc.type || "feature", policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const enforcementSummary = generateEnforcementSummary(policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const mandatoryStandards = generateMandatoryStandards(policy, {
    testMethodologyHint: classification.testMethodologyHint
  });
  const codeCraftGuidance = generateCodeCraftGuidance();
  const readBeforeWrite = generateReadBeforeWriteDiscipline();
  const selfReviewDirective = generateSelfReviewDirective(id);
  const designContextSection = generateDesignContextSection(classification);
  const executionModeSection = generateExecutionModeSection(options);
  const thinkToolGuidance = generateThinkToolGuidance(options);
  const thinkingSections = [executionModeSection, thinkToolGuidance].filter((section) => section.length > 0).join("\n\n---\n\n");
  const thinkingBlock = thinkingSections ? `${thinkingSections}

---

` : "";
  return `# ${id}: ${doc.title || "Untitled"}

${testGuidance}

---

## Context

${preamble}

---

## WU Details

- **ID:** ${id}
- **Lane:** ${doc.lane || "Unknown"}
- **Type:** ${doc.type || "feature"}
- **Status:** ${doc.status || "unknown"}
- **Worktree:** ${worktreePathHint}

## Description

${doc.description || "No description provided."}

## Scope (code_paths)

Only change files within these paths:

${codePaths.length > 0 ? codePaths.map((p) => `- ${p}`).join("\n") : "- No code paths defined"}

## Acceptance Criteria

${formatAcceptance(doc.acceptance)}

---

${mandatoryStandards}

---

${enforcementSummary}

---

${codeCraftGuidance}

---

${readBeforeWrite}

${designContextSection ? `---

${designContextSection}

` : ""}---

${skillsSection}

---

## Action

${action}

---

## Verification

- Run in worktree: \`pnpm gates\`
- From shared checkout: \`node packages/@lumenflow/agent/verification ${id}\`

---

${mandatorySection}${implementationContext ? `${implementationContext}

---

` : ""}${clientBlocks ? `${clientBlocks}

---

` : ""}${thinkingBlock}${bugDiscoverySection}

---

${laneGuidance}${laneGuidance ? "\n\n---\n\n" : ""}${selfReviewDirective}

---

${constraints}
`;
}
function checkLaneOccupation(lane) {
  const lockStatus = checkLaneLock(lane);
  if (lockStatus.locked && lockStatus.metadata) {
    return lockStatus.metadata;
  }
  return null;
}
function generateLaneOccupationWarning(lockMetadata, targetWuId, options = {}) {
  const { isStale = false } = options;
  let warning = `\u26A0\uFE0F  Lane "${lockMetadata.lane}" is occupied by ${lockMetadata.wuId}
`;
  warning += `   This violates WIP=1 (Work In Progress limit of 1 per lane).

`;
  if (isStale) {
    warning += `   \u23F0 This lock is STALE (>24 hours old) - the WU may be abandoned.
`;
    warning += `   Consider using pnpm wu:block --id ${lockMetadata.wuId} if work is stalled.

`;
  }
  warning += `   Options:
`;
  warning += `   1. Wait for ${lockMetadata.wuId} to complete or block
`;
  warning += `   2. Choose a different lane for ${targetWuId}
`;
  warning += `   3. Block ${lockMetadata.wuId} if work is stalled: pnpm wu:block --id ${lockMetadata.wuId}`;
  return warning;
}

export {
  DelegationStatus,
  DelegationRegistryStore,
  loadTemplatesWithOverrides,
  replaceTokens,
  evaluateCondition,
  validateSpawnArgs,
  generateExecutionModeSection,
  generateThinkToolGuidance,
  recordSpawnToRegistry,
  formatSpawnRecordedMessage,
  resolveClientConfig,
  generateClientSkillsGuidance,
  generateSkillsSelectionSection,
  TRUNCATION_WARNING_BANNER,
  SPAWN_END_SENTINEL,
  generateAgentCoordinationSection,
  generateTaskInvocation,
  generateCodexPrompt,
  checkLaneOccupation,
  generateLaneOccupationWarning
};
