Skip to content

DataArt/artisyn-implementation-harness / skills/implementation-harness

implementation-harness

Flagged

Install the portable AI-dev harness, rebuild its operational graph standalone, harvest project skill improvements into its canonical templates, package direct canonical edits into a portable bundle, or apply canonical updates to an existing project. Use /implementation-harness launch, /implementation-harness reindex-graph, or /implementation-harness patch harvest|prepare|apply.

FileKindSize
CHANGELOG.mdmarkdown37.5 KB
README.mdmarkdown13.7 KB
SKILL.mdskill md9.6 KB
bin/artisyn-implementation-harness.mjsexecutablescript11.8 KB
bin/lib/placer.mjsscript2.6 KB
bin/lib/providers.mjsscript1.8 KB
bin/lib/reporter.mjsscript3.0 KB
bin/lib/zip.mjsscript4.0 KB
canonical/adaptors/claude/browser.mdmarkdown2.5 KB
canonical/adaptors/claude/context.mdmarkdown517 B
canonical/adaptors/claude/credentials.mdmarkdown512 B
canonical/adaptors/claude/delegation.mdmarkdown910 B
canonical/adaptors/claude/interaction.mdmarkdown359 B
canonical/adaptors/claude/planning.mdmarkdown745 B
canonical/adaptors/claude/review.mdmarkdown1.0 KB
canonical/adaptors/claude/task-tracking.mdmarkdown897 B
canonical/adaptors/codex/browser.mdmarkdown1.0 KB
canonical/adaptors/codex/context.mdmarkdown517 B
canonical/adaptors/codex/credentials.mdmarkdown480 B
canonical/adaptors/codex/delegation.mdmarkdown910 B
canonical/adaptors/codex/interaction.mdmarkdown359 B
canonical/adaptors/codex/planning.mdmarkdown904 B
canonical/adaptors/codex/review.mdmarkdown973 B
canonical/adaptors/codex/task-tracking.mdmarkdown1.1 KB
canonical/adaptors/copilot/browser.mdmarkdown620 B
canonical/adaptors/copilot/context.mdmarkdown881 B
canonical/adaptors/copilot/credentials.mdmarkdown992 B
canonical/adaptors/copilot/delegation.mdmarkdown1.2 KB
canonical/adaptors/copilot/interaction.mdmarkdown454 B
canonical/adaptors/copilot/planning.mdmarkdown785 B
canonical/adaptors/copilot/review.mdmarkdown791 B
canonical/adaptors/copilot/task-tracking.mdmarkdown723 B
canonical/agents/architect/INTENT.mdmarkdown2.4 KB
canonical/agents/architect/TEMPLATE.mdmarkdown6.5 KB
canonical/agents/docs-writer/INTENT.mdmarkdown2.2 KB
canonical/agents/docs-writer/TEMPLATE.mdmarkdown2.8 KB
canonical/agents/infra/INTENT.mdmarkdown2.1 KB
canonical/agents/infra/TEMPLATE.mdmarkdown5.1 KB
canonical/agents/layer/INTENT.mdmarkdown6.0 KB
canonical/agents/layer/TEMPLATE.mdmarkdown1.5 KB
canonical/agents/onboarding/INTENT.mdmarkdown5.3 KB
canonical/agents/onboarding/TEMPLATE.mdmarkdown4.2 KB
canonical/agents/product-architect/INTENT.mdmarkdown7.5 KB
canonical/agents/product-architect/TEMPLATE.mdmarkdown3.9 KB
canonical/agents/scrum-master/INTENT.mdmarkdown10.9 KB
canonical/agents/scrum-master/TEMPLATE.mdmarkdown12.3 KB
canonical/docs/.og/cli.mjsscript13.6 KB
canonical/docs/.og/cli.test.mjsscript19.6 KB
canonical/docs/.og/constants.mjsscript2.9 KB
canonical/docs/.og/docs-operational-graph.sqlitebinary24.0 KB
canonical/docs/.og/docs.mjsscript5.5 KB
canonical/docs/.og/edges.mjsscript5.8 KB
canonical/docs/.og/schema.mjsscript741 B
canonical/docs/.og/utils.mjsscript5.2 KB
canonical/docs/Engineering Guide/01 Conventions.mdmarkdown3.0 KB
canonical/docs/Engineering Guide/03 Engineer Role.mdmarkdown2.6 KB
canonical/docs/Engineering Guide/04 AI Coding Tool Compatibility.mdmarkdown3.6 KB
canonical/docs/Engineering Guide/05 MCP Setup.mdmarkdown6.6 KB
canonical/docs/Engineering Guide/Documentation/01 Principles.mdmarkdown15.3 KB
canonical/docs/Engineering Guide/Documentation/02 Structure.mdmarkdown3.8 KB
canonical/docs/Engineering Guide/Documentation/03 HLD Intent.mdmarkdown8.1 KB
canonical/docs/Engineering Guide/Documentation/04 LLD Intent.mdmarkdown9.7 KB
canonical/docs/Engineering Guide/Documentation/05 NFR Intent.mdmarkdown6.0 KB
canonical/docs/Engineering Guide/Documentation/07 Terminology.mdmarkdown1.4 KB
canonical/docs/Engineering Guide/Lifecycles/00 Overview.mdmarkdown5.8 KB
canonical/docs/Engineering Guide/Lifecycles/01 Dev Lifecycle.mdmarkdown19.9 KB
canonical/docs/Engineering Guide/Lifecycles/02 Design Lifecycle.mdmarkdown29.4 KB
canonical/docs/Engineering Guide/Lifecycles/03 Evolve Lifecycle.mdmarkdown7.0 KB
canonical/docs/Engineering Guide/Lifecycles/04 Architecture Lifecycle.mdmarkdown3.6 KB
canonical/docs/Engineering Guide/Lifecycles/05 Documents Flow.mdmarkdown9.5 KB
canonical/manifest.jsonconfig1.6 KB
canonical/mcp.jsonconfig23 B
canonical/root-instructions/INTERFACE.mdmarkdown3.3 KB
canonical/settings.jsonconfig332 B
canonical/skills/design/INTENT.mdmarkdown28.6 KB
canonical/skills/design/TEMPLATE.mdmarkdown19.0 KB
canonical/skills/design/interfaces/architecture.mdmarkdown2.8 KB
canonical/skills/design/interfaces/contract.mdmarkdown7.4 KB
canonical/skills/design/interfaces/design.mdmarkdown2.3 KB
canonical/skills/design/interfaces/efforts.mdmarkdown2.5 KB
canonical/skills/design/interfaces/stack.mdmarkdown1.6 KB
canonical/skills/design/patterns/announce-progress.mdmarkdown997 B
canonical/skills/design/patterns/approval-intelligent.mdmarkdown1.5 KB
canonical/skills/design/patterns/approval-sign-off.mdmarkdown2.4 KB
canonical/skills/design/patterns/context-resolution.mdmarkdown6.6 KB
canonical/skills/design/patterns/design-architect-review.mdmarkdown2.4 KB
canonical/skills/design/patterns/design-oq-triage.mdmarkdown3.8 KB
canonical/skills/design/patterns/design-quality-gate.mdmarkdown1.4 KB
canonical/skills/design/patterns/do-report-commit.mdmarkdown1.2 KB
canonical/skills/design/patterns/docs-writer-authoring.mdmarkdown3.6 KB
canonical/skills/design/patterns/metrics.mdmarkdown11.9 KB
canonical/skills/design/patterns/multi-decision-split.mdmarkdown3.6 KB
canonical/skills/design/patterns/phase-sign-off.mdmarkdown2.4 KB
canonical/skills/design/patterns/satellite-review.mdmarkdown1.5 KB
canonical/skills/design/patterns/session-continuity.mdmarkdown827 B
canonical/skills/design/patterns/task-tracking.mdmarkdown779 B
canonical/skills/design/patterns/waf-review.mdmarkdown4.2 KB
canonical/skills/design/patterns/write-confirm.mdmarkdown963 B
canonical/skills/design/references/00-decision-router.mdmarkdown3.8 KB
canonical/skills/design/references/00-router.mdmarkdown4.6 KB
canonical/skills/design/references/01-context-gathering.mdmarkdown8.1 KB
canonical/skills/design/references/02-ceremony.mdmarkdown4.6 KB
canonical/skills/design/references/03-frame.mdmarkdown6.7 KB
canonical/skills/design/references/04-research.mdmarkdown8.1 KB
canonical/skills/design/references/05-evaluate.mdmarkdown9.0 KB
canonical/skills/design/references/06-solution.mdmarkdown13.7 KB
canonical/skills/design/references/07-review-gate.mdmarkdown4.1 KB
canonical/skills/design/references/08-address-feedback.mdmarkdown8.0 KB
canonical/skills/design/references/09-publish.mdmarkdown8.9 KB
canonical/skills/design/references/10-completion.mdmarkdown7.4 KB
canonical/skills/design/scripts/constants.mjsscript2.0 KB
canonical/skills/design/scripts/design-metrics.mjsscript35.4 KB
canonical/skills/design/scripts/design-metrics.test.mjsscript12.0 KB
canonical/skills/design/scripts/utils.mjsscript3.1 KB
canonical/skills/design/templates/evaluate.mdmarkdown1.4 KB
canonical/skills/design/templates/frame.mdmarkdown2.6 KB
canonical/skills/design/templates/report.mdmarkdown4.8 KB
canonical/skills/design/templates/research.mdmarkdown2.4 KB
canonical/skills/design/templates/stat.jsonconfig1.7 KB
canonical/skills/design/templates/stat.schema.jsonconfig17.1 KB
canonical/skills/dev/INTENT.mdmarkdown15.9 KB
canonical/skills/dev/TEMPLATE.mdmarkdown9.0 KB
canonical/skills/dev/interfaces/intent.mdmarkdown2.6 KB
canonical/skills/dev/patterns/announce-progress.mdmarkdown1.1 KB
canonical/skills/dev/patterns/approval-intelligent.mdmarkdown1.5 KB
canonical/skills/dev/patterns/approval-sign-off.mdmarkdown1.9 KB
canonical/skills/dev/patterns/do-report-commit.mdmarkdown888 B
canonical/skills/dev/patterns/metrics.mdmarkdown17.7 KB
canonical/skills/dev/patterns/phase-sign-off.mdmarkdown2.2 KB
canonical/skills/dev/patterns/review-gate.mdmarkdown3.6 KB
canonical/skills/dev/patterns/satellite-review.mdmarkdown3.1 KB
canonical/skills/dev/patterns/session-continuity.mdmarkdown797 B
canonical/skills/dev/patterns/task-tracking.mdmarkdown766 B
canonical/skills/dev/patterns/write-confirm.mdmarkdown615 B
canonical/skills/dev/references/00-router.mdmarkdown2.2 KB
canonical/skills/dev/references/01-context-gathering.mdmarkdown10.3 KB
canonical/skills/dev/references/02-ceremony.mdmarkdown4.5 KB
canonical/skills/dev/references/03-plan.mdmarkdown14.2 KB
canonical/skills/dev/references/04-implement.mdmarkdown11.7 KB
canonical/skills/dev/references/05-test.mdmarkdown7.8 KB
canonical/skills/dev/references/06-document.mdmarkdown11.7 KB
canonical/skills/dev/references/07-completion.mdmarkdown6.3 KB
canonical/skills/dev/scripts/constants.mjsscript3.2 KB
canonical/skills/dev/scripts/quality.mjsscript9.1 KB
canonical/skills/dev/scripts/quality.test.mjsscript6.6 KB
canonical/skills/dev/scripts/timing.mjsscript38.1 KB
canonical/skills/dev/scripts/timing.test.mjsscript21.0 KB
canonical/skills/dev/scripts/utils.mjsscript3.1 KB
canonical/skills/dev/templates/plan.mdmarkdown3.3 KB
canonical/skills/dev/templates/report.mdmarkdown6.4 KB
canonical/skills/dev/templates/stat.jsonconfig1.4 KB
canonical/skills/dev/templates/stat.schema.jsonconfig29.3 KB
canonical/skills/evolve/INTENT.mdmarkdown1.6 KB
canonical/skills/evolve/TEMPLATE.mdmarkdown1.3 KB
canonical/skills/evolve/interfaces/improvement.mdmarkdown1.2 KB
canonical/skills/evolve/interfaces/reflection.mdmarkdown353 B
canonical/skills/evolve/interfaces/validation.mdmarkdown653 B
canonical/skills/evolve/patterns/task-tracking.mdmarkdown787 B
canonical/skills/evolve/references/00-router.mdmarkdown1.1 KB
canonical/skills/evolve/references/01-reflect.mdmarkdown805 B
canonical/skills/evolve/references/02-triage.mdmarkdown2.6 KB
canonical/skills/evolve/references/03-draft.mdmarkdown1.2 KB
canonical/skills/evolve/references/04-validate.mdmarkdown1.5 KB
canonical/skills/evolve/references/05-adopt.mdmarkdown1.5 KB
canonical/skills/war/INTENT.mdmarkdown4.5 KB
canonical/skills/war/TEMPLATE.mdmarkdown1.8 KB
canonical/skills/war/patterns/present-and-save.mdmarkdown1.0 KB
canonical/skills/war/patterns/scope-resolution.mdmarkdown830 B
canonical/skills/war/references/01-design.mdmarkdown3.4 KB
canonical/skills/war/references/02-implementation.mdmarkdown3.8 KB
canonical/skills/war/templates/design-report.mdmarkdown869 B
canonical/skills/war/templates/implementation-report.mdmarkdown1.8 KB
canonical/skills/where-we-are/INTENT.mdmarkdown3.3 KB
canonical/skills/where-we-are/TEMPLATE.mdmarkdown6.3 KB
canonical/skills/where-we-are/report-template.mdmarkdown2.0 KB
canonical/skills/x-ray/INTENT.mdmarkdown2.4 KB
canonical/skills/x-ray/TEMPLATE.mdmarkdown10.5 KB
implementation-harness.mdmarkdown1.4 KB
package.jsonmanifest696 B
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/CHANGELOG.md.patchother1.2 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/README.md.patchother1.9 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/SKILL.md.patchother2.5 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/agents/docs-writer/INTENT.md.patchother1.4 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/docs/.og/cli.test.mjs.patchother846 B
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/docs/Engineering Guide/04 AI Coding Tool Compatibility.md.patchother3.4 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/docs/Engineering Guide/05 MCP Setup.md.patchother5.2 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/manifest.json.patchother662 B
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/settings.json.patchother150 B
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/canonical/skills/design/INTENT.md.patchother19.4 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/patterns/skill-authoring.md.patchother692 B
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/host-capabilities.md.patchother1.2 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/launch/01-launch.md.patchother1.1 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/launch/01a-launch-plan.md.patchother1.6 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/launch/01b-launch-install.md.patchother7.3 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/launch/02-launch-questions.md.patchother5.2 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/launch/08-provider-launch.md.patchother3.2 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/patch/04-patch-harvest.md.patchother2.6 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/patch/05-patch-apply.md.patchother3.0 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/references/patch/06-patch-state.md.patchother7.1 KB
patch/20261105T160045Z-3.3.0-copilot-provider-6630df3d-f6bf-4651-8732-8048942ad1fe/diffs/scripts/lib/agent-format.mjs.patchother2.2 KB

canonical/docs/.og/cli.mjs

View on GitHub
#!/usr/bin/env node
// Operational-graph tool: a deterministic knowledge graph over the repo's doc
// tiers. CLI entry (parseArgs, dispatch map, mirrors timing.mjs's own shape) and
// the programmatic module imported by the VitePress build hook and lifecycle
// skills. Zero runtime dependencies beyond node:sqlite (a Node built-in).
// This file is orchestration only — it operates on a DocsStore and an
// EdgesStore instance; neither file's own table SQL lives here.
import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { fileURLToPath } from 'node:url';
import { DatabaseSync } from 'node:sqlite';

import { DB_FILE, MERMAID_FILE, AUTHORED_EDGE_TYPES } from './constants.mjs';
import { SCHEMA } from './schema.mjs';
import { need, atomicWrite, listMarkdownFiles, readIgnoreList, toPosixRelative } from './utils.mjs';
import { DocsStore } from './docs.mjs';
import { EdgesStore, computeMirrors, computeKeywordMatches } from './edges.mjs';

/** The folder this tool lives in (`<project>/docs/.og`). */
const TOOL_DIR = path.dirname(fileURLToPath(import.meta.url));

/**
 * Open the graph database at `dir`'s DB_FILE, schema ensured, and wrap it as a
 * `{ docs, edges }` store pair. `dir` must be the project root, never `docs/` or
 * `docs/.og/` themselves: those values used to create a stray empty database at a
 * nested path and silently return empty results. An empty project with no `docs/`
 * yet is fine (build creates the schema). Read-only commands pass `create: false`
 * and fail when the database is absent instead of creating an empty one.
 * @param {string} dir
 * @param {{create?: boolean}} [opts]
 * @returns {{db: import('node:sqlite').DatabaseSync, docs: DocsStore, edges: EdgesStore}}
 */
function openStore(dir, { create = true } = {}) {
  const root = path.resolve(dir);
  need(
    root !== TOOL_DIR && root !== path.dirname(TOOL_DIR) && path.basename(root) !== '.og',
    `--dir must be the project root (the folder that contains docs/), not docs/ or docs/.og/ (got "${dir}")`
  );
  const dbPath = path.join(root, DB_FILE);
  if (!create) {
    need(
      fs.existsSync(dbPath),
      `Graph not built at ${dbPath}; run: node docs/.og/cli.mjs build --dir <project root>`
    );
  }
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
  const db = new DatabaseSync(dbPath);
  db.exec(SCHEMA);
  return { db, docs: new DocsStore(db), edges: new EdgesStore(db) };
}

/**
 * Assign/confirm a doc's ID via `DocsStore.assign()` and, when `--edge` is
 * given, write the authored (derived=0) graduation edge via `EdgesStore.write()`.
 * Note: `assign()` runs before the `--edge`/`--to` validation, so a call that
 * throws (e.g. `--to` target not indexed) can still have assigned `doc`'s ID
 * as a side effect — harmless, since assignment is additive-only/idempotent
 * and safe to retry, but the call is not all-or-nothing.
 * @param {{dir: string, doc: string, id?: string, edge?: string, to?: string}} opts
 */
export async function index({ dir, doc, id, edge, to }) {
  const { db, docs, edges } = openStore(dir);
  try {
    const absDoc = path.isAbsolute(doc) ? doc : path.join(dir, doc);
    const assigned = docs.assign(dir, absDoc, { id });
    if (edge) {
      need(
        AUTHORED_EDGE_TYPES.includes(edge),
        `Unknown edge type: ${edge} (expected one of ${AUTHORED_EDGE_TYPES.join(', ')})`
      );
      need(to, '--edge requires --to');
      const absTo = path.isAbsolute(to) ? to : path.join(dir, to);
      const relTo = toPosixRelative(dir, absTo);
      const toRow = need(docs.findByPath(relTo), `--to target is not indexed: ${relTo}`);
      edges.write(assigned.id, toRow.id, edge, 0);
    }
    return assigned;
  } finally {
    db.close();
  }
}

/**
 * Retract a specific edge — the review/stale-edge-cleanup path
 * (`reindex-graph.md`'s Step 2c). Both `doc` and `to` must already be
 * indexed; a no-op if the edge is already gone.
 * @param {{dir: string, doc: string, edge: string, to: string}} opts
 */
export async function unedge({ dir, doc, edge, to }) {
  need(
    AUTHORED_EDGE_TYPES.includes(edge),
    `Unknown edge type: ${edge} (expected one of ${AUTHORED_EDGE_TYPES.join(', ')})`
  );
  const { db, docs, edges } = openStore(dir);
  try {
    const absDoc = path.isAbsolute(doc) ? doc : path.join(dir, doc);
    const absTo = path.isAbsolute(to) ? to : path.join(dir, to);
    const fromRow = need(
      docs.findByPath(toPosixRelative(dir, absDoc)),
      `--doc is not indexed: ${doc}`
    );
    const toRow = need(docs.findByPath(toPosixRelative(dir, absTo)), `--to is not indexed: ${to}`);
    edges.remove(fromRow.id, toRow.id, edge);
  } finally {
    db.close();
  }
}

/**
 * Assign IDs to every doc under `docs/` still missing one, prune rows for docs
 * whose file was deleted since the last reindex (cascading their edges), then
 * recompute every derived edge: mirrors-consistent/mirrors-gap (HLD/LLD diff)
 * and keyword-match (shared `keywords:` tokens — from the stored column, no
 * content read). Idempotent: a second run with nothing changed on disk
 * changes nothing.
 *
 * Deliberately not wrapped in a single SQLite transaction: each step below
 * (assign, prune, mirrors, keyword-match) is its own auto-committing write.
 * An interruption mid-run can leave a transient inconsistency (e.g.
 * keyword-match edges cleared but not yet recomputed), but every step is
 * idempotent and fully recomputed from current state, so the next successful
 * `reindex()`/`build()` self-heals it — a half-measure transaction wrapping
 * only some of these steps (and not `build()`'s separate Mermaid-artifact
 * write) would add complexity without closing that same window anyway.
 * @param {{dir: string}} opts
 * @returns {Promise<{skipped: {path: string, reason: string}[], pruned: string[]}>}
 */
export async function reindex({ dir }) {
  const { db, docs, edges } = openStore(dir);
  try {
    const docsRoot = path.join(dir, 'docs');
    const found = listMarkdownFiles(docsRoot, readIgnoreList(docsRoot));
    for (const file of found) docs.assign(dir, file);
    const pruned = docs.pruneExcept(new Set(found.map((file) => toPosixRelative(dir, file))));
    edges.removeForDocs(pruned);
    const { edges: mirrorEdges, skipped } = computeMirrors(dir);
    for (const edge of mirrorEdges) {
      const from = docs.findByPath(edge.fromPath);
      if (!from) continue; // Not indexed (e.g. no docs/ tree yet) — nothing to relate.
      edges.write(from.id, edge.toPlaceholder, edge.edgeType, 1);
    }
    edges.removeAllOfType('keyword-match');
    for (const { fromId, toId } of computeKeywordMatches(docs.all()))
      edges.write(fromId, toId, 'keyword-match', 1);
    return { skipped, pruned };
  } finally {
    db.close();
  }
}

/**
 * Mermaid node IDs are unquoted and bare; a raw `:` is reserved syntax, not a
 * safe character. Sanitize to a safe ID.
 * @returns {string}
 */
function safeMermaidId(id) {
  return id.replace(/[^A-Za-z0-9_]/g, '_');
}

/** Quote a node's display text safely for Mermaid's `["..."]` text syntax. */
function quoteMermaidText(text) {
  return text.replace(/"/g, '#quot;');
}

const UNTIERED_BRANCH = 'Other';

/**
 * Render the generated Mermaid artifact as a tier-rooted `mindmap`: one
 * branch per tier, one leaf per doc. Mermaid's `mindmap` is a tree, not a
 * graph — it cannot draw the `edges` table's cross-doc relations (mirrors or
 * authored); those stay queryable via `query()`/`search()`, just not drawn
 * here. Favors a tier-grouped overview over edge visualization.
 *
 * Unlike flowchart, mindmap's grammar has no `classDef` statement (confirmed
 * against its compiled parser table — no `CLASSDEF` terminal exists), so
 * there is no in-diagram way to color nodes by tier; that is why tier
 * identity here is conveyed only by the branch label, not a fill color.
 */
function renderMermaid(docs) {
  const lines = ['mindmap', '  root(("Operational Graph"))'];
  const byTier = new Map();
  for (const doc of docs.all()) {
    const tier = doc.tier ?? UNTIERED_BRANCH;
    if (!byTier.has(tier)) byTier.set(tier, []);
    byTier.get(tier).push(doc);
  }
  for (const [tier, tierDocs] of byTier) {
    lines.push(`    ${tier}`);
    for (const doc of tierDocs)
      lines.push(`      ${safeMermaidId(doc.id)}["${quoteMermaidText(doc.title ?? doc.path)}"]`);
  }
  return lines.join('\n') + '\n';
}

/**
 * Full (re)build: ensure the schema, reindex every doc (assign/prune, cascade
 * edges) and the derived mirrors edges, then emit the generated Mermaid
 * artifact. Rolls back on partial failure.
 * @param {{dir: string}} opts
 * @returns {Promise<{skipped: {path: string, reason: string}[], pruned: string[]}>}
 */
export async function build({ dir }) {
  let result;
  try {
    result = await reindex({ dir });
  } catch (error) {
    throw new Error(`build() failed, no artifact written: ${error.message}`, { cause: error });
  }
  const { db, docs } = openStore(dir);
  try {
    atomicWrite(path.join(dir, MERMAID_FILE), renderMermaid(docs));
  } finally {
    db.close();
  }
  return result;
}

/**
 * @param {{dir: string, relatedTo: string, edge?: string}} opts
 * @returns {Promise<import('./edges.mjs').EdgeRow[]>}
 */
export async function query({ dir, relatedTo, edge }) {
  const { db, docs, edges } = openStore(dir, { create: false });
  try {
    const abs = path.isAbsolute(relatedTo) ? relatedTo : path.join(dir, relatedTo);
    const relPath = fs.existsSync(abs) ? toPosixRelative(dir, abs) : relatedTo;
    const doc = docs.findByPath(relPath) ?? docs.findById(relatedTo);
    return doc ? edges.queryFrom(doc.id, edge) : [];
  } finally {
    db.close();
  }
}

/**
 * @param {{dir: string, term: string}} opts
 * @returns {Promise<{id: string, path: string, title: string|null}[]>}
 */
export async function search({ dir, term }) {
  const { db, docs } = openStore(dir, { create: false });
  try {
    const needle = term.toLowerCase();
    return docs
      .all()
      .filter((row) => {
        const haystack = [row.title, row.purpose, row.keywords]
          .filter(Boolean)
          .join(' ')
          .toLowerCase();
        if (haystack.includes(needle)) return true;
        const abs = path.join(dir, row.path);
        return fs.existsSync(abs) && fs.readFileSync(abs, 'utf8').toLowerCase().includes(needle);
      })
      .map(({ id, path: p, title }) => ({ id, path: p, title }));
  } finally {
    db.close();
  }
}

const MISSING_FIELDS = ['purpose', 'keywords'];

/**
 * Every indexed doc, or (with `missing`) only those still missing `purpose`
 * and/or `keywords`. A pure query, no writes. The caller (an agent, following
 * `reindex-graph.md`'s intelligent-scan step) reads what comes back and
 * writes frontmatter/edges itself; this script never derives or writes
 * `purpose`/`keywords`/content-reference edges on its own.
 * @param {{dir: string, missing?: string}} opts `missing`, when given, is a
 *   comma-separated subset of `purpose,keywords`; omitted means every doc.
 * @returns {Promise<import('./docs.mjs').DocRow[]>}
 */
export async function list({ dir, missing }) {
  const fields = missing ? missing.split(',').map((field) => field.trim()) : [];
  for (const field of fields)
    need(
      MISSING_FIELDS.includes(field),
      `Unknown --missing field: ${field} (expected purpose, keywords)`
    );
  const { db, docs } = openStore(dir, { create: false });
  try {
    return fields.length ? docs.missing(fields) : docs.all();
  } finally {
    db.close();
  }
}

// --- CLI entry -------------------------------------------------------------

const USAGE = `Usage: cli.mjs <command> [options]

Commands:
  build   --dir <root>
  index   --dir <root> --doc <path> [--edge <type> --to <path>] [--id <id>]
  reindex --dir <root>
  query   --dir <root> --related-to <id|path> [--edge <type>]
  search  --dir <root> --term <text>
  list    --dir <root> [--missing <purpose|keywords|purpose,keywords>]
  unedge  --dir <root> --doc <path> --edge <type> --to <path>
`;

async function runCli() {
  const [command, ...rest] = process.argv.slice(2);
  if (!command || command === '--help' || command === '-h') {
    console.log(USAGE);
    return command ? 0 : 1;
  }
  const { values } = parseArgs({
    args: rest,
    options: {
      dir: { type: 'string' },
      doc: { type: 'string' },
      id: { type: 'string' },
      edge: { type: 'string' },
      to: { type: 'string' },
      'related-to': { type: 'string' },
      term: { type: 'string' },
      missing: { type: 'string' },
    },
  });
  const dir = need(values.dir, '--dir is required');
  const handlers = {
    build: () => build({ dir }),
    index: () =>
      index({
        dir,
        doc: need(values.doc, '--doc is required'),
        id: values.id,
        edge: values.edge,
        to: values.to,
      }),
    reindex: () => reindex({ dir }),
    query: () =>
      query({
        dir,
        relatedTo: need(values['related-to'], '--related-to is required'),
        edge: values.edge,
      }),
    search: () => search({ dir, term: need(values.term, '--term is required') }),
    list: () => list({ dir, missing: values.missing }),
    unedge: () =>
      unedge({
        dir,
        doc: need(values.doc, '--doc is required'),
        edge: need(values.edge, '--edge is required'),
        to: need(values.to, '--to is required'),
      }),
  };
  const handler = handlers[command];
  if (!handler) {
    console.error(`Unknown command: ${command}\n\n${USAGE}`);
    return 1;
  }
  console.log(JSON.stringify(await handler(), null, 2));
  return 0;
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  runCli()
    .then((code) => {
      process.exitCode = code;
    })
    .catch((error) => {
      console.error(`cli.mjs: ${error.message}`);
      process.exitCode = 1;
    });
}
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall