@ybotok/loam 0.0.0 → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +138 -0
  2. package/COMPARISON.md +63 -0
  3. package/LICENSE +21 -0
  4. package/MIGRATING-from-OpenSpec.md +202 -0
  5. package/README.md +246 -9
  6. package/SCHEMA.md +425 -0
  7. package/SECURITY.md +9 -0
  8. package/dist/cli.js +142 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/commands/adopt.js +240 -0
  11. package/dist/commands/adopt.js.map +1 -0
  12. package/dist/commands/archive.js +1313 -0
  13. package/dist/commands/archive.js.map +1 -0
  14. package/dist/commands/delta.js +388 -0
  15. package/dist/commands/delta.js.map +1 -0
  16. package/dist/commands/dependencies.js +83 -0
  17. package/dist/commands/dependencies.js.map +1 -0
  18. package/dist/commands/docs-repo-gate.js +104 -0
  19. package/dist/commands/docs-repo-gate.js.map +1 -0
  20. package/dist/commands/doctor.js +85 -0
  21. package/dist/commands/doctor.js.map +1 -0
  22. package/dist/commands/explore.js +195 -0
  23. package/dist/commands/explore.js.map +1 -0
  24. package/dist/commands/format.js +17 -0
  25. package/dist/commands/format.js.map +1 -0
  26. package/dist/commands/gherkin.js +309 -0
  27. package/dist/commands/gherkin.js.map +1 -0
  28. package/dist/commands/init.js +250 -0
  29. package/dist/commands/init.js.map +1 -0
  30. package/dist/commands/instructions.js +70 -0
  31. package/dist/commands/instructions.js.map +1 -0
  32. package/dist/commands/list.js +291 -0
  33. package/dist/commands/list.js.map +1 -0
  34. package/dist/commands/migrate-openspec.js +950 -0
  35. package/dist/commands/migrate-openspec.js.map +1 -0
  36. package/dist/commands/new.js +413 -0
  37. package/dist/commands/new.js.map +1 -0
  38. package/dist/commands/rebase.js +356 -0
  39. package/dist/commands/rebase.js.map +1 -0
  40. package/dist/commands/show.js +320 -0
  41. package/dist/commands/show.js.map +1 -0
  42. package/dist/commands/status.js +254 -0
  43. package/dist/commands/status.js.map +1 -0
  44. package/dist/commands/unarchive.js +317 -0
  45. package/dist/commands/unarchive.js.map +1 -0
  46. package/dist/commands/validate.js +1591 -0
  47. package/dist/commands/validate.js.map +1 -0
  48. package/dist/commands/verify.js +775 -0
  49. package/dist/commands/verify.js.map +1 -0
  50. package/dist/commands/vouch.js +343 -0
  51. package/dist/commands/vouch.js.map +1 -0
  52. package/dist/core/agent.js +2065 -0
  53. package/dist/core/agent.js.map +1 -0
  54. package/dist/core/agents-stamp.js +68 -0
  55. package/dist/core/agents-stamp.js.map +1 -0
  56. package/dist/core/arch.js +130 -0
  57. package/dist/core/arch.js.map +1 -0
  58. package/dist/core/brief.js +733 -0
  59. package/dist/core/brief.js.map +1 -0
  60. package/dist/core/coherence.js +577 -0
  61. package/dist/core/coherence.js.map +1 -0
  62. package/dist/core/concurrency.js +51 -0
  63. package/dist/core/concurrency.js.map +1 -0
  64. package/dist/core/config.js +180 -0
  65. package/dist/core/config.js.map +1 -0
  66. package/dist/core/delta.js +476 -0
  67. package/dist/core/delta.js.map +1 -0
  68. package/dist/core/dependencies.js +356 -0
  69. package/dist/core/dependencies.js.map +1 -0
  70. package/dist/core/docs.js +144 -0
  71. package/dist/core/docs.js.map +1 -0
  72. package/dist/core/doctor.js +559 -0
  73. package/dist/core/doctor.js.map +1 -0
  74. package/dist/core/document-bytes.js +59 -0
  75. package/dist/core/document-bytes.js.map +1 -0
  76. package/dist/core/explore.js +225 -0
  77. package/dist/core/explore.js.map +1 -0
  78. package/dist/core/fleet-context.js +225 -0
  79. package/dist/core/fleet-context.js.map +1 -0
  80. package/dist/core/frontmatter.js +199 -0
  81. package/dist/core/frontmatter.js.map +1 -0
  82. package/dist/core/gherkin.js +463 -0
  83. package/dist/core/gherkin.js.map +1 -0
  84. package/dist/core/health.js +67 -0
  85. package/dist/core/health.js.map +1 -0
  86. package/dist/core/ids.js +122 -0
  87. package/dist/core/ids.js.map +1 -0
  88. package/dist/core/issue.js +9 -0
  89. package/dist/core/issue.js.map +1 -0
  90. package/dist/core/json.js +74 -0
  91. package/dist/core/json.js.map +1 -0
  92. package/dist/core/likec4.js +479 -0
  93. package/dist/core/likec4.js.map +1 -0
  94. package/dist/core/maturity.js +66 -0
  95. package/dist/core/maturity.js.map +1 -0
  96. package/dist/core/openapi-merge.js +552 -0
  97. package/dist/core/openapi-merge.js.map +1 -0
  98. package/dist/core/openapi.js +255 -0
  99. package/dist/core/openapi.js.map +1 -0
  100. package/dist/core/openspec-inventory.js +1440 -0
  101. package/dist/core/openspec-inventory.js.map +1 -0
  102. package/dist/core/path-safety.js +168 -0
  103. package/dist/core/path-safety.js.map +1 -0
  104. package/dist/core/provenance.js +720 -0
  105. package/dist/core/provenance.js.map +1 -0
  106. package/dist/core/records.js +33 -0
  107. package/dist/core/records.js.map +1 -0
  108. package/dist/core/repo.js +436 -0
  109. package/dist/core/repo.js.map +1 -0
  110. package/dist/core/report.js +47 -0
  111. package/dist/core/report.js.map +1 -0
  112. package/dist/core/results.js +199 -0
  113. package/dist/core/results.js.map +1 -0
  114. package/dist/core/spec.js +481 -0
  115. package/dist/core/spec.js.map +1 -0
  116. package/dist/core/staging.js +890 -0
  117. package/dist/core/staging.js.map +1 -0
  118. package/dist/core/status.js +1104 -0
  119. package/dist/core/status.js.map +1 -0
  120. package/dist/core/steps.js +72 -0
  121. package/dist/core/steps.js.map +1 -0
  122. package/dist/core/verify.js +807 -0
  123. package/dist/core/verify.js.map +1 -0
  124. package/dist/core/version.js +24 -0
  125. package/dist/core/version.js.map +1 -0
  126. package/package.json +63 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor.js","sourceRoot":"","sources":["../../src/core/doctor.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,OAAO,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AAI,GAAG;SACrG,CAAC,CAAC;IACL,CAAC;IAED,8EAA8E;IAC9E,4EAA4E;IAC5E,kDAAkD;IAClD,MAAM,MAAM,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAE7F,OAAO;QACL,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,KAAK,SAAS,CAAC;QACpE,OAAO,EAAE;YACP,OAAO,EAAE,cAAc;YACvB,OAAO,EAAE,YAAY;YACrB,IAAI,EAAE,OAAO,CAAC,OAAO;YACrB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,IAAI,EAAE,OAAO,CAAC,IAAI;SACnB;QACD,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE;QAClE,IAAI,EAAE;YACJ,IAAI,EAAE,OAAO;YACb,MAAM;YACN,QAAQ;YACR,QAAQ;YACR,WAAW;YACX,SAAS;SACV;QACD,MAAM,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,cAAc,EAAE,cAAc,CAAC,MAAM,EAAE;QAC5E,cAAc;QACd,MAAM;QACN,SAAS;QACT,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["/** Read-only installation/repository diagnostics for `loam doctor`. */\nimport { constants, existsSync } from \"node:fs\";\nimport { access, readFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { CONFIG_FILENAME, configPath, parseConfig, type LoamConfig } from \"./config.js\";\nimport { LOAM_VERSION } from \"./version.js\";\nimport { agentsPath, docsRepoState, landscapePath, listFeatures, listServices } from \"./repo.js\";\nimport { loadFile } from \"./likec4.js\";\nimport { conflictMarkerLines } from \"./fleet-context.js\";\nimport { AGENT_TOOLS, DELIVERIES, plannedCommandFiles, type Delivery } from \"./agent.js\";\nimport {\n agentsStaleFinding,\n agentsStampLine,\n agentsStampVersion,\n versionTrails,\n} from \"./agents-stamp.js\";\nimport { scanWritePathResidue, type WritePathResidue } from \"./staging.js\";\n\nexport type DoctorSeverity = \"blocker\" | \"warning\";\n\nexport interface DoctorFinding {\n severity: DoctorSeverity;\n code: string;\n message: string;\n /**\n * The next command or edit that clears this finding. Mandatory, not optional:\n * a diagnostic that names a problem without naming its fix is a diagnostic\n * the reader has to research, and `doctor` is what someone runs precisely\n * because they do not yet know what loam wants from them.\n */\n fix: string;\n}\n\nexport interface DoctorReport {\n healthy: boolean;\n runtime: {\n package: \"@ybotok/loam\";\n version: string;\n node: string;\n platform: NodeJS.Platform;\n arch: string;\n };\n config: {\n path: string;\n status: \"missing\" | \"invalid\" | \"valid\";\n error: string | null;\n };\n docs: {\n path: string | null;\n exists: boolean;\n readable: boolean;\n writable: boolean;\n servicesDir: boolean;\n landscape: boolean;\n };\n counts: { services: number; activeFeatures: number };\n currentService: {\n configured: string | null;\n status: \"unbound\" | \"matched\" | \"unknown\";\n };\n /** The agent surface of this repo — see `inspectAgentSurface`. */\n agents: AgentSurface;\n /**\n * What a write that did not finish left in the docs repo, or null when\n * `docsDir` never resolved. Reported as state, like `docs` and `counts`: a\n * lock somebody is legitimately holding right now is a fact, not a complaint.\n */\n writePath: WritePathResidue | null;\n findings: DoctorFinding[];\n}\n\nexport interface AgentSurface {\n /** Tool ids this repo has an agent surface for. Empty is legal (`init --no-commands`). */\n tools: string[];\n /** Whether `tools` came from loam.json's own record or from what is on disk. */\n toolsSource: \"config\" | \"disk\";\n /** How many files the running binary would lay down for `tools`. */\n plannedFiles: number;\n /** Repo-relative paths of those files that are not there. */\n missingFiles: string[];\n /**\n * Repo-relative paths of the ones that ARE there carrying no version stamp,\n * or one older than this binary — see `staleAgentFiles`.\n */\n staleFiles: string[];\n stamp: {\n /** Where the docs repo's AGENTS.md is, or null when `docsDir` did not resolve. */\n path: string | null;\n /** Whether it could be read at all — absent and unstamped are different facts. */\n present: boolean;\n /** The version the stamp names, null when there is none (or an unparseable one). */\n version: string | null;\n /** Whether `agents.stale` fired: the stamp is missing or trails this binary. */\n stale: boolean;\n };\n}\n\ninterface ConfigInspection {\n status: DoctorReport[\"config\"][\"status\"];\n config: LoamConfig | null;\n error: string | null;\n}\n\n/**\n * Read and validate the config the way every other command does — through\n * `parseConfig`, never through a second implementation.\n *\n * doctor used to carry its own validator. It agreed with `loadConfig` on the\n * fields both happened to check and disagreed everywhere else: doctor accepted\n * a `gherkinDir` of `\"../shared\"` that `loadConfig` refused outright, so\n * `doctor` reported a healthy repo in which no command could run. Two\n * validators are two opinions about the same file, and the one the user reads\n * is never the one the commands obey.\n */\nasync function inspectConfig(cwd: string): Promise<ConfigInspection> {\n const path = configPath(cwd);\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return { status: \"missing\", config: null, error: null };\n return {\n status: \"invalid\",\n config: null,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n try {\n return { status: \"valid\", error: null, config: parseConfig(raw, dirname(path)) };\n } catch (error) {\n return {\n status: \"invalid\",\n config: null,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nasync function canAccess(path: string, mode: number): Promise<boolean> {\n try {\n await access(path, mode);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Read the landscape, don't just stat it. `doctor` reported `landscape: yes`\n * for a file full of conflict markers — the check answered \"is there a file\",\n * which is not the question anyone runs doctor to ask.\n */\nasync function inspectLandscape(path: string, findings: DoctorFinding[]): Promise<void> {\n let source: string;\n try {\n source = await readFile(path, \"utf8\");\n } catch (error) {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.landscape-unreadable\",\n message: `${path} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`,\n fix: `Check permissions on ${path}.`,\n });\n return;\n }\n\n // The three-way merge left its markers in the file. Checked BEFORE the\n // parser, because a conflicted landscape does parse sometimes — both sides of\n // a conflict can be syntactically valid LikeC4 — and \"your map contains two\n // halves of two different maps\" is a more useful sentence than any parser\n // error. This is the failure mode of onboarding a fleet: ten people adopt ten\n // services into one landscape.likec4 in the same week.\n //\n // The scan itself is fleet-context's, which is where the same rule already\n // grades every other document loam reads. doctor kept a second copy of it,\n // and a second copy of a rule is a second chance to spell it differently;\n // what doctor owns is what a conflicted landscape COSTS, which is the finding\n // below and not the search.\n const conflicted = conflictMarkerLines(source);\n if (conflicted.length > 0) {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.landscape-merge-conflict\",\n message:\n `architecture/landscape.likec4 still contains merge conflict markers ` +\n `(line${conflicted.length === 1 ? \"\" : \"s\"} ${conflicted.join(\", \")}).`,\n fix: `Resolve the conflict in ${path} — keep BOTH services' elements and edges, then re-run \\`loam doctor\\`.`,\n });\n return;\n }\n\n const doc = await loadFile(path);\n if (doc.errors.length > 0) {\n const first = doc.errors[0]!;\n findings.push({\n severity: \"blocker\",\n code: \"doctor.landscape-invalid\",\n message:\n `architecture/landscape.likec4 does not parse: ${first.message}` +\n (first.line === undefined ? \"\" : ` (line ${first.line})`) +\n (doc.errors.length > 1 ? ` — and ${doc.errors.length - 1} more` : \"\"),\n fix: `Fix ${path}; every fleet-wide check is blind until it parses.`,\n });\n }\n}\n\n/**\n * The tool ids loam.json records `init` as having written files for, or null\n * when it records none we can plan for.\n *\n * `parseConfig` checks `agentTools`' SHAPE and deliberately not its contents —\n * a config written by a newer binary may name a tool this one has never heard\n * of, and refusing to load it would break every command, not just this check.\n * So the registry filter belongs here: `plannedCommandFiles` throws on an id it\n * does not know, and a config from the future must not turn the read-only\n * preflight into a crash. A tool we cannot plan files for is a tool we have\n * nothing to say about.\n */\nfunction recordedTools(config: LoamConfig | null): string[] | null {\n const ids = (config?.agentTools ?? []).filter((t) => t in AGENT_TOOLS);\n return ids.length === 0 ? null : ids;\n}\n\n/**\n * Which tools this repo has agent files for, asked of the layout itself: a tool\n * counts when any file it would be given is already there.\n *\n * The fallback for a loam.json written before `agentTools` existed, and the\n * only answer a hand-written one can have — so its absence must never be the\n * thing that reports a problem. This asks a narrower question than `init`'s\n * own scan, and on purpose: init scans for a tool's dot-directory to decide\n * what a repo would LIKE, while doctor grades what loam has already put there.\n * A repo that runs Claude Code and took `--no-commands --no-skills` has chosen\n * to have no loam files, and is not behind the binary for it.\n */\nfunction detectedTools(repoRoot: string): string[] {\n return Object.keys(AGENT_TOOLS).filter((id) =>\n plannedCommandFiles(repoRoot, [id]).some((f) => existsSync(f.path)));\n}\n\n/**\n * Which deliveries this repo actually HOLDS for one tool — a delivery counts\n * when at least one of its files is on disk.\n *\n * `loam init --no-skills` (or `--no-commands`) records the tool in `agentTools`\n * and writes one delivery, so planning both and subtracting what exists reported\n * every skill file as missing on a brand-new repo — under a message saying it\n * \"was initialized by an older loam\" and a `fix` that re-runs init without the\n * flag that was the whole point. Which deliveries a repo asked for is written\n * down nowhere, and must not be: the files ARE the record (there is no state\n * file loam can disagree with). So the question is asked of them.\n *\n * A tool with NO files at all is the other story — recorded, then deleted — and\n * the caller falls back to the full plan there, which is what the finding's\n * \"or they were deleted\" already says.\n */\nfunction heldDeliveries(repoRoot: string, tool: string): readonly Delivery[] {\n const held = DELIVERIES.filter((d) =>\n plannedCommandFiles(repoRoot, [tool], [d]).some((f) => existsSync(f.path)));\n return held.length > 0 ? held : DELIVERIES;\n}\n\n/**\n * Of the planned files that ARE here, the ones whose stamp is missing or older\n * than this binary.\n *\n * The stamp is the ONLY thing read out of a generated file — never the body.\n * Comparing bodies would yield \"your file differs from the template\", one step\n * from offering to rewrite it, which is the thing loam refuses: a team's edits\n * to a generated file outrank ours. A stamp is a different claim — it says\n * which loam wrote these instructions — and it can be false while every edit\n * around it is legitimate. Same doctrine as AGENTS.md (agents-stamp.ts), same\n * repair: a human looks, and bumps the stamp or deletes the file so a re-run of\n * `loam init` lays down the current one.\n *\n * Absence of a stamp counts, because that is what every file written before\n * stamping existed looks like — precisely the \"initialized by an older loam\"\n * population this check is for.\n */\nasync function staleAgentFiles(\n repoRoot: string,\n planned: Array<{ path: string }>,\n): Promise<string[]> {\n // Read them together rather than one after another. `planned` is bounded by\n // the tool registry — every delivery of every tool loam knows, a couple of\n // hundred small files — so there is nothing here worth a concurrency cap, and\n // `Promise.all` preserves input order, which is the only property the caller\n // asks of the list it gets back.\n const graded = await Promise.all(planned.map(async (file): Promise<string | null> => {\n let text: string;\n try {\n text = await readFile(file.path, \"utf8\");\n } catch {\n // Unreadable is not stale: it is either the missing-file finding above or\n // a permissions problem, and neither is answered by editing a stamp.\n return null;\n }\n const stamp = agentsStampVersion(text);\n if (stamp === null || versionTrails(stamp, LOAM_VERSION)) {\n return relative(repoRoot, file.path).split(/[\\\\/]/).join(\"/\");\n }\n return null;\n }));\n return graded.filter((p) => p !== null);\n}\n\n/**\n * What the running binary would write for this repo's tools that is not here,\n * and what is here under an older loam's name.\n *\n * Presence is `existsSync`, the same probe `init` uses to compute its `skipped`\n * list, so doctor cannot disagree with init about which files init would write.\n */\nasync function inspectAgentSurface(\n repoRoot: string,\n config: LoamConfig | null,\n docsDir: string | null,\n findings: DoctorFinding[],\n): Promise<AgentSurface> {\n const recorded = recordedTools(config);\n const tools = recorded ?? detectedTools(repoRoot);\n const planned = tools.flatMap((id) =>\n plannedCommandFiles(repoRoot, [id], heldDeliveries(repoRoot, id)));\n const present = planned.filter((f) => existsSync(f.path));\n const missingFiles = planned\n .filter((f) => !existsSync(f.path))\n .map((f) => relative(repoRoot, f.path).split(/[\\\\/]/).join(\"/\"));\n const staleFiles = await staleAgentFiles(repoRoot, present);\n\n if (missingFiles.length > 0) {\n // A warning, never a blocker: an out-of-date command set is a repo whose\n // agents have fewer entry points than they could, not one where anything\n // refuses to run. doctor's blockers are for the second kind.\n //\n // The fix spells `--docs` and `--tools` and deliberately NOT `--service`:\n // `init` spreads the committed config forward, and a `--docs`-less re-run\n // keeps the pointer the repo already commits, so the binding survives\n // untouched. Every interpolation here stands for exactly one argument —\n // test/agent-commands-runnable.test.ts parses this string, and a `${flags}`\n // holding three of them is a command it cannot check.\n findings.push({\n severity: \"warning\",\n code: \"doctor.agent-files-missing\",\n message:\n `${missingFiles.length} of the ${planned.length} command and skill files loam v${LOAM_VERSION} `\n + `lays down for ${tools.join(\", \")} are not in this repo — it was initialized by an older loam, `\n + `or they were deleted: ${missingFiles.join(\", \")}`,\n fix:\n `Re-run \\`loam init --docs ${config?.docsDirAsWritten ?? \"<dir>\"} --tools ${tools.join(\",\")}\\` `\n + \"here — it writes only the files that are absent and leaves every existing one untouched, and \"\n + \"it keeps this repo's service binding. Nothing is regenerated, so leaving this standing costs \"\n + \"entry points and nothing else.\",\n });\n }\n\n if (staleFiles.length > 0) {\n // Also a warning, and for a stronger reason than the one above: these files\n // are the team's now. Only a person can say whether their edits still mean\n // what the current binary's tables say, so loam reports and stops.\n findings.push({\n severity: \"warning\",\n code: \"doctor.agent-files-stale\",\n message:\n `${staleFiles.length} of the ${planned.length} command and skill files here carry no `\n + `\\`${agentsStampLine(LOAM_VERSION)}\\` stamp, or one older than this loam — the protocol and `\n + `code tables they instruct an agent with may describe a loam that no longer exists: `\n + `${staleFiles.join(\", \")}`,\n fix:\n \"Read each against the body this loam writes, then set its stamp line to \"\n + `\\`${agentsStampLine(LOAM_VERSION)}\\`; or delete the file and re-run \\`loam init\\` to lay `\n + \"down the current one. loam never rewrites a file that exists — your edits outrank the \"\n + \"template, which is why the stamp is a human's claim and not a refresh.\",\n });\n }\n\n // AGENTS.md lives in the DOCS repo, not here: it travels with the thing it\n // describes. The comparison is `agentsStaleFinding`'s, not a second copy of\n // it — doctor only adds the `fix` column its own findings owe the reader.\n const agentsFile = docsDir === null ? null : agentsPath(docsDir);\n let agentsText: string | null = null;\n if (agentsFile !== null) {\n try {\n agentsText = await readFile(agentsFile, \"utf8\");\n } catch {\n // Unreadable reads as absent, exactly as `validate --all` treats it: no\n // file, no contract to have drifted. An unreadable docs repo is already\n // its own finding.\n }\n }\n const stale = agentsStaleFinding(agentsText, LOAM_VERSION);\n if (stale !== null) {\n findings.push({\n severity: \"warning\",\n code: stale.code,\n message: stale.message,\n fix:\n `Review ${agentsFile} against the current \\`loam --help\\`, then set its stamp line to `\n + `\\`${agentsStampLine(LOAM_VERSION)}\\`. loam never rewrites that file — bumping the stamp IS `\n + \"the record that somebody looked.\",\n });\n }\n\n return {\n tools,\n toolsSource: recorded === null ? \"disk\" : \"config\",\n plannedFiles: planned.length,\n missingFiles,\n staleFiles,\n stamp: {\n path: agentsFile,\n present: agentsText !== null,\n version: agentsText === null ? null : agentsStampVersion(agentsText),\n stale: stale !== null,\n },\n };\n}\n\n/**\n * Grade what a write that did not finish left in the docs repo.\n *\n * Three of the four are blockers, which is unusual for doctor and deliberate:\n * they are not \"you have fewer entry points than you could\", they are \"the\n * living docs may be half-written and the next reader cannot tell\". Before this\n * existed, a SIGKILL between two of archive's renames left `doctor: healthy:\n * true` over merged spec.md + openapi.yaml and an unmerged landscape, and the\n * next `loam archive` reported loam's own half-merge as the author's bug.\n *\n * The temp files are the exception: a `.loam-*.tmp` was never linked into place,\n * so nothing reads it and nothing depends on it. It is litter, not damage.\n */\nfunction gradeWritePathResidue(\n docsDir: string,\n residue: WritePathResidue,\n findings: DoctorFinding[],\n): void {\n if (residue.lock !== null) {\n const lockFile = join(docsDir, residue.lock.path);\n findings.push({\n // Held by a live process is a fact about right now — wait and re-run.\n // Held by a process that no longer exists is damage: nothing will ever\n // release it, and every archive and unarchive refuses `docs-busy` until\n // somebody deletes it.\n severity: residue.lock.stale ? \"blocker\" : \"warning\",\n code: \"doctor.docs-locked\",\n message: residue.lock.stale\n ? `${residue.lock.path} is held by ${residue.lock.holder}, a process that no longer exists on this host — every \\`loam archive\\` and \\`loam unarchive\\` will refuse with \\`docs-busy\\` until it is gone.`\n : `${residue.lock.path} is held by ${residue.lock.holder}; another archive or unarchive is running against this docs repo.`,\n fix: residue.lock.stale\n ? `Delete ${lockFile} — its holder is dead, so nothing is going to release it. Check \\`loam doctor\\` again afterwards for an interrupted commit.`\n : \"Wait for it to finish and re-run; nothing is read or written while it is held.\",\n });\n }\n\n if (residue.intentUnreadable) {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.commit-unreadable\",\n message: `${docsDir} holds a .loam-commit that cannot be read — a commit was interrupted and the one record of which files it had already written is unreadable.`,\n fix: \"Hand this to a human: compare the living docs against version control before running any loam command that writes. `loam archive` and `loam unarchive` both refuse with `commit-interrupted` while it is there.\",\n });\n } else if (residue.intent !== null) {\n const i = residue.intent;\n // The command is spelled out per branch rather than interpolated into one\n // sentence: `loam ${i.command} ${i.feature}` reads fine to a person and is\n // opaque to test/agent-commands-runnable.test.ts, which parses the commands\n // loam prints against the real program. Same discipline as spelling `code:`\n // literally — be visible to your own guard.\n const repair = i.command === \"archive\"\n ? `\\`loam archive ${i.feature}\\` — it recovers first, under the lock, putting the half-written files back from the snapshot`\n : `\\`loam unarchive ${i.feature}\\` — it recovers first, under the lock, finishing the restore (an interrupted restore is FINISHED, never undone: the merged text it was replacing is written down nowhere)`;\n findings.push({\n severity: \"blocker\",\n code: \"doctor.commit-interrupted\",\n message:\n `A ${i.command === \"archive\" ? `\\`loam archive ${i.feature}\\`` : `\\`loam unarchive ${i.feature}\\``} `\n + `was killed mid-commit (${i.host}, pid ${i.pid}, ${i.at}) — `\n + `${i.files.length} file(s) may be half-written: ${i.files.map((f) => f.path).join(\", \")}`,\n fix: `Re-run ${repair}, and refuses with \\`commit-interrupted\\` rather than guessing if a file has been edited since.`,\n });\n }\n\n if (residue.temps.length > 0) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.staging-temps\",\n message: `${residue.temps.length} orphaned staging file(s) under ${docsDir}: ${residue.temps.join(\", \")} — a killed writer's scratch, never linked into place.`,\n fix: \"The next `loam archive` or `loam unarchive` removes its own; delete any that remain. Nothing reads them, so they cost disk and nothing else.\",\n });\n }\n}\n\nexport async function diagnose(cwd = process.cwd()): Promise<DoctorReport> {\n const inspected = await inspectConfig(cwd);\n const path = configPath(cwd);\n const findings: DoctorFinding[] = [];\n if (inspected.status === \"missing\") {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.config-missing\",\n message: `No ${CONFIG_FILENAME} found at or above ${cwd}.`,\n fix: \"Run `loam init --docs <path-to-docs-repo>` here (add `--create` to make a new docs repo).\",\n });\n } else if (inspected.status === \"invalid\") {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.config-invalid\",\n message: `Invalid ${CONFIG_FILENAME}: ${inspected.error ?? \"unknown error\"}`,\n fix: `Repair ${path} — or delete it and re-run \\`loam init\\`.`,\n });\n }\n\n const docsDir = inspected.config?.docsDir ?? null;\n const state = docsDir === null ? null : docsRepoState(docsDir);\n const exists = state !== null && state.kind !== \"missing\";\n const readable = exists && docsDir !== null ? await canAccess(docsDir, constants.R_OK) : false;\n const writable = exists && docsDir !== null ? await canAccess(docsDir, constants.W_OK) : false;\n const servicesDir = state?.kind === \"ok\";\n const landscapeFile = docsDir === null ? null : landscapePath(docsDir);\n const landscape = landscapeFile === null ? false : await canAccess(landscapeFile, constants.F_OK);\n\n // The docs-repo verdict comes from `docsRepoState`, the same function\n // `listServices` refuses on, so doctor cannot call a repo healthy that the\n // enumeration will not read.\n if (state?.kind === \"missing\") {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.docs-missing\",\n message: `Configured docsDir is missing or is not a directory: ${docsDir}`,\n fix: `Fix \"docsDir\" in ${path}, clone the docs repo to ${docsDir}, or run \\`loam init --docs <dir> --create\\`.`,\n });\n } else if (state?.kind === \"no-services\") {\n findings.push({\n severity: \"blocker\",\n code: \"doctor.services-missing\",\n message: `Required services/ directory is missing under ${docsDir} — that path is not a docs repo.`,\n fix: `Point \"docsDir\" in ${path} at the shared docs repo, or run \\`loam init --docs ${docsDir} --create\\`.`,\n });\n }\n\n // An absolute docsDir in a committed config names a directory that exists on\n // exactly one machine. It is a warning and not a blocker because it works\n // perfectly — for the person who ran `loam init`, and for nobody who clones\n // the repo afterwards.\n const asWritten = inspected.config?.docsDirAsWritten;\n const configRoot = inspected.config?.root;\n if (\n asWritten !== undefined\n && configRoot !== undefined\n && isAbsolute(asWritten)\n && resolve(asWritten) !== resolve(configRoot)\n ) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.docs-absolute\",\n message:\n `\"docsDir\" is stored as an absolute path (${asWritten}); ` +\n `${CONFIG_FILENAME} is committed, so it will not resolve on anyone else's machine.`,\n fix: `Rewrite \"docsDir\" in ${path} as a path relative to that file (e.g. \"../docs\").`,\n });\n }\n\n if (exists && !readable) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.docs-unreadable\",\n message: `docsDir is not readable by this process: ${docsDir}`,\n fix: `Grant read access to ${docsDir} (check ownership and mode).`,\n });\n }\n if (exists && !writable) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.docs-readonly\",\n message: `docsDir is not writable; read-only commands work, archive/init do not: ${docsDir}`,\n fix: `Grant write access to ${docsDir} if you need \\`loam new\\`, \\`loam adopt\\` or \\`loam archive\\`.`,\n });\n }\n if (exists && !landscape) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.landscape-missing\",\n message: `${landscapeFile} is missing — nothing cross-service can be checked without it.`,\n fix: \"Create architecture/landscape.likec4 with one element per service and an edge per call (`loam init --create` writes the empty map).\",\n });\n } else if (exists && landscapeFile !== null && readable) {\n await inspectLandscape(landscapeFile, findings);\n }\n\n // What a killed writer left behind. Read from `scanWritePathResidue`, whose\n // spellings of `.loam-lock` / `.loam-commit` / the temp-file pattern are\n // staging's own — doctor grades, it does not re-spell. This is the surface\n // that used to report `healthy: true` over half-merged docs.\n const writePath = docsDir !== null && exists && readable\n ? await scanWritePathResidue(docsDir)\n : null;\n if (docsDir !== null && writePath !== null) gradeWritePathResidue(docsDir, writePath, findings);\n\n let services: Awaited<ReturnType<typeof listServices>> = [];\n let activeFeatures: Awaited<ReturnType<typeof listFeatures>> = [];\n // Whether the fleet was actually READ, which is a narrower question than\n // whether reading it was attempted — hence set inside the try and not from\n // the guard, so an enumeration that threw leaves this false alongside its own\n // `doctor.inventory-unreadable`.\n let inventoried = false;\n if (docsDir !== null && readable && servicesDir) {\n try {\n [services, activeFeatures] = await Promise.all([\n listServices(docsDir),\n listFeatures(docsDir),\n ]);\n inventoried = true;\n } catch (error) {\n findings.push({\n severity: \"warning\",\n code: \"doctor.inventory-unreadable\",\n message: `Could not inventory the docs repo: ${error instanceof Error ? error.message : String(error)}`,\n fix: `Check that ${docsDir}/services and ${docsDir}/features are readable directories.`,\n });\n }\n }\n\n const configuredService = inspected.config?.service ?? null;\n const currentService: DoctorReport[\"currentService\"] = configuredService === null\n ? { configured: null, status: \"unbound\" }\n : services.some((service) => service.id === configuredService)\n ? { configured: configuredService, status: \"matched\" }\n : { configured: configuredService, status: \"unknown\" };\n if (currentService.status === \"unbound\") {\n findings.push({\n severity: \"warning\",\n code: \"doctor.service-unbound\",\n message: \"loam.json has no service binding; service-repo checks need `service`.\",\n fix: `Run \\`loam init --docs ${inspected.config?.docsDirAsWritten ?? \"<dir>\"} --service <id>\\` here.`,\n });\n } else if (currentService.status === \"unknown\" && inventoried) {\n // Only when there was an inventory to be absent from. This finding is a\n // claim about a fleet that was read; with no docsDir, an unreadable one, or\n // an enumeration that threw, `services` is empty for a reason that has\n // nothing to do with `service`, and doctor pointed the reader at the one\n // config field that was fine while the blocker it had already filed named\n // the real one. `currentService.status` still reports `unknown` — the\n // envelope describes what loam could and could not match, and an unread\n // fleet matches nothing.\n findings.push({\n severity: \"warning\",\n code: \"doctor.service-unknown\",\n message: `Configured service '${configuredService}' is not present under services/.`,\n // `--service <id>`, not a positional: `loam adopt` takes no argument, so\n // the spelling this finding used to print was refused by commander with\n // \"too many arguments\" — as the FIRST instruction a freshly bound service\n // repo ever receives. test/agent-commands-runnable.test.ts parses every\n // `loam …` loam prints against the real program so it cannot recur.\n fix: `Run \\`loam adopt --service ${configuredService}\\` to onboard it, or fix \"service\" in ${path}.`,\n });\n }\n\n // The slash commands (and everything else `init` lays down for a tool) belong\n // to the repo `init` ran in — the directory holding loam.json, which is not\n // the cwd now that config discovery walks upward.\n const agents = await inspectAgentSurface(dirname(path), inspected.config, docsDir, findings);\n\n return {\n healthy: !findings.some((finding) => finding.severity === \"blocker\"),\n runtime: {\n package: \"@ybotok/loam\",\n version: LOAM_VERSION,\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n },\n config: { path, status: inspected.status, error: inspected.error },\n docs: {\n path: docsDir,\n exists,\n readable,\n writable,\n servicesDir,\n landscape,\n },\n counts: { services: services.length, activeFeatures: activeFeatures.length },\n currentService,\n agents,\n writePath,\n findings,\n };\n}\n"]}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Decode the bytes of a document loam is about to parse, or refuse naming it.
3
+ *
4
+ * The rule belongs to every module that turns a markdown artifact into text —
5
+ * the frontmatter reader, the requirement parser, the fleet-wide read index and
6
+ * three commands that read a single file directly. It lived beside the read
7
+ * index, so each of those imported the whole index (and through it repo.ts,
8
+ * openapi.ts and spec.ts) to reach a dozen lines of decoding, and several of
9
+ * them closed an import cycle doing it. A leaf whose only dependency is
10
+ * `node:buffer` costs nothing to import and can be reached from anywhere.
11
+ */
12
+ import { isUtf8 } from "node:buffer";
13
+ /**
14
+ * A document loam was about to parse that is not UTF-8 text.
15
+ *
16
+ * Thrown rather than returned, and named as the file rather than as an empty
17
+ * document, because every parser in the codebase reads "no requirements, no
18
+ * frontmatter" as a legitimate state — a fresh baseline looks exactly like it.
19
+ * A `spec.md` saved as UTF-16 (PowerShell's `>` writes UTF-16LE by default)
20
+ * therefore validated green, with every requirement in it invisible.
21
+ *
22
+ * `path` is spelled the way Node spells it on an ErrnoException so that
23
+ * validate's per-target guard names the file without knowing this type; the
24
+ * write path makes the same two tests for the same reasons (staging.ts's
25
+ * `decodeUtf8`), and its messages differ only in saying what a rewrite would
26
+ * additionally destroy, which is not what a reader needs to hear.
27
+ */
28
+ export class NotUtf8DocumentError extends Error {
29
+ path;
30
+ name = "NotUtf8DocumentError";
31
+ constructor(path, reason) {
32
+ super(`${path} is not a UTF-8 text document — ${reason}. Read as UTF-8 its requirements, frontmatter and headings ` +
33
+ `all come out absent rather than wrong, so the file grades as an empty baseline instead of an unreadable one. ` +
34
+ `Nothing here was checked. Re-save it as UTF-8 (PowerShell's \`>\` and \`Out-File\` write UTF-16 unless told ` +
35
+ `otherwise: use \`Out-File -Encoding utf8\`), then re-run.`);
36
+ this.path = path;
37
+ }
38
+ }
39
+ /**
40
+ * Decode a document loam is about to parse, or refuse naming it.
41
+ *
42
+ * Two tests, because one is not enough. `isUtf8` catches the byte sequences
43
+ * that cannot be UTF-8 at all — which is what a byte-order mark makes UTF-16
44
+ * into, and PowerShell writes one. Without a BOM, UTF-16LE of ASCII is a
45
+ * sequence of valid UTF-8 bytes: every other byte is NUL, which decodes to
46
+ * U+0000 and nothing complains. That file parsed as zero requirements and no
47
+ * frontmatter, and validated green. A NUL in a markdown document loam owns has
48
+ * no legitimate spelling, so it is the second test.
49
+ */
50
+ export function decodeDocument(bytes, path) {
51
+ if (!isUtf8(bytes))
52
+ throw new NotUtf8DocumentError(path, "its bytes are not a valid UTF-8 sequence");
53
+ const text = bytes.toString("utf8");
54
+ if (text.includes("\u0000")) {
55
+ throw new NotUtf8DocumentError(path, "it holds NUL characters, which no markdown document does — almost always UTF-16 saved without a byte-order mark");
56
+ }
57
+ return text;
58
+ }
59
+ //# sourceMappingURL=document-bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-bytes.js","sourceRoot":"","sources":["../../src/core/document-bytes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAIlC,IAAI;IAHG,IAAI,GAAG,sBAAsB,CAAC;IAEhD,YACW,IAAY,EACrB,MAAc;QAEd,KAAK,CACH,GAAG,IAAI,mCAAmC,MAAM,6DAA6D;YAC3G,+GAA+G;YAC/G,8GAA8G;YAC9G,2DAA2D,CAC9D,CAAC;oBARO,IAAI;IASf,CAAC;CACF;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAAC,KAAa,EAAE,IAAY;IACxD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,oBAAoB,CAAC,IAAI,EAAE,0CAA0C,CAAC,CAAC;IACrG,MAAM,IAAI,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,oBAAoB,CAC5B,IAAI,EACJ,iHAAiH,CAClH,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Decode the bytes of a document loam is about to parse, or refuse naming it.\n *\n * The rule belongs to every module that turns a markdown artifact into text —\n * the frontmatter reader, the requirement parser, the fleet-wide read index and\n * three commands that read a single file directly. It lived beside the read\n * index, so each of those imported the whole index (and through it repo.ts,\n * openapi.ts and spec.ts) to reach a dozen lines of decoding, and several of\n * them closed an import cycle doing it. A leaf whose only dependency is\n * `node:buffer` costs nothing to import and can be reached from anywhere.\n */\nimport { isUtf8 } from \"node:buffer\";\n\n/**\n * A document loam was about to parse that is not UTF-8 text.\n *\n * Thrown rather than returned, and named as the file rather than as an empty\n * document, because every parser in the codebase reads \"no requirements, no\n * frontmatter\" as a legitimate state — a fresh baseline looks exactly like it.\n * A `spec.md` saved as UTF-16 (PowerShell's `>` writes UTF-16LE by default)\n * therefore validated green, with every requirement in it invisible.\n *\n * `path` is spelled the way Node spells it on an ErrnoException so that\n * validate's per-target guard names the file without knowing this type; the\n * write path makes the same two tests for the same reasons (staging.ts's\n * `decodeUtf8`), and its messages differ only in saying what a rewrite would\n * additionally destroy, which is not what a reader needs to hear.\n */\nexport class NotUtf8DocumentError extends Error {\n override readonly name = \"NotUtf8DocumentError\";\n\n constructor(\n readonly path: string,\n reason: string,\n ) {\n super(\n `${path} is not a UTF-8 text document — ${reason}. Read as UTF-8 its requirements, frontmatter and headings ` +\n `all come out absent rather than wrong, so the file grades as an empty baseline instead of an unreadable one. ` +\n `Nothing here was checked. Re-save it as UTF-8 (PowerShell's \\`>\\` and \\`Out-File\\` write UTF-16 unless told ` +\n `otherwise: use \\`Out-File -Encoding utf8\\`), then re-run.`,\n );\n }\n}\n\n/**\n * Decode a document loam is about to parse, or refuse naming it.\n *\n * Two tests, because one is not enough. `isUtf8` catches the byte sequences\n * that cannot be UTF-8 at all — which is what a byte-order mark makes UTF-16\n * into, and PowerShell writes one. Without a BOM, UTF-16LE of ASCII is a\n * sequence of valid UTF-8 bytes: every other byte is NUL, which decodes to\n * U+0000 and nothing complains. That file parsed as zero requirements and no\n * frontmatter, and validated green. A NUL in a markdown document loam owns has\n * no legitimate spelling, so it is the second test.\n */\nexport function decodeDocument(bytes: Buffer, path: string): string {\n if (!isUtf8(bytes)) throw new NotUtf8DocumentError(path, \"its bytes are not a valid UTF-8 sequence\");\n const text = bytes.toString(\"utf8\");\n if (text.includes(\"\\u0000\")) {\n throw new NotUtf8DocumentError(\n path,\n \"it holds NUL characters, which no markdown document does — almost always UTF-16 saved without a byte-order mark\",\n );\n }\n return text;\n}\n"]}
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The blast radius of a change nobody has written down yet.
3
+ *
4
+ * Everything else in loam answers a question about documents that exist. This
5
+ * module answers the one that comes BEFORE the first document: which services
6
+ * does this feature actually touch? On a fleet of a hundred that call is the
7
+ * hardest one in the cycle and the only one made with no tool in hand —
8
+ * `loam new FEAT-101 --touches a --touches b` takes the answer as an argument
9
+ * and scaffolds whatever it was told. A `--touches` list short by one service
10
+ * is not caught by anything: the feature validates, archives, and ships with a
11
+ * consumer nobody updated.
12
+ *
13
+ * So this states the work the same way `brief.ts` does. It reads the fleet map
14
+ * and the living contracts, reports the ring of services around the seeds, the
15
+ * features already in flight over the same ground, and how far each service's
16
+ * documentation has got — and stops. Which of those neighbours the feature
17
+ * really touches is a judgement about intent, and loam does not make those.
18
+ *
19
+ * The landscape is parsed ONCE for the whole exploration. Per-service reads of
20
+ * it exist (`brief.ts`'s `landscapeContext`) and are correct for one service;
21
+ * calling one of those per seed is how `validate --all` came to cost 13 seconds
22
+ * on 120 services, and this command sits in front of authoring, where that is
23
+ * the difference between a habit and a thing people skip.
24
+ */
25
+ import { existsSync } from "node:fs";
26
+ import { FleetContext } from "./fleet-context.js";
27
+ import { serviceResolver } from "./likec4.js";
28
+ import { maturityGaps, serviceMaturity, } from "./maturity.js";
29
+ import { compareIds, landscapePath, nearestIds, servicePaths, } from "./repo.js";
30
+ /**
31
+ * Read the fleet around a proposed change. Reads only; writes nothing, and
32
+ * refuses nothing — every miss is reported as a field.
33
+ */
34
+ export async function explore(req) {
35
+ const { docsDir, featureId } = req;
36
+ const context = req.context ?? new FleetContext();
37
+ const entries = await context.listServices(docsDir);
38
+ const byId = new Map(entries.map((e) => [e.id, e]));
39
+ const known = new Set(byId.keys());
40
+ const landPath = landscapePath(docsDir);
41
+ const present = existsSync(landPath);
42
+ const land = present ? await context.loadLikeC4(landPath) : null;
43
+ const parses = land !== null && land.errors.length === 0;
44
+ const elements = parses ? land.elements : [];
45
+ const relationships = parses ? land.relationships : [];
46
+ // One resolver for the whole scan, built with the real service ids so an edge
47
+ // drawn into a modelled container (`paymentService.api`) counts for the
48
+ // service that owns it — the same resolution `list`, `show` and `validate`
49
+ // use, so no two commands can disagree about who calls whom.
50
+ const svcOf = serviceResolver(elements, known);
51
+ // Operation seeds resolve through the living contracts, not the map: the map
52
+ // says who CALLS an operation, and the question here is who DEFINES it.
53
+ const opSeeds = [];
54
+ const unresolvedOperations = [];
55
+ for (const op of req.operations) {
56
+ const owner = await operationOwner(docsDir, entries, op, context);
57
+ if (owner === null)
58
+ unresolvedOperations.push(op);
59
+ else
60
+ opSeeds.push(owner);
61
+ }
62
+ const seeds = [...new Set([...req.services, ...opSeeds])];
63
+ const unknown = seeds
64
+ .filter((id) => !known.has(id))
65
+ .map((id) => ({ id, nearest: nearestIds(id, [...known]) }));
66
+ // The ring: one hop, both directions. A seed that is not modelled contributes
67
+ // nothing here and that is the honest answer — an invisible service has no
68
+ // neighbours anyone can derive, which is what `landscape.service-unmodelled`
69
+ // is about.
70
+ //
71
+ // The two directions are collected separately rather than written into one
72
+ // map as the loop goes, because a neighbour can be BOTH — it calls a seed and
73
+ // the seed calls it — and a single-map version answers whichever edge the
74
+ // parser happened to yield last. That is a field whose value depends on the
75
+ // order lines appear in a `.likec4` file, which is the kind of answer that
76
+ // reads as derived and is not.
77
+ const seedSet = new Set(seeds);
78
+ const callsSeed = new Set();
79
+ const calledBySeed = new Set();
80
+ for (const r of relationships) {
81
+ const from = svcOf(r.source);
82
+ const to = svcOf(r.target);
83
+ if (seedSet.has(from) && !seedSet.has(to))
84
+ calledBySeed.add(to);
85
+ if (seedSet.has(to) && !seedSet.has(from))
86
+ callsSeed.add(from);
87
+ }
88
+ // `calls-seed` wins the overlap, deterministically. Of the two directions it
89
+ // is the one that more often has to be touched: a consumer depends on the
90
+ // seed's contract, so a change to that contract is what breaks it, while a
91
+ // provider the seed merely calls is usually unaffected by the seed changing.
92
+ const ring = new Map([
93
+ ...[...calledBySeed].map((id) => [id, "called-by-seed"]),
94
+ ...[...callsSeed].map((id) => [id, "calls-seed"]),
95
+ ]);
96
+ const ordered = [
97
+ ...[...seeds].sort(compareIds).map((id) => ({ id, reason: "seed" })),
98
+ ...[...ring]
99
+ .sort(([a], [b]) => compareIds(a, b))
100
+ .map(([id, reason]) => ({ id, reason })),
101
+ ];
102
+ const services = [];
103
+ for (const { id, reason } of ordered) {
104
+ services.push(await describe({
105
+ id,
106
+ reason,
107
+ entry: byId.get(id),
108
+ docsDir,
109
+ relationships,
110
+ svcOf,
111
+ elements,
112
+ parses,
113
+ context,
114
+ }));
115
+ }
116
+ const covered = new Set(services.map((s) => s.id));
117
+ const features = await context.listFeatures(docsDir);
118
+ const overlaps = features
119
+ .map((f) => ({ feature: f.id, services: f.services.filter((s) => covered.has(s)) }))
120
+ .filter((o) => o.services.length > 0)
121
+ .sort((a, b) => compareIds(a.feature, b.feature));
122
+ return {
123
+ seeds,
124
+ unknown,
125
+ unresolvedOperations,
126
+ services,
127
+ neighbours: [...ring.keys()].sort(compareIds),
128
+ overlaps,
129
+ landscape: { present, parses },
130
+ scaffold: newCommand(featureId, seeds, known),
131
+ };
132
+ }
133
+ async function describe(req) {
134
+ const { id, reason, entry, docsDir, relationships, svcOf } = req;
135
+ const inbound = [];
136
+ const outbound = [];
137
+ for (const r of relationships) {
138
+ const edge = { op: r.op ?? null, title: r.title ?? null };
139
+ if (svcOf(r.target) === id)
140
+ inbound.push({ service: svcOf(r.source), ...edge });
141
+ else if (svcOf(r.source) === id)
142
+ outbound.push({ service: svcOf(r.target), ...edge });
143
+ }
144
+ const modelled = req.elements.some((e) => svcOf(e.id) === id);
145
+ // A service that does not exist has no rung: `empty` would be a claim about a
146
+ // directory nobody has made, and it reads as "exists, nothing in it" — the
147
+ // one state a caller most needs to tell it apart from.
148
+ if (entry === undefined) {
149
+ return {
150
+ id,
151
+ reason,
152
+ known: false,
153
+ maturity: null,
154
+ missing: [],
155
+ modelled,
156
+ operations: [],
157
+ // Not `unreadable`: there is no contract here to fail to read. A service
158
+ // with no directory owes nothing, and reporting a parse failure over an
159
+ // absent file would send a reader looking for a document to fix.
160
+ openapi: { unreadable: false },
161
+ inbound,
162
+ outbound,
163
+ };
164
+ }
165
+ const archSpec = existsSync(servicePaths(docsDir, id).archSpec);
166
+ // Positive evidence only, and the rule is `list`'s verbatim: an inbound edge
167
+ // carrying an operation is proof somebody calls this service, while a
168
+ // landscape that is absent or does not parse proves nothing about who calls
169
+ // it — so the contract is still owed. Spelling this differently here is how
170
+ // the same service would grade `partial` in one command and `vouched` in the
171
+ // other.
172
+ const apiExpected = !req.parses || inbound.some((e) => e.op !== null);
173
+ const input = { entry, archSpec, apiExpected };
174
+ // `readOpenapi`, not `operationIds`: a contract that exists but does not
175
+ // parse comes back from the id list as an EMPTY set, indistinguishable from a
176
+ // service with no endpoints — and "this service offers nothing" is the worst
177
+ // possible lie to tell somebody deciding whether to call it.
178
+ const api = await req.context.readOpenapi(servicePaths(docsDir, id).openapi);
179
+ const operations = api.ops.filter((o) => !o.remove).map((o) => o.id);
180
+ return {
181
+ id,
182
+ reason,
183
+ known: true,
184
+ maturity: serviceMaturity(input),
185
+ missing: maturityGaps(input),
186
+ modelled,
187
+ operations,
188
+ openapi: {
189
+ unreadable: api.unreadable,
190
+ ...(api.error === undefined ? {} : { error: api.error }),
191
+ },
192
+ inbound,
193
+ outbound,
194
+ };
195
+ }
196
+ /**
197
+ * The service whose living contract defines an operationId, or null.
198
+ *
199
+ * Reads every service's `openapi.yaml`, which is the cost of asking a question
200
+ * nothing indexes. It is YAML, not LikeC4 — the expensive parse in this
201
+ * codebase — and it happens only when somebody passes `--op`.
202
+ */
203
+ async function operationOwner(docsDir, entries, op, context) {
204
+ for (const entry of entries) {
205
+ if (!entry.has.openapi)
206
+ continue;
207
+ const api = await context.readOpenapi(servicePaths(docsDir, entry.id).openapi);
208
+ if (api.ops.some((o) => o.id === op && !o.remove))
209
+ return entry.id;
210
+ }
211
+ return null;
212
+ }
213
+ /**
214
+ * The `loam new` line the seeds imply. A seed that names no existing service is
215
+ * `--new-service`, not `--touches`: those are different scaffolds, and getting
216
+ * it wrong is what leaves a feature with a requirement delta for a service that
217
+ * has no directory to archive into.
218
+ */
219
+ function newCommand(featureId, seeds, known) {
220
+ const flags = [...seeds]
221
+ .sort(compareIds)
222
+ .map((id) => (known.has(id) ? `--touches ${id}` : `--new-service ${id}`));
223
+ return `loam new ${featureId}${flags.length > 0 ? ` ${flags.join(" ")}` : ""}`;
224
+ }
225
+ //# sourceMappingURL=explore.js.map
@@ -0,0 +1 @@
1
+ {"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CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5E,OAAO,YAAY,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The blast radius of a change nobody has written down yet.\n *\n * Everything else in loam answers a question about documents that exist. This\n * module answers the one that comes BEFORE the first document: which services\n * does this feature actually touch? On a fleet of a hundred that call is the\n * hardest one in the cycle and the only one made with no tool in hand —\n * `loam new FEAT-101 --touches a --touches b` takes the answer as an argument\n * and scaffolds whatever it was told. A `--touches` list short by one service\n * is not caught by anything: the feature validates, archives, and ships with a\n * consumer nobody updated.\n *\n * So this states the work the same way `brief.ts` does. It reads the fleet map\n * and the living contracts, reports the ring of services around the seeds, the\n * features already in flight over the same ground, and how far each service's\n * documentation has got — and stops. Which of those neighbours the feature\n * really touches is a judgement about intent, and loam does not make those.\n *\n * The landscape is parsed ONCE for the whole exploration. Per-service reads of\n * it exist (`brief.ts`'s `landscapeContext`) and are correct for one service;\n * calling one of those per seed is how `validate --all` came to cost 13 seconds\n * on 120 services, and this command sits in front of authoring, where that is\n * the difference between a habit and a thing people skip.\n */\nimport { existsSync } from \"node:fs\";\nimport { FleetContext } from \"./fleet-context.js\";\nimport { serviceResolver, type Elem, type Rel } from \"./likec4.js\";\nimport {\n maturityGaps,\n serviceMaturity,\n type Maturity,\n} from \"./maturity.js\";\nimport {\n compareIds,\n landscapePath,\n nearestIds,\n servicePaths,\n type ServiceEntry,\n} from \"./repo.js\";\n\n/** One end of a call the fleet map already draws. */\nexport interface ExploreEdge {\n /** The service at the other end. */\n service: string;\n /** The operationId the call uses, or null for an edge nobody tied to one. */\n op: string | null;\n title: string | null;\n}\n\n/**\n * Why a service is in the answer. Seeds were asked for; the rest were derived.\n *\n * A neighbour on both sides of a seed reports `calls-seed` — see the overlap\n * rule in `explore`. The field is a hint about where to look, not a complete\n * description of the edges; `inbound`/`outbound` are that.\n */\nexport type ExploreReason = \"seed\" | \"calls-seed\" | \"called-by-seed\";\n\nexport interface ExploreService {\n id: string;\n reason: ExploreReason;\n /** Whether `services/<id>/` exists at all. */\n known: boolean;\n /**\n * How far this service's documentation has got, or null when it does not\n * exist yet. A `--touches` naming a service at `empty` or `partial` is a\n * different job from one naming a vouched service, and the difference decides\n * whether the feature starts with `loam adopt`.\n */\n maturity: Maturity | null;\n /** What stands between it and `vouched` — `maturityGaps`, so it matches `list --needs-work`. */\n missing: string[];\n /** Whether anything in the fleet map resolves to it. */\n modelled: boolean;\n /** operationIds its living contract exposes today, `x-loam-remove` markers excluded. */\n operations: string[];\n /**\n * Whether that contract could be read at all, beside the `error` the parser\n * gave when it could not.\n *\n * It rides next to `operations` rather than inside it for the reason `delta`\n * carries the same pair: an unreadable contract yields an EMPTY operation\n * list, indistinguishable from a service with no endpoints — and this is the\n * field the workflow tells an agent to read before deciding whether an\n * operation it is about to add already exists. Answering `[]` over a YAML\n * error is how a MODIFIED requirement gets authored as ADDED.\n */\n openapi: { unreadable: boolean; error?: string };\n inbound: ExploreEdge[];\n outbound: ExploreEdge[];\n}\n\n/** An active feature already working over ground the exploration covers. */\nexport interface ExploreOverlap {\n feature: string;\n /** The explored services it already carries a delta for. */\n services: string[];\n}\n\nexport interface Exploration {\n /** The seed ids, as asked for. */\n seeds: string[];\n /**\n * Seeds that name no `services/<id>/`, each with the closest real ids. A seed\n * may legitimately be a service the feature INTRODUCES, so this is reported\n * rather than refused — but a typo produces exactly the same shape, and the\n * near-miss list is what tells the two apart.\n */\n unknown: Array<{ id: string; nearest: string[] }>;\n /** Operation seeds that resolved to no service's living contract. */\n unresolvedOperations: string[];\n /** Seeds first, then the ring, each in id order. */\n services: ExploreService[];\n /** Ids the ring added that were not asked for — the candidates to weigh. */\n neighbours: string[];\n overlaps: ExploreOverlap[];\n landscape: { present: boolean; parses: boolean };\n /**\n * The literal `loam new` line the seeds imply — seeds only. The ring is\n * deliberately NOT folded in: this module's whole claim is that it does not\n * know which neighbours the feature touches, and a command line that quietly\n * included them would make the guess on the reader's behalf and look derived\n * while doing it.\n *\n * Named for what it does rather than `command`, which is the envelope's key\n * for the command that RAN. The rename is not cosmetic: `emitJson` spreads\n * the payload LAST, so a payload field called `command` would silently\n * OVERRIDE the envelope's — `command` would come back as\n * `\"loam new FEAT-000 …\"`, and every consumer branching on\n * `command === \"explore\"` (the same key `status`, `doctor`, `dependencies`,\n * `archive` and `unarchive` emit) would quietly stop matching, with tsc and\n * the linter green throughout.\n */\n scaffold: string;\n}\n\nexport interface ExploreRequest {\n docsDir: string;\n /** Service ids to explore around. */\n services: string[];\n /** operationIds to explore around; each resolves to the service that defines it. */\n operations: string[];\n /** Placeholder feature id for the suggested command line. */\n featureId: string;\n context?: FleetContext;\n}\n\n/**\n * Read the fleet around a proposed change. Reads only; writes nothing, and\n * refuses nothing — every miss is reported as a field.\n */\nexport async function explore(req: ExploreRequest): Promise<Exploration> {\n const { docsDir, featureId } = req;\n const context = req.context ?? new FleetContext();\n const entries = await context.listServices(docsDir);\n const byId = new Map(entries.map((e) => [e.id, e]));\n const known = new Set(byId.keys());\n\n const landPath = landscapePath(docsDir);\n const present = existsSync(landPath);\n const land = present ? await context.loadLikeC4(landPath) : null;\n const parses = land !== null && land.errors.length === 0;\n const elements = parses ? land.elements : [];\n const relationships: Rel[] = parses ? land.relationships : [];\n // One resolver for the whole scan, built with the real service ids so an edge\n // drawn into a modelled container (`paymentService.api`) counts for the\n // service that owns it — the same resolution `list`, `show` and `validate`\n // use, so no two commands can disagree about who calls whom.\n const svcOf = serviceResolver(elements, known);\n\n // Operation seeds resolve through the living contracts, not the map: the map\n // says who CALLS an operation, and the question here is who DEFINES it.\n const opSeeds: string[] = [];\n const unresolvedOperations: string[] = [];\n for (const op of req.operations) {\n const owner = await operationOwner(docsDir, entries, op, context);\n if (owner === null) unresolvedOperations.push(op);\n else opSeeds.push(owner);\n }\n\n const seeds = [...new Set([...req.services, ...opSeeds])];\n const unknown = seeds\n .filter((id) => !known.has(id))\n .map((id) => ({ id, nearest: nearestIds(id, [...known]) }));\n\n // The ring: one hop, both directions. A seed that is not modelled contributes\n // nothing here and that is the honest answer — an invisible service has no\n // neighbours anyone can derive, which is what `landscape.service-unmodelled`\n // is about.\n //\n // The two directions are collected separately rather than written into one\n // map as the loop goes, because a neighbour can be BOTH — it calls a seed and\n // the seed calls it — and a single-map version answers whichever edge the\n // parser happened to yield last. That is a field whose value depends on the\n // order lines appear in a `.likec4` file, which is the kind of answer that\n // reads as derived and is not.\n const seedSet = new Set(seeds);\n const callsSeed = new Set<string>();\n const calledBySeed = new Set<string>();\n for (const r of relationships) {\n const from = svcOf(r.source);\n const to = svcOf(r.target);\n if (seedSet.has(from) && !seedSet.has(to)) calledBySeed.add(to);\n if (seedSet.has(to) && !seedSet.has(from)) callsSeed.add(from);\n }\n\n // `calls-seed` wins the overlap, deterministically. Of the two directions it\n // is the one that more often has to be touched: a consumer depends on the\n // seed's contract, so a change to that contract is what breaks it, while a\n // provider the seed merely calls is usually unaffected by the seed changing.\n const ring = new Map<string, ExploreReason>([\n ...[...calledBySeed].map((id) => [id, \"called-by-seed\" as const] as const),\n ...[...callsSeed].map((id) => [id, \"calls-seed\" as const] as const),\n ]);\n\n const ordered: Array<{ id: string; reason: ExploreReason }> = [\n ...[...seeds].sort(compareIds).map((id) => ({ id, reason: \"seed\" as const })),\n ...[...ring]\n .sort(([a], [b]) => compareIds(a, b))\n .map(([id, reason]) => ({ id, reason })),\n ];\n\n const services: ExploreService[] = [];\n for (const { id, reason } of ordered) {\n services.push(\n await describe({\n id,\n reason,\n entry: byId.get(id),\n docsDir,\n relationships,\n svcOf,\n elements,\n parses,\n context,\n }),\n );\n }\n\n const covered = new Set(services.map((s) => s.id));\n const features = await context.listFeatures(docsDir);\n const overlaps: ExploreOverlap[] = features\n .map((f) => ({ feature: f.id, services: f.services.filter((s) => covered.has(s)) }))\n .filter((o) => o.services.length > 0)\n .sort((a, b) => compareIds(a.feature, b.feature));\n\n return {\n seeds,\n unknown,\n unresolvedOperations,\n services,\n neighbours: [...ring.keys()].sort(compareIds),\n overlaps,\n landscape: { present, parses },\n scaffold: newCommand(featureId, seeds, known),\n };\n}\n\n/* ------------------------------------------------------------------ */\n\ninterface DescribeRequest {\n id: string;\n reason: ExploreReason;\n entry: ServiceEntry | undefined;\n docsDir: string;\n relationships: Rel[];\n svcOf: (id: string) => string;\n elements: Elem[];\n /** Whether the landscape parsed — what makes its silence evidence rather than absence. */\n parses: boolean;\n context: FleetContext;\n}\n\nasync function describe(req: DescribeRequest): Promise<ExploreService> {\n const { id, reason, entry, docsDir, relationships, svcOf } = req;\n\n const inbound: ExploreEdge[] = [];\n const outbound: ExploreEdge[] = [];\n for (const r of relationships) {\n const edge = { op: r.op ?? null, title: r.title ?? null };\n if (svcOf(r.target) === id) inbound.push({ service: svcOf(r.source), ...edge });\n else if (svcOf(r.source) === id) outbound.push({ service: svcOf(r.target), ...edge });\n }\n const modelled = req.elements.some((e) => svcOf(e.id) === id);\n\n // A service that does not exist has no rung: `empty` would be a claim about a\n // directory nobody has made, and it reads as \"exists, nothing in it\" — the\n // one state a caller most needs to tell it apart from.\n if (entry === undefined) {\n return {\n id,\n reason,\n known: false,\n maturity: null,\n missing: [],\n modelled,\n operations: [],\n // Not `unreadable`: there is no contract here to fail to read. A service\n // with no directory owes nothing, and reporting a parse failure over an\n // absent file would send a reader looking for a document to fix.\n openapi: { unreadable: false },\n inbound,\n outbound,\n };\n }\n\n const archSpec = existsSync(servicePaths(docsDir, id).archSpec);\n // Positive evidence only, and the rule is `list`'s verbatim: an inbound edge\n // carrying an operation is proof somebody calls this service, while a\n // landscape that is absent or does not parse proves nothing about who calls\n // it — so the contract is still owed. Spelling this differently here is how\n // the same service would grade `partial` in one command and `vouched` in the\n // other.\n const apiExpected = !req.parses || inbound.some((e) => e.op !== null);\n const input = { entry, archSpec, apiExpected };\n\n // `readOpenapi`, not `operationIds`: a contract that exists but does not\n // parse comes back from the id list as an EMPTY set, indistinguishable from a\n // service with no endpoints — and \"this service offers nothing\" is the worst\n // possible lie to tell somebody deciding whether to call it.\n const api = await req.context.readOpenapi(servicePaths(docsDir, id).openapi);\n const operations = api.ops.filter((o) => !o.remove).map((o) => o.id);\n\n return {\n id,\n reason,\n known: true,\n maturity: serviceMaturity(input),\n missing: maturityGaps(input),\n modelled,\n operations,\n openapi: {\n unreadable: api.unreadable,\n ...(api.error === undefined ? {} : { error: api.error }),\n },\n inbound,\n outbound,\n };\n}\n\n/**\n * The service whose living contract defines an operationId, or null.\n *\n * Reads every service's `openapi.yaml`, which is the cost of asking a question\n * nothing indexes. It is YAML, not LikeC4 — the expensive parse in this\n * codebase — and it happens only when somebody passes `--op`.\n */\nasync function operationOwner(\n docsDir: string,\n entries: ServiceEntry[],\n op: string,\n context: FleetContext,\n): Promise<string | null> {\n for (const entry of entries) {\n if (!entry.has.openapi) continue;\n const api = await context.readOpenapi(servicePaths(docsDir, entry.id).openapi);\n if (api.ops.some((o) => o.id === op && !o.remove)) return entry.id;\n }\n return null;\n}\n\n/**\n * The `loam new` line the seeds imply. A seed that names no existing service is\n * `--new-service`, not `--touches`: those are different scaffolds, and getting\n * it wrong is what leaves a feature with a requirement delta for a service that\n * has no directory to archive into.\n */\nfunction newCommand(featureId: string, seeds: string[], known: ReadonlySet<string>): string {\n const flags = [...seeds]\n .sort(compareIds)\n .map((id) => (known.has(id) ? `--touches ${id}` : `--new-service ${id}`));\n return `loam new ${featureId}${flags.length > 0 ? ` ${flags.join(\" \")}` : \"\"}`;\n}\n"]}