codeburn/src/guard/flags.ts
iamtoruk 6998c5ac07 fix: keep macOS and Linux path behaviour exact in guard flags and Hermes
Two of today's Windows fixes changed POSIX results. Guard flags counted
a backslash as a directory boundary on every platform, where it is an
ordinary filename character off Windows; it now counts only on win32,
while a forward slash counts everywhere so POSIX-shaped provider paths
still match on a Windows host. Hermes accepted drive-letter paths as
real workspaces on every host on the theory that a state.db can be read
on another machine; discovery is strictly local and the ledger contract
rules out restored databases, so that acceptance is Windows-only again.
2026-09-02 15:11:01 -07:00

88 lines
3.5 KiB
TypeScript

import { mkdir, readFile, writeFile } from 'fs/promises'
import type { ProjectSummary } from '../types.js'
import { flagsPath, guardDir } from './store.js'
// Per-project flag list computed at install / `guard refresh` time and read on
// SessionStart. The resolved opener text is stored here (not a code path into
// optimize) so the hot SessionStart handler never imports the analyzer.
export type ProjectFlag = { path: string; openers: string[] }
export type GuardFlags = { generatedAt: string; projects: ProjectFlag[] }
export const FLAG_STALE_MS = 7 * 24 * 60 * 60 * 1000
// optimize is loaded lazily so importing this module (for readFlags/matchFlag,
// which the SessionStart hook needs) does not pull the analyzer.
export async function buildFlags(projects: ProjectSummary[]): Promise<GuardFlags> {
const { findLowWorthCandidates, findContextBloatCandidates, LOW_WORTH_OPENER, CONTEXT_HEAVY_OPENER } =
await import('../optimize.js')
const lowWorth = new Set(findLowWorthCandidates(projects).map(c => c.project))
const contextHeavy = new Set(findContextBloatCandidates(projects).map(c => c.project))
const flags: ProjectFlag[] = []
for (const project of projects) {
const openers: string[] = []
if (lowWorth.has(project.project)) openers.push(LOW_WORTH_OPENER)
if (contextHeavy.has(project.project)) openers.push(CONTEXT_HEAVY_OPENER)
if (openers.length > 0) flags.push({ path: project.projectPath, openers })
}
return { generatedAt: new Date().toISOString(), projects: flags }
}
export async function readFlags(base?: string): Promise<GuardFlags | null> {
let raw: string
try {
raw = await readFile(flagsPath(base), 'utf-8')
} catch {
return null
}
try {
const parsed = JSON.parse(raw) as GuardFlags
if (typeof parsed?.generatedAt !== 'string' || !Array.isArray(parsed.projects)) return null
return parsed
} catch {
return null
}
}
export async function writeFlags(flags: GuardFlags, base?: string): Promise<void> {
await mkdir(guardDir(base), { recursive: true })
await writeFile(flagsPath(base), JSON.stringify(flags, null, 2) + '\n', 'utf-8')
}
export function flagsAgeMs(flags: GuardFlags): number {
const t = Date.parse(flags.generatedAt)
return Number.isNaN(t) ? Number.POSITIVE_INFINITY : Date.now() - t
}
// A flagged project path comes from provider data and can be POSIX-shaped on a
// Windows host, so a Windows host has to count either separator as a directory
// boundary. Everywhere else a backslash is an ordinary filename character and
// must never split a path.
const WINDOWS_HOST = process.platform === 'win32'
function endsWithSeparator(p: string): boolean {
return p.endsWith('/') || (WINDOWS_HOST && p.endsWith('\\'))
}
function norm(p: string): string {
return p.length > 1 && endsWithSeparator(p) ? p.slice(0, -1) : p
}
function isWithin(target: string, base: string): boolean {
if (target === base) return true
if (target.startsWith(`${base}/`)) return true
return WINDOWS_HOST && target.startsWith(`${base}\\`)
}
// Openers for the flagged project the cwd sits in (exact match or a subdir of
// it); most-specific project wins. Empty when the cwd is not flagged.
export function matchFlag(flags: GuardFlags, cwd: string): string[] {
const target = norm(cwd)
let best: ProjectFlag | null = null
for (const flag of flags.projects) {
const base = norm(flag.path)
if (isWithin(target, base)) {
if (!best || base.length > norm(best.path).length) best = flag
}
}
return best ? best.openers : []
}