Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/aienvmap.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { main } from "../src/cli.js";

main(process.argv.slice(2)).catch((error) => {
console.error(`aienvmap: ${error.message}`);
process.exit(1);
process.exitCode = 1;
});
34 changes: 33 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ const commands = new Map([

const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
const globalValueOptions = new Set(["--dir"]);
const booleanOptions = new Set([
"all", "check", "ci", "clear_import", "deep", "dry_run", "full_packages", "inspect_project_wrappers",
"json", "markdown", "no_sync", "open", "owner_verification", "portable", "quick", "quiet", "record",
"security", "show_paths", "uninstall", "verbose"
]);
const requiredValueOptions = new Set([
"action", "actor", "after", "against", "agent", "agents", "alias", "baseline", "before", "case_summary",
"change", "comparison", "dir", "evidence", "format", "home_evidence", "id", "if_revision", "import",
"inspect_home", "inspect_homes", "lease_minutes", "portable_compare", "portable_from", "reason", "ref",
"review", "scenario", "session", "status", "strict", "summary", "target", "type"
]);
const knownOptions = new Set([...booleanOptions, ...requiredValueOptions, "write"]);
const positionalCommands = new Set(["demo", "onboard", "snippet"]);

export async function main(argv) {
const { command, rest, globalArgs } = splitCommand(argv);
Expand All @@ -73,10 +86,24 @@ export async function main(argv) {
printUsage();
throw new Error(`unknown command "${command}"`);
}
await run({ ...globalArgs, ...parseArgs(rest) });
if (rest.includes("--help") || rest.includes("-h")) {
printUsage();
return;
}
const args = { ...globalArgs, ...parseArgs(rest) };
if (!positionalCommands.has(command) && args._.length) {
throw new Error(`${command}: unexpected argument "${args._[0]}"`);
}
if (["demo", "snippet"].includes(command) && args._.length > 1) {
throw new Error(`${command}: unexpected argument "${args._[1]}"`);
}
await run(args);
}

function splitCommand(argv) {
if (["-h", "--help", "-v", "--version", "version"].includes(argv[0])) {
return { command: argv[0], rest: argv.slice(1), globalArgs: { _: [] } };
}
const leading = [];
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
Expand Down Expand Up @@ -109,10 +136,15 @@ export function parseArgs(argv) {
}
const [rawKey, inline] = arg.slice(2).split("=", 2);
const key = rawKey.replaceAll("-", "_");
if (!knownOptions.has(key)) throw new Error(`unknown option "--${rawKey}"`);
if (inline !== undefined) {
out[key] = inline;
} else if (booleanOptions.has(key)) {
out[key] = true;
} else if (argv[i + 1] && !argv[i + 1].startsWith("--")) {
out[key] = argv[++i];
} else if (requiredValueOptions.has(key)) {
throw new Error(`--${rawKey} requires a value`);
} else {
out[key] = true;
}
Expand Down
8 changes: 4 additions & 4 deletions src/commands/compile.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from "node:fs/promises";
import { diagnose } from "../doctor.js";
import { readJson } from "../fsutil.js";
import { assertWritePathInsideWorkspace, readJsonStrict, writeTextAtomic } from "../fsutil.js";
import { openIntents, readJsonl, readTimeline } from "../timeline.js";
import { aiEnvPath, intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js";
import { renderAIEnv } from "../render.js";
Expand All @@ -9,7 +8,7 @@ import { buildPreflight } from "../preflight.js";

export async function compileWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const timeline = await readTimeline(timelinePath(dir));
const intents = openIntents(await readJsonl(intentsPath(dir)));
Expand All @@ -19,7 +18,8 @@ export async function compileWorkspace(args) {
...manifest,
preflight: buildPreflight(manifest, warnings, intents)
}, timeline, warnings, intents, policy);
await fs.writeFile(aiEnvPath(dir), rendered, "utf8");
await assertWritePathInsideWorkspace(dir, aiEnvPath(dir));
await writeTextAtomic(aiEnvPath(dir), rendered);
if (!args.quiet) {
console.log(`compiled ${aiEnvPath(dir)}`);
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/context.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { diagnose } from "../doctor.js";
import { readJson } from "../fsutil.js";
import { readJsonStrict } from "../fsutil.js";
import { openIntents, readJsonl, readTimeline } from "../timeline.js";
import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js";
import { renderContext } from "../render.js";
Expand All @@ -13,7 +13,7 @@ import { externalSbomWarnings, loadExternalSbomStartupSignal } from "../external

export async function contextWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const timeline = await readTimeline(timelinePath(dir));
const intents = openIntents(await readJsonl(intentsPath(dir)));
Expand Down
41 changes: 25 additions & 16 deletions src/commands/dash.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import fs from "node:fs/promises";
import { execFile } from "node:child_process";
import path from "node:path";
import { promisify } from "node:util";
import { diagnose } from "../doctor.js";
import { exists, readJson } from "../fsutil.js";
import { exists, readJsonStrict, writeTextAtomic } from "../fsutil.js";
import { openIntents, readJsonl, readTimeline } from "../timeline.js";
import { dashboardPath, intentsPath, manifestPath, planJsonPath, planMdPath, timelinePath, workspaceDir } from "../paths.js";
import { renderDashboard } from "../render.js";
Expand All @@ -11,9 +10,11 @@ import { recommendedActions } from "../actions.js";
import { strictResult } from "../enforcement.js";
import { buildPreflight } from "../preflight.js";

const execFileAsync = promisify(execFile);

export async function dashWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const timeline = await readTimeline(timelinePath(dir));
const intents = openIntents(await readJsonl(intentsPath(dir)));
Expand All @@ -32,10 +33,9 @@ export async function dashWorkspace(args) {
ciReadiness: ciReadiness(warnings)
}, timeline, warnings, intents, policy);
const out = dashboardPath(dir);
await fs.mkdir(path.dirname(out), { recursive: true });
await fs.writeFile(out, html, "utf8");
await writeTextAtomic(out, html);
if (!args.quiet) console.log(`dashboard: ${out}`);
if (args.open) openFile(out);
if (args.open) await openDashboardFile(out);
return { dashboard: out };
}

Expand All @@ -60,7 +60,7 @@ async function detectedPlanArtifacts(dir) {
}

async function detectedPlanRemediation(dir) {
const plan = await readJson(planJsonPath(dir), {});
const plan = await readJsonStrict(planJsonPath(dir), {});
return (plan.remediationSteps || []).slice(0, 5).map((item) => ({
package: item.package || "unknown",
severity: item.severity || "unknown",
Expand All @@ -71,20 +71,29 @@ async function detectedPlanRemediation(dir) {
}

async function detectedPlanEnvironment(dir) {
const plan = await readJson(planJsonPath(dir), {});
const plan = await readJsonStrict(planJsonPath(dir), {});
return (plan.environmentSteps || []).slice(0, 5).map((item) => ({
code: item.code || "unknown",
category: item.category || "environment",
summary: item.summary || ""
}));
}

function openFile(file) {
if (process.platform === "win32") {
execFile("cmd", ["/c", "start", "", file], { windowsHide: true });
} else if (process.platform === "darwin") {
execFile("open", [file]);
} else {
execFile("xdg-open", [file]);
export function dashboardOpenCommand(file, platform = process.platform) {
if (platform === "win32") return { command: "explorer.exe", args: [file] };
if (platform === "darwin") return { command: "open", args: [file] };
return { command: "xdg-open", args: [file] };
}

export async function openDashboardFile(file, options = {}) {
const launch = dashboardOpenCommand(file, options.platform || process.platform);
const run = options.run || execFileAsync;
try {
await run(launch.command, launch.args, { windowsHide: true, timeout: 10000 });
} catch (cause) {
const error = new Error(`dashboard was written but could not be opened with ${launch.command}`);
error.code = "AIENVMAP_DASHBOARD_OPEN_FAILED";
error.cause = cause;
throw error;
}
}
6 changes: 3 additions & 3 deletions src/commands/diff.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { diffManifests } from "../diff.js";
import { readJson } from "../fsutil.js";
import { readJsonStrict } from "../fsutil.js";
import { manifestPath, previousManifestPath, workspaceDir } from "../paths.js";

export async function diffWorkspace(args) {
const dir = workspaceDir(args);
const previous = await readJson(previousManifestPath(dir));
const current = await readJson(manifestPath(dir));
const previous = await readJsonStrict(previousManifestPath(dir));
const current = await readJsonStrict(manifestPath(dir));
if (!current) throw new Error("missing manifest; run `aienvmap sync` first");
const changes = diffManifests(previous, current);
if (!changes.length) {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/discover.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from "node:path";
import { aiDefaultReadOrder, aiDiscoveryEntry, aiEntryContract, aiEnvMap, aiSessionUseContract, aiStartHere, aiStatus, aiSummary, npxAiFallbackPrompt, npxAiMissingFallbackPrompt, npxAiStartupChecklist } from "../ai-contract.js";
import { hasAgentPointer } from "../agent-pointer.js";
import { agentSkillLocations, hasAienvmapAgentSkill } from "../agent-skill.js";
import { readJson } from "../fsutil.js";
import { readJsonStrict } from "../fsutil.js";
import { aiEnvPath, dashboardPath, discoveryJsonPath, manifestPath, sbomJsonPath, stateDir, stateReadmePath, statusJsonPath, summaryMdPath, workspaceDir } from "../paths.js";

const pointerFiles = [
Expand All @@ -25,7 +25,7 @@ const sessionStart = [

export async function discoverWorkspace(args = {}) {
const dir = workspaceDir(args);
const status = await readJson(statusJsonPath(dir), null);
const status = await readJsonStrict(statusJsonPath(dir), null);
const artifacts = await discoverArtifacts(dir);
const pointers = await discoverPointers(dir);
const skills = await discoverAgentSkills(dir);
Expand Down
4 changes: 2 additions & 2 deletions src/commands/doctor.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { diagnose } from "../doctor.js";
import { readJson } from "../fsutil.js";
import { readJsonStrict } from "../fsutil.js";
import { openIntents, readJsonl, readTimeline } from "../timeline.js";
import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js";
import { loadPolicy, policyWarnings } from "../policy.js";
Expand All @@ -11,7 +11,7 @@ export { strictResult } from "../enforcement.js";

export async function doctorWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const policy = await loadPolicy(dir);
const timeline = await readTimeline(timelinePath(dir));
Expand Down
4 changes: 2 additions & 2 deletions src/commands/handoff.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { diagnose } from "../doctor.js";
import { appendJsonLine, readJson } from "../fsutil.js";
import { appendJsonLine, readJsonStrict } from "../fsutil.js";
import { loadPolicy, policyWarnings } from "../policy.js";
import { intentsPath, manifestPath, timelinePath, workspaceDir } from "../paths.js";
import { renderHandoff } from "../render.js";
Expand All @@ -11,7 +11,7 @@ import { buildPreflight } from "../preflight.js";

export async function handoffWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const timeline = await readTimeline(timelinePath(dir));
const intents = openIntents(await readJsonl(intentsPath(dir)));
Expand Down
11 changes: 9 additions & 2 deletions src/commands/init.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import fs from "node:fs/promises";
import path from "node:path";
import { assertWritePathInsideWorkspace } from "../fsutil.js";
import { stateDir, workspaceDir } from "../paths.js";

export async function initWorkspace(args) {
const dir = workspaceDir(args);
await fs.mkdir(dir, { recursive: true });
await fs.mkdir(stateDir(dir), { recursive: true });
await fs.writeFile(`${stateDir(dir)}/policy.yml`, [
const policy = path.join(stateDir(dir), "policy.yml");
await assertWritePathInsideWorkspace(dir, policy);
await fs.writeFile(policy, [
"# aienvmap policy",
"# Keep this small and explicit so AI agents can avoid version drift.",
"# Default behavior is non-blocking: warn, ask, and record instead of locking.",
Expand All @@ -17,7 +22,9 @@ export async function initWorkspace(args) {
"globalInstalls: ask-first",
"runtimeChanges: ask-first",
""
].join("\n"), { flag: "wx" }).catch(() => {});
].join("\n"), { flag: "wx" }).catch((error) => {
if (error?.code !== "EEXIST") throw error;
});
if (!args.quiet) console.log(`initialized ${stateDir(dir)}`);
return { stateDir: stateDir(dir) };
}
7 changes: 3 additions & 4 deletions src/commands/plan.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from "node:fs/promises";
import { diagnose } from "../doctor.js";
import { readJson, writeJson } from "../fsutil.js";
import { readJsonStrict, writeJson, writeTextAtomic } from "../fsutil.js";
import { loadPolicy, policyWarnings } from "../policy.js";
import { intentsPath, manifestPath, planJsonPath, planMdPath, timelinePath, workspaceDir } from "../paths.js";
import { renderPlan } from "../render.js";
Expand All @@ -12,7 +11,7 @@ import { buildPreflight } from "../preflight.js";

export async function planWorkspace(args) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
const timeline = await readTimeline(timelinePath(dir));
const intents = openIntents(await readJsonl(intentsPath(dir)));
Expand All @@ -22,7 +21,7 @@ export async function planWorkspace(args) {

if (args.write) {
await writeJson(planJsonPath(dir), plan);
await fs.writeFile(planMdPath(dir), renderPlan(plan), "utf8");
await writeTextAtomic(planMdPath(dir), renderPlan(plan));
}

if (args.json) {
Expand Down
8 changes: 4 additions & 4 deletions src/commands/reconcile.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { inspectPackageManagers } from "../package-managers.js";
import { reconcileJsonPath, workspaceDir } from "../paths.js";
import { writeJson } from "../fsutil.js";
import { readJson } from "../fsutil.js";
import { readJsonStrict } from "../fsutil.js";
import { compareReconciliation } from "../reconcile-drift.js";
import path from "node:path";
import { buildPortableCaseSummary, buildPortableReconciliation, comparePortableReconciliations, readPortableEvidence, renderPortableCaseMarkdown } from "../portable-reconcile.js";
Expand Down Expand Up @@ -42,7 +42,7 @@ export async function reconcileWorkspace(args = {}) {
if (args.case_summary === true) throw new Error("--case-summary requires a portable reconciliation JSON file");
if (args.portable || args.portable_from || args.portable_compare || args.home_evidence || args.inspect_homes || args.write || args.check || args.quick || args.full_packages || args.show_paths || args.inspect_home || args.baseline) throw new Error("--case-summary cannot be combined with scanning, writing, checking, baseline, or path options");
const report = await readPortableEvidence(path.resolve(dir, String(args.case_summary)));
const comparison = args.comparison ? await readJson(path.resolve(dir, String(args.comparison)), null) : null;
const comparison = args.comparison ? await readJsonStrict(path.resolve(dir, String(args.comparison)), null) : null;
const summary = buildPortableCaseSummary(report, comparison);
if (args.markdown && args.json) throw new Error("use either --markdown or --json, not both");
if (args.markdown) console.log(renderPortableCaseMarkdown(summary));
Expand All @@ -65,15 +65,15 @@ export async function reconcileWorkspace(args = {}) {
if (args.portable_from) {
if (args.portable || args.write || args.check || args.quick || args.full_packages || args.show_paths || args.inspect_home || args.baseline) throw new Error("--portable-from cannot be combined with scanning, writing, checking, baseline, or path options");
if (args.portable_from === true) throw new Error("--portable-from requires a reconciliation JSON file");
const source = await readJson(path.resolve(dir, String(args.portable_from)), null);
const source = await readJsonStrict(path.resolve(dir, String(args.portable_from)), null);
if (source?.schemaName !== "aienvmap.reconcile" || source?.schemaVersion !== 1) throw new Error("--portable-from requires an aienvmap.reconcile v1 JSON artifact");
const portable = buildPortableReconciliation(source, { sourceMode: "artifact" });
if (args.json) console.log(JSON.stringify(portable, null, 2));
else if (!args.quiet) printPortable(portable);
return portable;
}
const baselinePath = args.baseline ? path.resolve(dir, String(args.baseline)) : reconcileJsonPath(dir);
const baseline = args.check ? await readJson(baselinePath, null) : null;
const baseline = args.check ? await readJsonStrict(baselinePath, null) : null;
if (args.check && !baseline) throw new Error(`missing reconciliation baseline at ${baselinePath}; run \`aienvmap reconcile --write\` first`);
if (args.check && baseline?.baselineUse?.checkEligible !== true) {
throw new Error(`reconciliation snapshot at ${baselinePath} was created automatically and is not an accepted drift baseline; review the environment, then run \`aienvmap reconcile --write\``);
Expand Down
6 changes: 3 additions & 3 deletions src/commands/sbom.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { sbomReadOrder } from "../ai-contract.js";
import { readJson, writeJson } from "../fsutil.js";
import { readJsonStrict, writeJson } from "../fsutil.js";
import fs from "node:fs/promises";
import { cyclonedxSbomPath, externalSbomEvidencePath, manifestPath, sbomJsonPath, workspaceDir } from "../paths.js";
import { compareSbomEvidence, importSbomEvidence, verifySbomEvidence } from "../sbom-evidence.js";
import { buildAiDecisionEnvelope } from "../ai-decision-envelope.js";

export async function sbomWorkspace(args = {}) {
const dir = workspaceDir(args);
const manifest = await readJson(manifestPath(dir));
const manifest = await readJsonStrict(manifestPath(dir));
if (!manifest) throw new Error("missing manifest; run `aienvmap sync` first");
if (args.import && args.clear_import) throw new Error("use either --import or --clear-import, not both");
if (args.clear_import && !args.write) throw new Error("--clear-import requires --write");
const evidenceFile = externalSbomEvidencePath(dir);
if (args.clear_import) await fs.rm(evidenceFile, { force: true });
const previousEvidence = !args.clear_import ? await readJson(evidenceFile, null) : null;
const previousEvidence = !args.clear_import ? await readJsonStrict(evidenceFile, null) : null;
const imported = args.import ? await importSbomEvidence(dir, args.import) : null;
const importedEvidence = imported ? {
...imported,
Expand Down
5 changes: 3 additions & 2 deletions src/commands/scan.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import fs from "node:fs/promises";
import { buildManifest } from "../manifest.js";
import { diffManifests } from "../diff.js";
import { appendJsonLine, exists, readJson, writeJson } from "../fsutil.js";
import { appendJsonLine, assertWritePathInsideWorkspace, exists, readJsonStrict, writeJson } from "../fsutil.js";
import { manifestPath, previousManifestPath, timelinePath, workspaceDir } from "../paths.js";

export async function scanWorkspace(args) {
const dir = workspaceDir(args);
const currentPath = manifestPath(dir);
const previous = await readJson(currentPath, null);
await assertWritePathInsideWorkspace(dir, currentPath);
const previous = await readJsonStrict(currentPath, null);
if (previous && await exists(currentPath)) {
await fs.copyFile(currentPath, previousManifestPath(dir));
}
Expand Down
Loading