Intelligence

Artifacts

Browse the repository, read documents, and manage the governance folders. Source, runtime, and infrastructure are read-only.

Repository
README.md
CONSTITUTION_COMPLIANCE_AUDIT_V1.mdREADME.md
repositories/aaf-holdings/hq01/lib/executives/briefing.ts
8.1 KB
import fs from "node:fs";
import path from "node:path";
import { readText, walkFiles } from "@/lib/content/fs";
import { startSession } from "@/lib/sessions/manager";
import {
  CLAUDE_ALLOWED_TOOLS,
  CLAUDE_PERMISSION_MODE,
  claudePermissionArgs,
} from "@/lib/sessions/config";
import type { Session } from "@/lib/sessions/types";
import { DISPATCH_WORKSPACE_ROOT } from "./config";
import { getEntry } from "./registry";
import type { Briefing } from "./types";

/**
 * The Executive Briefing Loader (Part 6). Before a session runs, it assembles
 * the office's operating context — identity, why it was dispatched, its loaded
 * constitution, operating constraints, and the report requirement — and launches
 * through the existing Session Manager. The Session Manager itself is untouched:
 * the briefing is passed as the session's appended system context.
 */

const TEXT_EXT = new Set([".md", ".mdx", ".txt", ".yaml", ".yml", ".json"]);
const MAX_CONSTITUTION_BYTES = 200 * 1024;

const OPERATING_CONSTRAINTS = [
  "Additive only — never delete or rewrite existing functionality without explicit approval.",
  "No production deploys and no production CRM changes.",
  "No self-modification of canonical doctrine.",
  "Act only within this office's authority; escalate anything beyond it.",
  "Files are the source of truth; commit and report what you change.",
];

const REPORT_REQUIREMENT =
  "Before terminating, write ./report.md with these sections, using '## ' markdown " +
  "headings EXACTLY as named:\n" +
  "## Summary\n## Files Changed\n## Files Created\n## Commands Executed\n" +
  "## Artifacts Produced\n## Recommendations\n## Doctrine Candidates\n" +
  "## Next Pass Recommendation\n" +
  "Use '- ' bullet lists under the list sections (Files/Commands/Artifacts/" +
  "Recommendations/Doctrine Candidates); leave a section empty if nothing applies. " +
  "Doctrine Candidates are reusable lessons worth preserving — write them plainly; " +
  "they are stored exactly as written.";

function loadConstitution(
  constitutionPath: string,
): { files: { path: string; bytes: number }[]; text: string } {
  const files = walkFiles(constitutionPath, (p) =>
    TEXT_EXT.has(path.extname(p).toLowerCase()),
  );
  const loaded: { path: string; bytes: number }[] = [];
  const parts: string[] = [];
  let total = 0;
  for (const file of files) {
    let content: string;
    try {
      content = readText(file);
    } catch {
      continue;
    }
    if (total + content.length > MAX_CONSTITUTION_BYTES) break;
    total += content.length;
    loaded.push({ path: path.basename(file), bytes: content.length });
    parts.push(`### ${path.basename(file)}\n\n${content.trim()}`);
  }
  return { files: loaded, text: parts.join("\n\n---\n\n") };
}

/** Assemble the briefing for an executive + instruction (no launch). */
export function assembleBriefing(
  executiveId: string,
  instruction: string,
  routingReason: string,
): Briefing {
  const entry = getEntry(executiveId);
  if (!entry) throw new Error(`No registry entry for "${executiveId}".`);

  const { files, text } = loadConstitution(entry.constitutionPath);
  const constitutionLoaded = files.length > 0;
  const warnings: string[] = [];
  if (!constitutionLoaded) {
    warnings.push(
      `No constitution document is filed for ${entry.office} yet — the session will run without office-specific rules. Add documents to ${entry.constitutionPath}.`,
    );
  }

  const systemPrompt = [
    `# You are ${entry.displayName}, ${entry.office} (${entry.department}) of AAF Holdings.`,
    "",
    "You operate as an OFFICE, not a chat. The organization owns the intelligence; " +
      "you are the temporary reasoning engine staffing this office for one assignment. " +
      "You inherit from CANONICAL_00, the parent doctrine of AAF Holdings.",
    "",
    "## Why you were dispatched",
    routingReason,
    "",
    "## Operating constraints",
    ...OPERATING_CONSTRAINTS.map((c) => `- ${c}`),
    "",
    "## Your constitution",
    constitutionLoaded
      ? text
      : "No constitution document has been filed for this office yet. Operate within " +
        "the operating constraints above and the canonical doctrine until one is provided.",
    "",
    "## Report requirement",
    REPORT_REQUIREMENT,
  ].join("\n");

  return {
    executiveId,
    office: entry.office,
    department: entry.department,
    routingReason,
    instruction,
    constitutionFiles: files,
    constitutionLoaded,
    operatingConstraints: OPERATING_CONSTRAINTS,
    reportRequirement: REPORT_REQUIREMENT,
    systemPrompt,
    warnings,
  };
}

export interface DispatchInput {
  executiveId: string;
  instruction: string;
  repository?: string;
  routingReason: string;
  /** The mission this dispatch belongs to (required by the dispatch endpoint). */
  missionId?: string;
  /**
   * Pre-provisioned runtime workspace (e.g. an assignment's). When given it is
   * used as the cwd/runtime root instead of creating a fresh one.
   */
  workspace?: string;
}

function dispatchStamp(): string {
  return new Date().toISOString().replace(/[:.]/g, "-");
}

/**
 * Dispatch an active executive: assemble the briefing, create an isolated
 * runtime workspace, apply the controlled permission posture, and launch a
 * briefed session confined to that workspace.
 *
 * Safety posture:
 *   - The session's working directory is a fresh runtime workspace, never the
 *     repository, so its writes cannot touch repository source.
 *   - Permission flags come from config (e.g. acceptEdits + a tool allowlist);
 *     they NEVER include --dangerously-skip-permissions, and Bash is not allowed
 *     unless explicitly configured, so there is no arbitrary shell from the UI.
 */
export function dispatchExecutive(input: DispatchInput): {
  session: Session;
  briefing: Briefing;
  workspace: string;
} {
  const entry = getEntry(input.executiveId);
  if (!entry) throw new Error(`No registry entry for "${input.executiveId}".`);
  if (entry.status !== "active") {
    throw new Error(
      `The ${entry.office} office is not active — it must be approved before dispatch.`,
    );
  }

  const base = assembleBriefing(
    input.executiveId,
    input.instruction,
    input.routingReason,
  );

  // Isolated, write-confined runtime workspace for this dispatch. An assignment
  // (PASS M3) provides its own; otherwise we create a fresh one.
  const slug = entry.id.replace(/[^a-z0-9-]/gi, "-");
  const workspace =
    input.workspace?.trim() ||
    path.join(DISPATCH_WORKSPACE_ROOT, `${dispatchStamp()}-${slug}`);
  const outputsDir = path.join(workspace, "outputs");
  fs.mkdirSync(outputsDir, { recursive: true });

  const permArgs = claudePermissionArgs();
  const scope = [
    "",
    "## Runtime write scope (enforced)",
    `- Your runtime working folder is: ${workspace}`,
    `- Write ONLY inside that folder. Your outputs folder is: ${outputsDir}`,
    "- Do NOT edit repository source files. Repository write is not permitted in this assignment (repository_write_allowed: false).",
    "- Do NOT run deployment commands. Do NOT install packages. Do NOT access customer data.",
    permArgs.length
      ? `- Permission mode: ${CLAUDE_PERMISSION_MODE}. Allowed tools: ${CLAUDE_ALLOWED_TOOLS.join(", ")}.`
      : "- This is a non-interactive session; tools requiring approval are unavailable.",
  ].join("\n");

  const systemPrompt = `${base.systemPrompt}\n${scope}`;
  const briefing: Briefing = { ...base, systemPrompt };

  const args = [
    "--print",
    "--verbose",
    ...permArgs,
    "--append-system-prompt",
    systemPrompt,
    input.instruction,
  ];

  const shortInstruction =
    input.instruction.length > 60
      ? input.instruction.slice(0, 57) + "…"
      : input.instruction;

  const session = startSession({
    name: `${entry.displayName}: ${shortInstruction}`,
    executive: input.executiveId,
    working_directory: workspace,
    prompt: input.instruction,
    args,
    created_by: "HQ01 Executive Router",
    mission_id: input.missionId ?? null,
    permission_mode: CLAUDE_PERMISSION_MODE || null,
    allowed_tools: CLAUDE_ALLOWED_TOOLS,
    runtime_write_root: workspace,
    repository_write_allowed: false,
    expects_report: true,
  });

  return { session, briefing, workspace };
}

root · /srv/aaf