From d47ec15ec83b953fbd84b4e9bbc847a1b7d3972e Mon Sep 17 00:00:00 2001 From: Jack Felke Date: Tue, 10 Mar 2026 10:36:48 -0700 Subject: [PATCH 1/3] docs: add example .preflight/ config directory with ready-to-use templates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README documents .preflight/ config extensively but there were no actual example files to copy. Adds: - examples/.preflight/config.yml — profile, related projects, thresholds - examples/.preflight/triage.yml — keyword rules and strictness - examples/.preflight/contracts/api.yml — manual contract definitions - examples/.preflight/README.md — setup instructions and tips - README.md pointer to the examples directory --- README.md | 2 ++ examples/.preflight/README.md | 24 ++++++++++++++++++ examples/.preflight/config.yml | 31 +++++++++++++++++++++++ examples/.preflight/contracts/api.yml | 35 ++++++++++++++++++++++++++ examples/.preflight/triage.yml | 36 +++++++++++++++++++++++++++ 5 files changed, 128 insertions(+) create mode 100644 examples/.preflight/README.md create mode 100644 examples/.preflight/config.yml create mode 100644 examples/.preflight/contracts/api.yml create mode 100644 examples/.preflight/triage.yml diff --git a/README.md b/README.md index f60fefa..7b4b747 100644 --- a/README.md +++ b/README.md @@ -500,6 +500,8 @@ Manual contract definitions that supplement auto-extraction: Environment variables are **fallbacks** — `.preflight/` config takes precedence when present. +> **💡 Ready-to-use example configs:** Copy [`examples/.preflight/`](examples/.preflight/) into your project root to get started quickly. See [`examples/.preflight/README.md`](examples/.preflight/README.md) for details. + --- ## Embedding Providers diff --git a/examples/.preflight/README.md b/examples/.preflight/README.md new file mode 100644 index 0000000..c3ca3b6 --- /dev/null +++ b/examples/.preflight/README.md @@ -0,0 +1,24 @@ +# Example `.preflight/` Config + +Copy this directory into your project root to get started: + +```bash +cp -r examples/.preflight /path/to/your/project/ +``` + +Then edit the files to match your project: + +| File | Purpose | +|------|---------| +| `config.yml` | Profile, related projects, thresholds, embedding provider | +| `triage.yml` | Keyword rules and strictness for prompt classification | +| `contracts/*.yml` | Manual type/interface definitions for cross-service awareness | + +All files are optional — preflight works without any config. These let you tune it for your team and codebase. + +## Tips + +- **Commit `.preflight/` to your repo** so the whole team shares the same rules +- **Start with `strictness: standard`**, then relax or tighten based on your experience +- **Add domain terms to `always_check`** that are frequently ambiguous in your codebase (e.g., "billing", "permissions") +- **Use contracts** for types that live in a separate repo or aren't auto-detected diff --git a/examples/.preflight/config.yml b/examples/.preflight/config.yml new file mode 100644 index 0000000..df4f864 --- /dev/null +++ b/examples/.preflight/config.yml @@ -0,0 +1,31 @@ +# .preflight/config.yml +# Drop this in your project root. Every field is optional. +# See: https://github.com/TerminalGravity/preflight#configuration-reference + +# Profile controls how much detail preflight returns. +# "minimal" — only flags ambiguous+, skips clarification detail +# "standard" — default behavior +# "full" — maximum detail on every non-trivial prompt +profile: standard + +# Related projects for cross-service contract awareness. +# When your prompt mentions a keyword from a related project, +# triage escalates to cross-service and searches those projects. +related_projects: + - path: /Users/you/projects/auth-service + alias: auth + - path: /Users/you/projects/shared-types + alias: shared + +# Behavioral thresholds +thresholds: + session_stale_minutes: 30 # warn if no activity for this long + max_tool_calls_before_checkpoint: 100 # suggest checkpoint after N tool calls + correction_pattern_threshold: 3 # min corrections before forming a pattern + +# Embedding provider for timeline search +# "local" uses Xenova (zero config, runs on-device) +# "openai" uses text-embedding-3-small (faster, needs API key) +embeddings: + provider: local + # openai_api_key: sk-... # only needed if provider is "openai" diff --git a/examples/.preflight/contracts/api.yml b/examples/.preflight/contracts/api.yml new file mode 100644 index 0000000..154ad5b --- /dev/null +++ b/examples/.preflight/contracts/api.yml @@ -0,0 +1,35 @@ +# .preflight/contracts/api.yml +# Manual contract definitions that supplement auto-extraction. +# Use these when preflight can't auto-detect your shared types, +# or when you want to be explicit about cross-service boundaries. + +- name: User + kind: interface + description: Core user object shared across services + fields: + - name: id + type: string + required: true + - name: email + type: string + required: true + - name: role + type: "'admin' | 'member' | 'viewer'" + required: true + - name: teamId + type: string + required: false + +- name: ApiResponse + kind: interface + description: Standard API response wrapper + fields: + - name: data + type: T + required: true + - name: error + type: string + required: false + - name: meta + type: "{ page: number, total: number }" + required: false diff --git a/examples/.preflight/triage.yml b/examples/.preflight/triage.yml new file mode 100644 index 0000000..d418ace --- /dev/null +++ b/examples/.preflight/triage.yml @@ -0,0 +1,36 @@ +# .preflight/triage.yml +# Controls the triage classification engine. +# Customize which prompts get flagged, skipped, or escalated. + +rules: + # Prompts containing these words → always at least AMBIGUOUS. + # Add domain terms that are frequently underspecified in your codebase. + always_check: + - rewards + - permissions + - migration + - schema + - billing + + # Prompts containing these words → TRIVIAL (pass through without checks). + # Safe, low-risk operations that don't need guardrails. + skip: + - commit + - format + - lint + - prettier + + # Prompts containing these words → CROSS-SERVICE. + # Triggers a search across related_projects defined in config.yml. + cross_service_keywords: + - auth + - notification + - event + - webhook + - queue + +# How aggressively to classify prompts. +# "relaxed" — more prompts pass as clear (experienced users) +# "standard" — balanced (recommended) +# "strict" — more prompts flagged as ambiguous (teams, onboarding) +strictness: standard From 245cd5db5d42af05064e8a471d128b2c8ec62526 Mon Sep 17 00:00:00 2001 From: Jack Felke Date: Tue, 10 Mar 2026 10:45:06 -0700 Subject: [PATCH 2/3] fix(token-audit): replace shell syntax in run() calls with Node.js APIs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #172. Fixes 4 broken patterns in token-audit.ts: - run('git diff ... 2>/dev/null') → run(['diff', ...]) (array args) - run('wc -l < file') → countLines() using fs.readFileSync - run('wc -c < file') → fileSize() using fs.statSync - run('tail -c N file') → readTail() using fs.openSync/readSync These shell operators were passed as literal git args since run() uses execFileSync without a shell. --- src/tools/token-audit.ts | 46 +++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/tools/token-audit.ts b/src/tools/token-audit.ts index b7aad2c..a2ff47f 100644 --- a/src/tools/token-audit.ts +++ b/src/tools/token-audit.ts @@ -4,12 +4,37 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { run } from "../lib/git.js"; import { readIfExists, findWorkspaceDocs, PROJECT_DIR } from "../lib/files.js"; import { loadState, saveState, now, STATE_DIR } from "../lib/state.js"; -import { readFileSync, existsSync, statSync } from "fs"; +import { readFileSync, existsSync, statSync, openSync, readSync, closeSync } from "fs"; import { join } from "path"; -/** Shell-escape a filename for safe interpolation */ -function shellEscape(s: string): string { - return s.replace(/'/g, "'\\''"); +/** Count lines in a file using Node.js fs (no shell needed). Returns 0 on error. */ +function countLines(filePath: string): number { + try { + const abs = join(PROJECT_DIR, filePath); + const content = readFileSync(abs, "utf-8"); + return content.split("\n").length; + } catch { return 0; } +} + +/** Get file size in bytes using Node.js fs. Returns 0 on error. */ +function fileSize(filePath: string): number { + try { + const abs = join(PROJECT_DIR, filePath); + return statSync(abs).size; + } catch { return 0; } +} + +/** Read tail bytes of a file. Returns empty string on error. */ +function readTail(filePath: string, maxBytes: number): string { + try { + const stat = statSync(filePath); + const fd = openSync(filePath, "r"); + const start = Math.max(0, stat.size - maxBytes); + const buf = Buffer.alloc(Math.min(maxBytes, stat.size)); + readSync(fd, buf, 0, buf.length, start); + closeSync(fd); + return buf.toString("utf-8"); + } catch { return ""; } } /** @@ -39,8 +64,8 @@ export function registerTokenAudit(server: McpServer): void { let wasteScore = 0; // 1. Git diff size & dirty file count - const diffStat = run("git diff --stat --no-color 2>/dev/null"); - const dirtyFiles = run("git diff --name-only 2>/dev/null"); + const diffStat = run(["diff", "--stat", "--no-color"]); + const dirtyFiles = run(["diff", "--name-only"]); const dirtyList = dirtyFiles.split("\n").filter(Boolean); const dirtyCount = dirtyList.length; @@ -62,9 +87,7 @@ export function registerTokenAudit(server: McpServer): void { const largeFiles: string[] = []; for (const f of dirtyList.slice(0, 30)) { - // Use shell-safe quoting instead of interpolation - const wc = run(`wc -l < '${shellEscape(f)}' 2>/dev/null`); - const lines = parseInt(wc) || 0; + const lines = countLines(f); estimatedContextTokens += lines * AVG_LINE_BYTES * AVG_TOKENS_PER_BYTE; if (lines > 500) { largeFiles.push(`${f} (${lines} lines)`); @@ -80,8 +103,7 @@ export function registerTokenAudit(server: McpServer): void { // 3. CLAUDE.md bloat check const claudeMd = readIfExists("CLAUDE.md", 1); if (claudeMd !== null) { - const stat = run(`wc -c < '${shellEscape("CLAUDE.md")}' 2>/dev/null`); - const bytes = parseInt(stat) || 0; + const bytes = fileSize("CLAUDE.md"); if (bytes > 5120) { patterns.push(`CLAUDE.md is ${(bytes / 1024).toFixed(1)}KB — injected every session, burns tokens on paste`); recommendations.push("Trim CLAUDE.md to essentials (<5KB). Move reference docs to files read on-demand"); @@ -139,7 +161,7 @@ export function registerTokenAudit(server: McpServer): void { // Read with size cap: take the tail if too large const raw = stat.size <= MAX_TOOL_LOG_BYTES ? readFileSync(toolLogPath, "utf-8") - : run(`tail -c ${MAX_TOOL_LOG_BYTES} '${shellEscape(toolLogPath)}'`); + : readTail(toolLogPath, MAX_TOOL_LOG_BYTES); const lines = raw.trim().split("\n").filter(Boolean); totalToolCalls = lines.length; From b1b3fc56c3fd4f2497b556879d69396eeabf6b88 Mon Sep 17 00:00:00 2001 From: Jack Felke Date: Tue, 10 Mar 2026 10:46:35 -0700 Subject: [PATCH 3/3] fix(session-handoff,sharpen-followup,sequence-tasks): replace shell syntax in run() calls - session-handoff: hasCommand() uses 'which' instead of 'command -v' via git; gh pr list uses execFileSync directly instead of run() - sharpen-followup: diff commands use array args; status uses array args - sequence-tasks: ls-files uses array args, pipe to head replaced with JS slice Part of #172. --- src/tools/sequence-tasks.ts | 3 ++- src/tools/session-handoff.ts | 16 ++++++++++++---- src/tools/sharpen-followup.ts | 10 +++++----- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/tools/sequence-tasks.ts b/src/tools/sequence-tasks.ts index 22dea23..b6fbdc0 100644 --- a/src/tools/sequence-tasks.ts +++ b/src/tools/sequence-tasks.ts @@ -90,7 +90,8 @@ export function registerSequenceTasks(server: McpServer): void { // For locality: infer directories from path-like tokens in task text if (strategy === "locality") { // Use git ls-files with a depth limit instead of find for performance - const gitFiles = run("git ls-files 2>/dev/null | head -1000"); + const gitFilesRaw = run(["ls-files"]); + const gitFiles = gitFilesRaw.split("\n").slice(0, 1000).join("\n"); const knownDirs = new Set(); for (const f of gitFiles.split("\n").filter(Boolean)) { const parts = f.split("/"); diff --git a/src/tools/session-handoff.ts b/src/tools/session-handoff.ts index d199462..eb275de 100644 --- a/src/tools/session-handoff.ts +++ b/src/tools/session-handoff.ts @@ -2,14 +2,17 @@ import { z } from "zod"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { existsSync, readFileSync } from "fs"; import { join } from "path"; +import { execFileSync } from "child_process"; import { run, getBranch, getRecentCommits, getStatus } from "../lib/git.js"; import { readIfExists, findWorkspaceDocs } from "../lib/files.js"; import { STATE_DIR, now } from "../lib/state.js"; -/** Check if a CLI tool is available */ +/** Check if a CLI tool is available on PATH */ function hasCommand(cmd: string): boolean { - const result = run(`command -v ${cmd} 2>/dev/null`); - return !!result && !result.startsWith("[command failed"); + try { + execFileSync("which", [cmd], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }); + return true; + } catch { return false; } } export function registerSessionHandoff(server: McpServer): void { @@ -44,7 +47,12 @@ export function registerSessionHandoff(server: McpServer): void { // Only try gh if it exists if (hasCommand("gh")) { - const openPRs = run("gh pr list --state open --json number,title,headRefName 2>/dev/null || echo '[]'"); + let openPRs = "[]"; + try { + openPRs = execFileSync("gh", ["pr", "list", "--state", "open", "--json", "number,title,headRefName"], { + encoding: "utf-8", timeout: 10000, stdio: ["pipe", "pipe", "pipe"], + }).trim(); + } catch { /* gh not authed or no remote — skip */ } if (openPRs && openPRs !== "[]") { sections.push(`## Open PRs\n\`\`\`json\n${openPRs}\n\`\`\``); } diff --git a/src/tools/sharpen-followup.ts b/src/tools/sharpen-followup.ts index db5acaa..e95bdaf 100644 --- a/src/tools/sharpen-followup.ts +++ b/src/tools/sharpen-followup.ts @@ -27,10 +27,10 @@ function parsePortelainFiles(output: string): string[] { /** Get recently changed files, safe for first commit / shallow clones */ function getRecentChangedFiles(): string[] { // Try HEAD~1..HEAD, fall back to just staged, then unstaged - const commands = [ - "git diff --name-only HEAD~1 HEAD 2>/dev/null", - "git diff --name-only --cached 2>/dev/null", - "git diff --name-only 2>/dev/null", + const commands: string[][] = [ + ["diff", "--name-only", "HEAD~1", "HEAD"], + ["diff", "--name-only", "--cached"], + ["diff", "--name-only"], ]; const results = new Set(); for (const cmd of commands) { @@ -87,7 +87,7 @@ export function registerSharpenFollowup(server: McpServer): void { // Gather context to resolve ambiguity const contextFiles: string[] = [...(previous_files ?? [])]; const recentChanged = getRecentChangedFiles(); - const porcelainOutput = run("git status --porcelain 2>/dev/null"); + const porcelainOutput = run(["status", "--porcelain"]); const untrackedOrModified = parsePortelainFiles(porcelainOutput); const allKnownFiles = [...new Set([...contextFiles, ...recentChanged, ...untrackedOrModified])].filter(Boolean);