Skip to content
forms-raw_singleitemedit-icon
navigation
modification_btn
docs
messages
flatprojectmap.handlebars
Plug-in - Documentation Engine
modificationbutton
docs_htmltables.handlebars

Plug-in - Documentation Engine

docs_html.handlebars
documentation.handlebars

MVP Specification: Hierarchical “Units on Disk” with an LLM Feedback Loop

Stack: Node.js, Express, Handlebars, local filesystem (no MVC). Scope: minimum viable product to iterate with an LLM.

1) Overview

This MVP replaces the traditional MVC layout with a hierarchical graph of Units stored on disk. Each Unit has a one-to-one relationship with its Notes, LLM Prompt, Code, Tests, and Run logs. The UI provides a left navigation tree (parent→child), a central editor with tabs (Notes/Prompt/Code/Tests/Runs), and an optional right panel for lineage (Prompt→Code→Tests).

The goal is to make the LLM feedback loop explicit: prompts generate or refine code, tests validate outputs, runs record evidence, and notes capture rationale. All artifacts live together under a Unit so the loop is traceable and easy to edit.

2) Goals & Non-Goals

Goals

  • Single Unit entity for hierarchy + co-located artifacts (notes/prompt/code/tests/runs).
  • Local-first, file-backed store (data/units) with atomic writes (no DB).
  • Express + Handlebars UI (no MVC controllers/models by feature type).
  • LLM loop primitives: “Generate from Prompt”, “Refine”, “Record Run”.
  • Export/tangle/weave of a Unit or subtree (HTML/JSON).

Non-Goals (MVP)

  • Multi-user concurrency & locking.
  • Auth/permissions beyond local dev.
  • LLM provider integration server-side (can be added later).
  • Rich code execution sandbox; tests may be recorded, not executed in-app.

3) Core Concepts

3.1 Unit

A Unit is a node in a tree (like a feature, module, endpoint, or component). It owns pointers to sidecar files: notes.mdprompt.mdcode.*tests.*runs/*.json. Units can be folders or leaves; parent/child define the hierarchy.

3.2 Edges & Provenance

Units store lightweight edges declaring relationships, e.g., generatedFrom: ["prompt"], validatedBy: ["tests"]. The UI renders these edges as a simple lineage (no heavy graph DB).

3.3 Local Filesystem Store

The store reads/writes JSON and sidecar files under data/units/. Atomic writes use temporary files + rename.

4) On-Disk Layout & Schemas

4.1 Directory Layout

data/
                      units/
                        000-root.hunit.json            (optional root as a file)
                        auth/
                          auth.hunit.json
                          notes.md
                          prompt.md
                          code.js
                          tests.spec.js
                          runs/
                            2025-09-24T102355Z.json
                        invoices/
                          invoices.hunit.json
                          notes.md
                          prompt.md
                          code.ts
                          tests.spec.ts
                          runs/
                            2025-09-24T111201Z.json
                    

4.2 .hunit.json Schema (MVP)

FieldTypeRequiredDescription
idstringYesDirectory name & stable identifier.
titlestringYesHuman-readable title.
parentIdstring|nullNoParent Unit id; null for root.
ordernumberNoSibling ordering (asc).
kind"unit"|"folder"NoOptional label for UI rendering.
languagestringNoHint for code editor (e.g., js, ts, html).
pathsobjectPartialRelative paths: notes, prompt, code, tests.
edgesobjectNoProvenance: generatedFrom, validatedBy, related.
metaobjectNoTags, timestamps, createdBy, etc.
childrenarrayNoFilled at runtime by the store (not required on disk).

4.3 Example .hunit.json

{
                      "id": "auth",
                      "title": "Auth module",
                      "parentId": "root",
                      "order": 5,
                      "kind": "unit",
                      "language": "js",
                      "paths": {
                        "notes": "notes.md",
                        "prompt": "prompt.md",
                        "code": "code.js",
                        "tests": "tests.spec.js"
                      },
                      "edges": {
                        "generatedFrom": ["prompt"],
                        "validatedBy": ["tests"],
                        "related": []
                      },
                      "meta": {
                        "tags": ["backend","security"],
                        "createdBy": "dev",
                        "updatedAt": "2025-09-24T10:12:00Z"
                      }
                    }
                    

4.4 Run Log Entry (JSON)

{
                      "timestamp": "2025-09-24T11:12:33.000Z",
                      "action": "generate|refine|test|export|tangle",
                      "input": { "prompt": "..." },
                      "output": { "files": ["code.js"] },
                      "result": { "passed": 10, "failed": 0 },
                      "meta": { "model": "gpt-X", "durationMs": 1423 }
                    }
                    

5) Filesystem Store (Node)

The store replaces ORM/Models. It exposes minimal functions for the UI and API to manipulate Units and their content.

5.1 Store API

FunctionPurpose
loadTree()Scan data/units, build { roots, byId } hierarchy.
getUnit(id)Read a Unit’s JSON.
saveUnit(unit)Atomic write of a Unit’s JSON.
readContent(unit, kind)Read notes/prompt/code/tests.
writeContent(unit, kind, text)Write sidecar file.
recordRun(unit, run)Append a run JSON into runs/.

5.2 Implementation (Skeleton)

// /plugins/units/store/fsStore.js
                    const fs = require('fs/promises');
                    const path = require('path');
                    const ROOT = path.join(process.cwd(), 'data', 'units');
                    
                    async function readJSON(p) { return JSON.parse(await fs.readFile(p, 'utf8')); }
                    async function writeJSON(p, obj) {
                      const tmp = p + '.tmp';
                      await fs.mkdir(path.dirname(p), { recursive: true });
                      await fs.writeFile(tmp, JSON.stringify(obj, null, 2), 'utf8');
                      await fs.rename(tmp, p);
                    }
                    
                    async function getUnit(id) {
                      const dir = path.join(ROOT, id);
                      const file = path.join(dir, `${id}.hunit.json`);
                      try { return await readJSON(file); }
                      catch {
                        const fallback = path.join(ROOT, `${id}.hunit.json`);
                        return await readJSON(fallback);
                      }
                    }
                    
                    async function saveUnit(unit) {
                      const dir = path.join(ROOT, unit.id);
                      const file = path.join(dir, `${unit.id}.hunit.json`);
                      await writeJSON(file, unit);
                    }
                    
                    async function readContent(unit, kind) {
                      const rel = unit.paths?.[kind];
                      if (!rel) return '';
                      const base = path.join(ROOT, unit.id);
                      return fs.readFile(path.join(base, rel), 'utf8');
                    }
                    
                    async function writeContent(unit, kind, text) {
                      const rel = unit.paths?.[kind];
                      if (!rel) throw new Error(\`No path for \${kind}\`);
                      const base = path.join(ROOT, unit.id);
                      await fs.mkdir(base, { recursive: true });
                      await fs.writeFile(path.join(base, rel), text, 'utf8');
                    }
                    
                    async function recordRun(unit, run) {
                      const dir = path.join(ROOT, unit.id, 'runs');
                      await fs.mkdir(dir, { recursive: true });
                      const stamp = new Date().toISOString().replace(/[:.]/g,'');
                      await writeJSON(path.join(dir, \`\${stamp}.json\`), { timestamp: new Date().toISOString(), ...run });
                    }
                    
                    async function loadTree() {
                      const entries = await fs.readdir(ROOT, { withFileTypes: true }).catch(() => []);
                      const units = [];
                      for (const e of entries) {
                        if (e.isDirectory()) {
                          const id = e.name;
                          const p = path.join(ROOT, id, \`\${id}.hunit.json\`);
                          try { units.push(await readJSON(p)); } catch {}
                        } else if (e.isFile() && e.name.endsWith('.hunit.json')) {
                          units.push(await readJSON(path.join(ROOT, e.name)));
                        }
                      }
                      const byId = Object.fromEntries(units.map(u => [u.id, u]));
                      const roots = [];
                      units.forEach(u => u.children = []);
                      for (const u of units) {
                        if (u.parentId && byId[u.parentId]) byId[u.parentId].children.push(u);
                        else roots.push(u);
                      }
                      const sort = (a,b) => (a.order ?? 0) - (b.order ?? 0) || String(a.title).localeCompare(b.title);
                      (function sortRec(list){ list.sort(sort); list.forEach(x => sortRec(x.children)); })(roots);
                      return { roots, byId };
                    }
                    
                    module.exports = { loadTree, getUnit, saveUnit, readContent, writeContent, recordRun };
                    

6) Express Routes (Thin, No MVC)

// /plugins/units/index.js
                    const express = require('express');
                    const router = express.Router();
                    const store = require('./store/fsStore');
                    const path = require('path');
                    
                    // Browser: nav + selected preview
                    router.get('/heron', async (req, res, next) => {
                      try {
                        const { roots } = await store.loadTree();
                        const selectedId = req.query.selectedId || (roots[0] && roots[0].id) || null;
                        res.render(path.join(__dirname, 'views/browser'), { layout: 'main', navTree: roots, selectedId });
                      } catch (e) { next(e); }
                    });
                    
                    // Unit editor (tabs)
                    router.get('/heron/unit/:id', async (req, res, next) => {
                      try {
                        const unit = await store.getUnit(req.params.id);
                        const [notes,prompt,code,tests] = await Promise.all([
                          store.readContent(unit, 'notes').catch(()=>''), 
                          store.readContent(unit, 'prompt').catch(()=>''), 
                          store.readContent(unit, 'code').catch(()=>''), 
                          store.readContent(unit, 'tests').catch(()=>''), 
                        ]);
                        res.render(path.join(__dirname, 'views/unit'), { layout: 'main', unit, notes, prompt, code, tests });
                      } catch (e) { next(e); }
                    });
                    
                    // Save a content stream (notes/prompt/code/tests)
                    router.post('/api/unit/:id/content/:kind', express.text({ type: '*/*' }), async (req, res, next) => {
                      try {
                        const unit = await store.getUnit(req.params.id);
                        await store.writeContent(unit, req.params.kind, req.body || '');
                        unit.meta = unit.meta || {}; unit.meta.updatedAt = new Date().toISOString();
                        await store.saveUnit(unit);
                        res.json({ ok: true });
                      } catch (e) { next(e); }
                    });
                    
                    // Update unit meta (title, order, parent, edges)
                    router.patch('/api/unit/:id', express.json(), async (req, res, next) => {
                      try {
                        const unit = await store.getUnit(req.params.id);
                        Object.assign(unit, req.body);
                        unit.meta = unit.meta || {}; unit.meta.updatedAt = new Date().toISOString();
                        await store.saveUnit(unit);
                        res.json({ ok: true, unit });
                      } catch (e) { next(e); }
                    });
                    
                    // Record a run (LLM gen/refine/test)
                    router.post('/api/unit/:id/runs', express.json(), async (req, res, next) => {
                      try {
                        const unit = await store.getUnit(req.params.id);
                        await store.recordRun(unit, req.body);
                        res.status(201).json({ ok: true });
                      } catch (e) { next(e); }
                    });
                    
                    module.exports = router;
                    

7) Handlebars Views

7.1 Browser (Tree + Open Unit)

{{!-- /plugins/units/views/browser.handlebars --}}
                    <div class="container-fluid">
                      <div class="row">
                        <nav class="col-md-3 col-12 border-end pt-3">
                          <h5>Units</h5>
                          <ul class="nav flex-column">
                            {{#each navTree}}
                              {{> navNodeSelect this}}
                            {{/each}}
                          </ul>
                        </nav>
                    
                        <main class="col-md-9 col-12 pt-3">
                          <h2>Workspace</h2>
                          {{#if selectedId}}
                            <p>
                              <a class="btn btn-primary btn-sm" href="/heron/unit/{{selectedId}}">Open selected Unit</a>
                            </p>
                          {{else}}
                            <p class="text-muted">Select a Unit from the tree.</p>
                          {{/if}}
                        </main>
                      </div>
                    </div>
                    

7.2 Nav Partial (Browser)

{{!-- /plugins/units/views/partials/navNodeSelect.handlebars --}}
                    <li class="nav-item">
                      <a class="nav-link py-1 px-2 {{#if isActive}}active fw-semibold{{/if}}" 
                         href="/heron?selectedId={{id}}">{{title}}</a>
                      {{#if children}}
                        <ul class="nav flex-column ms-3">
                          {{#each children}}
                            {{> navNodeSelect this}}
                          {{/each}}
                        </ul>
                      {{/if}}
                    </li>
                    

7.3 Unit Editor (Tabs)

{{!-- /plugins/units/views/unit.handlebars --}}
                    <div class="container-fluid">
                      <div class="row">
                        <nav class="col-md-3 col-12 border-end pt-3">
                          <h5><a href="/heron?selectedId={{unit.id}}">Units</a></h5>
                        </nav>
                    
                        <main class="col-md-9 col-12 pt-3">
                          <h2>{{unit.title}}</h2>
                    
                          <ul class="nav nav-tabs" role="tablist">
                            <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-notes">Notes</button></li>
                            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-prompt">Prompt</button></li>
                            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-code">Code</button></li>
                            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-tests">Tests</button></li>
                            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-runs">Runs</button></li>
                          </ul>
                    
                          <div class="tab-content border p-3 border-top-0">
                            <div id="tab-notes" class="tab-pane fade show active">
                              <textarea id="notes" class="form-control" rows="10">{{{notes}}}</textarea>
                              <button data-kind="notes" class="btn btn-secondary mt-2 js-save">Save Notes</button>
                            </div>
                    
                            <div id="tab-prompt" class="tab-pane fade">
                              <textarea id="prompt" class="form-control" rows="10">{{{prompt}}}</textarea>
                              <div class="mt-2 d-flex gap-2">
                                <button data-kind="prompt" class="btn btn-secondary js-save">Save Prompt</button>
                                <button class="btn btn-primary js-generate">Generate/Refine Code</button>
                              </div>
                            </div>
                    
                            <div id="tab-code" class="tab-pane fade">
                              <textarea id="code" class="form-control" rows="12">{{{code}}}</textarea>
                              <button data-kind="code" class="btn btn-secondary mt-2 js-save">Save Code</button>
                            </div>
                    
                            <div id="tab-tests" class="tab-pane fade">
                              <textarea id="tests" class="form-control" rows="10">{{{tests}}}</textarea>
                              <button data-kind="tests" class="btn btn-secondary mt-2 js-save">Save Tests</button>
                            </div>
                    
                            <div id="tab-runs" class="tab-pane fade">
                              <p class="text-muted">MVP: runs are JSON files stored per unit. Use Export to view combined logs.</p>
                              <button class="btn btn-outline-primary js-record-run">Record Dummy Run</button>
                            </div>
                          </div>
                    
                          <script>
                          (function(){
                            const unitId = "{{unit.id}}";
                            async function save(kind, txt) {
                              await fetch(\`/api/unit/\${unitId}/content/\${kind}\`, { method: 'POST', body: txt, headers: { 'Content-Type': 'text/plain' }});
                            }
                            document.querySelectorAll('.js-save').forEach(btn => {
                              btn.addEventListener('click', async () => {
                                const kind = btn.getAttribute('data-kind');
                                const txt = document.getElementById(kind)?.value || '';
                                btn.disabled = true; await save(kind, txt); btn.disabled = false;
                              });
                            });
                            document.querySelector('.js-record-run')?.addEventListener('click', async () => {
                              await fetch(\`/api/unit/\${unitId}/runs\`, {
                                method: 'POST', headers: {'Content-Type':'application/json'},
                                body: JSON.stringify({ action:'test', result:{ passed:0, failed:0 }, meta:{ source:'mvp' }})
                              });
                              alert('Run recorded.');
                            });
                            document.querySelector('.js-generate')?.addEventListener('click', async () => {
                              // MVP placeholder: we only record an intent. LLM integration can be added later.
                              const prompt = document.getElementById('prompt').value;
                              await fetch(\`/api/unit/\${unitId}/runs\`, {
                                method:'POST', headers:{'Content-Type':'application/json'},
                                body: JSON.stringify({ action:'generate', input:{ prompt }, meta:{ note:'MVP placeholder' }})
                              });
                              alert('Generation intent recorded (hook LLM later).');
                            });
                          })();
                          </script>
                        </main>
                      </div>
                    </div>
                    

8) LLM Feedback Loop (MVP Flows)

  1. Author Notes in Notes to capture intent, constraints, edge cases.
  2. Draft Prompt in Prompt. Click Generate/Refine Code (MVP: records intent as a run; wire LLM later).
  3. Edit Code in Code. Save updates.
  4. Write Tests in Tests. (MVP: store; optional to run externally.)
  5. Record Runs after executing tests externally (or use the dummy recorder for now).
  6. Review Lineage via edges: Prompt → Code (generatedFrom), Code → Tests (validatedBy), Tests → Runs (evidence).

The MVP keeps actions local and explicit. A later increment can call an LLM provider, update code automatically, and append a run with provenance.

9) Export, Tangle, Weave (MVP)

  • Export (JSON): Walk a subtree and return { unit, children, files, runs }.
  • Weave (HTML): Concatenate depth-first: title, notes (rendered markdown), prompt (pre), code (pre), tests (pre).
  • Tangle (Files): Optionally write code.* files into a target workspace folder.
// Example export endpoint (skeleton)
                    router.get('/api/unit/:id/export', async (req, res, next) => {
                      try {
                        const { byId, roots } = await store.loadTree();
                        const id = req.params.id;
                        function gather(node) {
                          const u = byId[node.id] || node;
                          return { 
                            unit: u,
                            children: (u.children || []).map(gather)
                          };
                        }
                        const root = byId[id] || roots[0];
                        res.json({ ok:true, tree: gather(root) });
                      } catch (e) { next(e); }
                    });
                    

10) MVP Build Plan (1–2 days of focused work)

  1. Create data/units/ and seed one Unit (root) with minimal sidecar files.
  2. Implement fsStore with loadTree/getUnit/saveUnit etc.
  3. Add routes: GET /heron, GET /heron/unit/:id, POST /api/unit/:id/content/:kind, PATCH /api/unit/:id, POST /api/unit/:id/runs.
  4. Build browser.handlebars + navNodeSelect partial.
  5. Build unit.handlebars (tabs, Save buttons, dummy run record).
  6. Smoke test: create child Units by copying a folder + editing .hunit.json.
  7. Optional: add Export (JSON) endpoint and a Weave (HTML) preview.

11) Acceptance Criteria

  • Left tree shows Units in hierarchical order (order asc, then title asc).
  • Unit editor loads and saves notes, prompt, code, tests correctly.
  • Clicking “Generate/Refine Code” creates a run JSON entry with action generate.
  • “Record Dummy Run” creates a run JSON entry with action test.
  • Export endpoint returns a structured JSON for the selected Unit subtree.

12) Security & Operations (MVP)

  • Local development only. No authentication required (yet).
  • Atomic JSON writes (.tmp + rename) to prevent corruption.
  • Escape content on HTML render (notes can be Markdown → sanitized HTML if you add a renderer).
  • Backups: Git commit the data/units/ folder or copy per sprint.

13) Migration (Optional)

If you have legacy Mongo docs (e.g., Heron), write a one-off script that creates Unit folders per document: title → title, slug/id → id, content → code.html, plus empty notes.md and prompt.md. Set parentId and order to preserve hierarchy.

14) Future Enhancements

  • LLM Integration: server-side action to call a provider with prompt, patch code, and append run with diffs.
  • Test Runner: execute tests (Node/Playwright/etc.) and capture structured results into runs.
  • Search: full-text across notes/prompts/code.
  • Templates: “New Unit from Template” (API route, UI action).
  • Graph View: visualize edges across Units (dependencies, lineage).
  • Multi-user: auth, file locks, merge helpers.

End of MVP spec. This file is ready to drop into your docs; copy into a Unit’s code.html or a standalone page.

=
modal1
modal2
modal3
docs_javascript
new_issue_button.handlebars
shortcut_edit