nubos-pilot 1.3.1 → 1.3.3

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.
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { test, afterEach } = require('node:test');
7
+ const assert = require('node:assert/strict');
8
+
9
+ const subcmd = require('./simplify-debt.cjs');
10
+
11
+ const _sandboxes = [];
12
+
13
+ function makeSandbox() {
14
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'np-simplify-debt-'));
15
+ fs.mkdirSync(path.join(root, '.nubos-pilot'), { recursive: true });
16
+ _sandboxes.push(root);
17
+ return root;
18
+ }
19
+
20
+ function capture(fn) {
21
+ const out = [];
22
+ const orig = process.stdout.write.bind(process.stdout);
23
+ process.stdout.write = (c) => { out.push(String(c)); return true; };
24
+ let rc;
25
+ try { rc = fn(); } finally { process.stdout.write = orig; }
26
+ return { stdout: out.join(''), rc };
27
+ }
28
+
29
+ afterEach(() => {
30
+ while (_sandboxes.length) {
31
+ try { fs.rmSync(_sandboxes.pop(), { recursive: true, force: true }); } catch { /* best effort */ }
32
+ }
33
+ });
34
+
35
+ test('SD-1: add records an entry and reports was_new', () => {
36
+ const cwd = makeSandbox();
37
+ const { stdout, rc } = capture(() =>
38
+ subcmd.run(['add', '--file', 'src/foo.ts', '--line', '42', '--category', 'over-engineering', '--note', 'inline the factory'], { cwd }),
39
+ );
40
+ assert.equal(rc, 0);
41
+ const res = JSON.parse(stdout);
42
+ assert.equal(res.ok, true);
43
+ assert.equal(res.action, 'add');
44
+ assert.equal(res.was_new, true);
45
+ assert.equal(res.entry.category, 'over-engineering');
46
+ });
47
+
48
+ test('SD-2: add accepts the note as positional args', () => {
49
+ const cwd = makeSandbox();
50
+ const { stdout, rc } = capture(() =>
51
+ subcmd.run(['add', '--category', 'shrinkable', 'collapse', 'this', 'loop'], { cwd }),
52
+ );
53
+ assert.equal(rc, 0);
54
+ assert.equal(JSON.parse(stdout).entry.note, 'collapse this loop');
55
+ });
56
+
57
+ test('SD-3: list (default open) renders the ledger', () => {
58
+ const cwd = makeSandbox();
59
+ capture(() => subcmd.run(['add', '--file', 'a.ts', '--category', 'shrinkable', '--note', 'use reduce'], { cwd }));
60
+ const { stdout, rc } = capture(() => subcmd.run(['list'], { cwd }));
61
+ assert.equal(rc, 0);
62
+ assert.match(stdout, /shrinkable/);
63
+ assert.match(stdout, /1 open/);
64
+ });
65
+
66
+ test('SD-4: list --json emits structured entries', () => {
67
+ const cwd = makeSandbox();
68
+ capture(() => subcmd.run(['add', '--file', 'a.ts', '--category', 'shrinkable', '--note', 'x'], { cwd }));
69
+ const { stdout } = capture(() => subcmd.run(['list', '--json'], { cwd }));
70
+ const res = JSON.parse(stdout);
71
+ assert.equal(res.count, 1);
72
+ assert.equal(res.entries[0].category, 'shrinkable');
73
+ });
74
+
75
+ test('SD-5: no-arg defaults to list', () => {
76
+ const cwd = makeSandbox();
77
+ const { stdout, rc } = capture(() => subcmd.run([], { cwd }));
78
+ assert.equal(rc, 0);
79
+ assert.match(stdout, /empty|Lean already/i);
80
+ });
81
+
82
+ test('SD-6: resolve moves an entry to resolved', () => {
83
+ const cwd = makeSandbox();
84
+ const added = capture(() => subcmd.run(['add', '--file', 'a.ts', '--category', 'native-duplication', '--note', 'reuse helper'], { cwd }));
85
+ const id = JSON.parse(added.stdout).entry.id;
86
+ const { stdout, rc } = capture(() => subcmd.run(['resolve', id], { cwd }));
87
+ assert.equal(rc, 0);
88
+ assert.equal(JSON.parse(stdout).entry.status, 'resolved');
89
+ const open = capture(() => subcmd.run(['list', '--json'], { cwd }));
90
+ assert.equal(JSON.parse(open.stdout).count, 0);
91
+ });
92
+
93
+ test('SD-7: unknown verb throws', () => {
94
+ const cwd = makeSandbox();
95
+ assert.throws(
96
+ () => subcmd.run(['frobnicate'], { cwd }),
97
+ (err) => err && err.name === 'NubosPilotError' && err.code === 'simplify-debt-unknown-verb',
98
+ );
99
+ });
@@ -6,8 +6,9 @@ const LEGACY_CRITIC_AXIS_AGENTS = Object.freeze([
6
6
  'np-critic-style',
7
7
  'np-critic-tests',
8
8
  'np-critic-acceptance',
9
+ 'np-critic-economy',
9
10
  ]);
10
- const SUPPORTED_CRITIC_AXES = Object.freeze(['critic', 'style', 'tests', 'acceptance']);
11
+ const SUPPORTED_CRITIC_AXES = Object.freeze(['critic', 'style', 'tests', 'acceptance', 'economy']);
11
12
 
12
13
  const EXECUTOR_AGENT = 'np-executor';
13
14
  const BUILD_FIXER_AGENT = 'np-build-fixer';
@@ -248,6 +248,7 @@ const NP_AGENTS = [
248
248
  { file: 'np-sc-extractor', expected_tier: 'haiku' },
249
249
  { file: 'np-critic', expected_tier: 'sonnet' },
250
250
  { file: 'np-learnings-extractor', expected_tier: 'haiku' },
251
+ { file: 'np-simplifier', expected_tier: 'sonnet' },
251
252
  ];
252
253
 
253
254
  // Audit-surface modules — files in agents/ that carry agent-shaped frontmatter
@@ -257,6 +258,7 @@ const NP_AGENT_MODULES = [
257
258
  { file: 'np-critic-style', parent: 'np-critic' },
258
259
  { file: 'np-critic-tests', parent: 'np-critic' },
259
260
  { file: 'np-critic-acceptance', parent: 'np-critic' },
261
+ { file: 'np-critic-economy', parent: 'np-critic' },
260
262
  ];
261
263
 
262
264
  for (let i = 0; i < NP_AGENTS.length; i += 1) {
@@ -0,0 +1,42 @@
1
+ const path = require('node:path');
2
+ const { listCheckpoints, deleteCheckpoint } = require('./checkpoint.cjs');
3
+ const { findCommitByTaskId } = require('./git.cjs');
4
+ const { TASK_ID_RE } = require('./ids.cjs');
5
+
6
+ function committedSha(taskId, cwd) {
7
+ try {
8
+ return findCommitByTaskId(taskId, cwd);
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ function reconcileCommittedCheckpoints(cwd = process.cwd(), opts = {}) {
15
+ const exclude = opts.exclude || null;
16
+ const pruned = [];
17
+ const remaining = [];
18
+ for (const file of listCheckpoints(cwd)) {
19
+ const taskId = path.basename(file, '.json');
20
+ if (!TASK_ID_RE.test(taskId)) {
21
+ remaining.push(taskId);
22
+ continue;
23
+ }
24
+ if (exclude && taskId === exclude) {
25
+ remaining.push(taskId);
26
+ continue;
27
+ }
28
+ const sha = committedSha(taskId, cwd);
29
+ if (sha) {
30
+ deleteCheckpoint(taskId, cwd);
31
+ pruned.push({ task_id: taskId, sha });
32
+ } else {
33
+ remaining.push(taskId);
34
+ }
35
+ }
36
+ return { pruned, remaining };
37
+ }
38
+
39
+ module.exports = {
40
+ committedSha,
41
+ reconcileCommittedCheckpoints,
42
+ };
@@ -0,0 +1,106 @@
1
+ const { test, after } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const { execFileSync } = require('node:child_process');
7
+
8
+ const { startTask, listCheckpoints } = require('./checkpoint.cjs');
9
+ const { reconcileCommittedCheckpoints, committedSha } = require('./checkpoint-reconcile.cjs');
10
+
11
+ const _repos = [];
12
+
13
+ function makeRepo() {
14
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'np-cr-'));
15
+ execFileSync('git', ['init', '-q', '-b', 'main', root], { stdio: 'pipe' });
16
+ execFileSync('git', ['-C', root, 'config', 'user.email', 'test@nubos.local']);
17
+ execFileSync('git', ['-C', root, 'config', 'user.name', 'nubos-test']);
18
+ execFileSync('git', ['-C', root, 'commit', '--allow-empty', '-q', '-m', 'chore: init'], { stdio: 'pipe' });
19
+ fs.mkdirSync(path.join(root, '.nubos-pilot'), { recursive: true });
20
+ fs.writeFileSync(path.join(root, '.nubos-pilot', 'STATE.md'), `---
21
+ schema_version: 2
22
+ milestone: m1
23
+ milestone_name: m1
24
+ current_phase: null
25
+ current_plan: null
26
+ current_task: null
27
+ last_updated: "2026-04-15T00:00:00Z"
28
+ progress:
29
+ total_phases: 0
30
+ completed_phases: 0
31
+ total_plans: 0
32
+ completed_plans: 0
33
+ percent: 0
34
+ session:
35
+ stopped_at: null
36
+ resume_file: null
37
+ last_activity: null
38
+ ---
39
+
40
+ # State
41
+ `, 'utf-8');
42
+ _repos.push(root);
43
+ return root;
44
+ }
45
+
46
+ function commitFor(root, taskId) {
47
+ execFileSync('git', ['-C', root, 'commit', '--allow-empty', '-q', '-m', `task(${taskId}): demo`], { stdio: 'pipe' });
48
+ }
49
+
50
+ after(() => {
51
+ while (_repos.length) {
52
+ const r = _repos.pop();
53
+ try { fs.rmSync(r, { recursive: true, force: true }); } catch {}
54
+ }
55
+ });
56
+
57
+ test('CR-1: prunes a checkpoint whose task already has a commit', () => {
58
+ const root = makeRepo();
59
+ startTask({ id: 'M013-S005-T0002', phase: 6, plan: '06-01', wave: 1 }, root);
60
+ commitFor(root, 'M013-S005-T0002');
61
+
62
+ const { pruned, remaining } = reconcileCommittedCheckpoints(root);
63
+ assert.equal(pruned.length, 1);
64
+ assert.equal(pruned[0].task_id, 'M013-S005-T0002');
65
+ assert.match(pruned[0].sha, /^[0-9a-f]{40}$/);
66
+ assert.deepEqual(remaining, []);
67
+ assert.deepEqual(listCheckpoints(root), []);
68
+ });
69
+
70
+ test('CR-2: keeps a checkpoint with no matching commit (genuine orphan)', () => {
71
+ const root = makeRepo();
72
+ startTask({ id: 'M013-S005-T0003', phase: 6, plan: '06-01', wave: 1 }, root);
73
+
74
+ const { pruned, remaining } = reconcileCommittedCheckpoints(root);
75
+ assert.deepEqual(pruned, []);
76
+ assert.deepEqual(remaining, ['M013-S005-T0003']);
77
+ assert.equal(listCheckpoints(root).length, 1);
78
+ });
79
+
80
+ test('CR-3: excludes the active current_task even when committed', () => {
81
+ const root = makeRepo();
82
+ startTask({ id: 'M013-S005-T0004', phase: 6, plan: '06-01', wave: 1 }, root);
83
+ commitFor(root, 'M013-S005-T0004');
84
+
85
+ const { pruned, remaining } = reconcileCommittedCheckpoints(root, { exclude: 'M013-S005-T0004' });
86
+ assert.deepEqual(pruned, []);
87
+ assert.deepEqual(remaining, ['M013-S005-T0004']);
88
+ assert.equal(listCheckpoints(root).length, 1);
89
+ });
90
+
91
+ test('CR-4: prunes committed tombstone but keeps uncommitted sibling', () => {
92
+ const root = makeRepo();
93
+ startTask({ id: 'M013-S005-T0002', phase: 6, plan: '06-01', wave: 1 }, root);
94
+ startTask({ id: 'M013-S005-T0003', phase: 6, plan: '06-01', wave: 1 }, root);
95
+ commitFor(root, 'M013-S005-T0002');
96
+
97
+ const { pruned, remaining } = reconcileCommittedCheckpoints(root);
98
+ assert.deepEqual(pruned.map((p) => p.task_id), ['M013-S005-T0002']);
99
+ assert.deepEqual(remaining, ['M013-S005-T0003']);
100
+ });
101
+
102
+ test('CR-5: committedSha returns null outside a git repo (no throw)', () => {
103
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'np-cr-nogit-'));
104
+ _repos.push(root);
105
+ assert.equal(committedSha('M013-S005-T0002', root), null);
106
+ });
@@ -18,6 +18,10 @@ const DEFAULT_AGENTS = Object.freeze({
18
18
  research: true,
19
19
  plan_checker: true,
20
20
  verifier: true,
21
+ // Economy axis level (off|lite|full|ultra). Default `lite` = prevention-first:
22
+ // the climb-the-ladder discipline is on, the in-loop critic is opt-in (full/ultra).
23
+ // Resolved via lib/economy-mode.cjs; legacy `economy_critic` bool still honoured.
24
+ economy: 'lite',
21
25
  });
22
26
 
23
27
  const DEFAULT_LOOP = Object.freeze({
@@ -35,6 +39,7 @@ const DEFAULT_SWARM_CRITIC = Object.freeze({
35
39
  style_tier: 'haiku',
36
40
  tests_tier: 'sonnet',
37
41
  acceptance_tier: 'sonnet',
42
+ economy_tier: 'haiku',
38
43
  });
39
44
 
40
45
  const DEFAULT_SWARM = Object.freeze({
@@ -118,6 +123,13 @@ const DEFAULT_MODEL_PROFILE = 'frontier';
118
123
  const DEFAULT_SCOPE = 'local';
119
124
  const DEFAULT_RESPONSE_LANGUAGE = 'en';
120
125
 
126
+ // Install/update ships the most aggressive Economy level by default. This is the
127
+ // value written into a fresh config.json (and backfilled into keyless configs on
128
+ // update — see bin/install.js). It deliberately differs from the *resolved*
129
+ // fallback in DEFAULT_AGENTS.economy (`lite`): a config with the key absent
130
+ // entirely stays conservative, but anything nubos-pilot writes opts into ultra.
131
+ const INSTALL_ECONOMY_MODE = 'ultra';
132
+
121
133
  const DEFAULT_CONFIG_TREE = Object.freeze({
122
134
  scope: DEFAULT_SCOPE,
123
135
  model_profile: DEFAULT_MODEL_PROFILE,
@@ -147,7 +159,7 @@ function buildInstallConfig(answers) {
147
159
  model_profile: a.model_profile || DEFAULT_MODEL_PROFILE,
148
160
  response_language: a.response_language || DEFAULT_RESPONSE_LANGUAGE,
149
161
  workflow: workflowOverride,
150
- agents: { ...DEFAULT_AGENTS },
162
+ agents: { ...DEFAULT_AGENTS, economy: INSTALL_ECONOMY_MODE },
151
163
  loop: { ...DEFAULT_LOOP },
152
164
  swarm: {
153
165
  research: { ...DEFAULT_SWARM_RESEARCH },
@@ -191,6 +203,7 @@ module.exports = {
191
203
  DEFAULT_MODEL_PROFILE,
192
204
  DEFAULT_SCOPE,
193
205
  DEFAULT_RESPONSE_LANGUAGE,
206
+ INSTALL_ECONOMY_MODE,
194
207
  DEFAULT_CONFIG_TREE,
195
208
  buildInstallConfig,
196
209
  };
@@ -6,8 +6,17 @@ const {
6
6
  DEFAULT_WORKFLOW,
7
7
  DEFAULT_MODEL_PROFILE,
8
8
  DEFAULT_SCOPE,
9
+ DEFAULT_CONFIG_TREE,
10
+ INSTALL_ECONOMY_MODE,
9
11
  } = require('./config-defaults.cjs');
10
12
 
13
+ test('CFD-economy: install writes economy=ultra, but the resolved fallback stays lite', () => {
14
+ assert.equal(INSTALL_ECONOMY_MODE, 'ultra');
15
+ assert.equal(buildInstallConfig({ runtime: 'claude' }).agents.economy, 'ultra');
16
+ // The keyless resolved fallback is intentionally conservative.
17
+ assert.equal(DEFAULT_CONFIG_TREE.agents.economy, 'lite');
18
+ });
19
+
11
20
  test('CFD-1: buildInstallConfig defaults preserve commit_artifacts:true (back-compat)', () => {
12
21
  const cfg = buildInstallConfig({ runtime: 'claude' });
13
22
  assert.equal(cfg.workflow.commit_artifacts, true);
@@ -5,6 +5,7 @@ const VALID_SCOPES = Object.freeze(['local', 'global']);
5
5
  const VALID_MODEL_PROFILES = Object.freeze(['frontier', 'quality', 'balanced', 'budget', 'inherit']);
6
6
  const VALID_KNOWLEDGE_ADAPTERS = Object.freeze(['local']);
7
7
  const VALID_TIERS = Object.freeze(['haiku', 'sonnet', 'opus']);
8
+ const { VALID_ECONOMY_MODES } = require('./economy-mode.cjs');
8
9
 
9
10
  const SCHEMA = Object.freeze({
10
11
  scope: { type: 'enum', values: VALID_SCOPES, optional: true },
@@ -32,6 +33,8 @@ const SCHEMA = Object.freeze({
32
33
  research: { type: 'boolean', optional: true },
33
34
  plan_checker: { type: 'boolean', optional: true },
34
35
  verifier: { type: 'boolean', optional: true },
36
+ economy: { type: 'enum', values: VALID_ECONOMY_MODES, optional: true },
37
+ economy_critic: { type: 'boolean', optional: true },
35
38
  },
36
39
  },
37
40
  loop: {
@@ -54,6 +57,7 @@ const SCHEMA = Object.freeze({
54
57
  style_tier: { type: 'enum', values: VALID_TIERS, optional: true },
55
58
  tests_tier: { type: 'enum', values: VALID_TIERS, optional: true },
56
59
  acceptance_tier: { type: 'enum', values: VALID_TIERS, optional: true },
60
+ economy_tier: { type: 'enum', values: VALID_TIERS, optional: true },
57
61
  },
58
62
  },
59
63
  knowledge_adapter: { type: 'enum', values: VALID_KNOWLEDGE_ADAPTERS, optional: true },
@@ -0,0 +1,235 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const crypto = require('node:crypto');
6
+
7
+ const { projectStateDir, NubosPilotError } = require('./core.cjs');
8
+ const { slugify } = require('./layout.cjs');
9
+ const { extractFrontmatter } = require('./frontmatter.cjs');
10
+
11
+ // The economy-debt ledger records simplifications a reviewer chose to DEFER
12
+ // rather than fix now — the manual twin of the in-loop Economy critic
13
+ // (agents.economy ∈ {full,ultra}). It exists so "later" does not become "never":
14
+ // /np:simplify-review surfaces over-build, and what is not fixed this round is
15
+ // harvested here. Categories mirror the canonical four economy routes in
16
+ // lib/nubosloop.cjs::ROUTE_TABLE and agents/np-critic-economy.md — keep in sync.
17
+ const ECONOMY_CATEGORIES = Object.freeze([
18
+ 'over-engineering',
19
+ 'stdlib-reinvention',
20
+ 'native-duplication',
21
+ 'shrinkable',
22
+ ]);
23
+
24
+ const STATUSES = Object.freeze(['open', 'resolved']);
25
+ const MAX_NOTE_LENGTH = 500;
26
+ const ID_LENGTH = 7;
27
+
28
+ function debtRoot(cwd) {
29
+ return path.join(projectStateDir(cwd || process.cwd()), 'economy-debt');
30
+ }
31
+
32
+ function statusDir(status, cwd) {
33
+ return path.join(debtRoot(cwd), status);
34
+ }
35
+
36
+ function _entryId(file, line, category, note) {
37
+ const key = String(file) + ':' + String(line) + ':' + String(category) + ':' + String(note);
38
+ return crypto.createHash('sha1').update(key, 'utf-8').digest('hex').slice(0, ID_LENGTH);
39
+ }
40
+
41
+ function _composeMd(entry) {
42
+ const fm = [
43
+ '---',
44
+ 'id: ' + entry.id,
45
+ 'category: ' + entry.category,
46
+ 'file: ' + entry.file,
47
+ 'line: ' + entry.line,
48
+ 'created: ' + entry.created,
49
+ 'status: ' + entry.status,
50
+ ];
51
+ if (entry.resolved) fm.push('resolved: ' + entry.resolved);
52
+ fm.push('---');
53
+ return fm.join('\n') + '\n' + entry.note + '\n';
54
+ }
55
+
56
+ function _parseEntry(filePath) {
57
+ const raw = fs.readFileSync(filePath, 'utf-8');
58
+ const { frontmatter, body } = extractFrontmatter(raw);
59
+ const lineRaw = frontmatter.line;
60
+ const lineNum = Number.parseInt(lineRaw, 10);
61
+ return {
62
+ id: frontmatter.id != null ? String(frontmatter.id) : '',
63
+ category: frontmatter.category != null ? String(frontmatter.category) : '',
64
+ file: frontmatter.file != null ? String(frontmatter.file) : '',
65
+ line: Number.isFinite(lineNum) ? lineNum : 0,
66
+ created: frontmatter.created != null ? String(frontmatter.created) : '',
67
+ resolved: frontmatter.resolved != null ? String(frontmatter.resolved) : '',
68
+ status: frontmatter.status != null ? String(frontmatter.status) : '',
69
+ note: String(body || '').trim(),
70
+ path: filePath,
71
+ };
72
+ }
73
+
74
+ function _validateInput(input) {
75
+ const file = input && input.file != null ? String(input.file).trim() : '';
76
+ const note = input && input.note != null ? String(input.note).trim() : '';
77
+ const category = input && input.category != null ? String(input.category).trim() : '';
78
+ if (!note) {
79
+ throw new NubosPilotError(
80
+ 'economy-debt-missing-note',
81
+ 'economy-debt entry requires a non-empty note',
82
+ {},
83
+ );
84
+ }
85
+ if (note.length > MAX_NOTE_LENGTH) {
86
+ throw new NubosPilotError(
87
+ 'economy-debt-note-too-long',
88
+ 'economy-debt note must be <= ' + MAX_NOTE_LENGTH + ' chars',
89
+ { length: note.length },
90
+ );
91
+ }
92
+ if (!ECONOMY_CATEGORIES.includes(category)) {
93
+ throw new NubosPilotError(
94
+ 'economy-debt-invalid-category',
95
+ 'economy-debt category must be one of: ' + ECONOMY_CATEGORIES.join(', '),
96
+ { category, valid: ECONOMY_CATEGORIES.slice() },
97
+ );
98
+ }
99
+ let line = 0;
100
+ if (input && input.line != null && String(input.line).trim() !== '') {
101
+ line = Number.parseInt(input.line, 10);
102
+ if (!Number.isFinite(line) || line < 0) {
103
+ throw new NubosPilotError(
104
+ 'economy-debt-invalid-line',
105
+ 'economy-debt line must be a non-negative integer',
106
+ { line: input.line },
107
+ );
108
+ }
109
+ }
110
+ return { file, note, category, line };
111
+ }
112
+
113
+ /**
114
+ * Append a deferred-simplification entry to the open ledger. Idempotent: an
115
+ * identical (file, line, category, note) maps to the same id and is not
116
+ * duplicated — a re-harvest of the same finding is a no-op, returning the
117
+ * existing entry with `created: false`.
118
+ * @returns {{id, category, file, line, created, status, path, was_new: boolean}}
119
+ */
120
+ function addEntry(input, cwd) {
121
+ const { file, note, category, line } = _validateInput(input);
122
+ const id = _entryId(file, line, category, note);
123
+ const openDir = statusDir('open', cwd);
124
+ const resolvedDir = statusDir('resolved', cwd);
125
+ const slug = slugify(note).slice(0, 48) || 'entry';
126
+ const fileName = id + '-' + slug + '.md';
127
+
128
+ // already open, or already resolved — either way this finding is on record
129
+ const existingOpen = _findById(id, 'open', cwd);
130
+ if (existingOpen) return Object.assign({}, _parseEntry(existingOpen), { was_new: false });
131
+ const existingResolved = _findById(id, 'resolved', cwd);
132
+ if (existingResolved) return Object.assign({}, _parseEntry(existingResolved), { was_new: false });
133
+
134
+ fs.mkdirSync(openDir, { recursive: true });
135
+ const entry = {
136
+ id,
137
+ category,
138
+ file,
139
+ line,
140
+ created: new Date().toISOString(),
141
+ status: 'open',
142
+ note,
143
+ };
144
+ const target = path.join(openDir, fileName);
145
+ fs.writeFileSync(target, _composeMd(entry), 'utf-8');
146
+ void resolvedDir;
147
+ return Object.assign({}, entry, { path: target, was_new: true });
148
+ }
149
+
150
+ function _findById(id, status, cwd) {
151
+ const dir = statusDir(status, cwd);
152
+ let names;
153
+ try {
154
+ names = fs.readdirSync(dir);
155
+ } catch {
156
+ return null;
157
+ }
158
+ const hit = names.find((n) => n.endsWith('.md') && n.slice(0, ID_LENGTH) === id);
159
+ return hit ? path.join(dir, hit) : null;
160
+ }
161
+
162
+ /**
163
+ * List ledger entries. status: 'open' | 'resolved' | 'all'. Sorted by created
164
+ * ascending (oldest debt first — the longest-deferred is the most urgent).
165
+ */
166
+ function listEntries(status, cwd) {
167
+ const want = status || 'open';
168
+ const dirs = want === 'all' ? STATUSES.slice() : [want];
169
+ if (want !== 'all' && !STATUSES.includes(want)) {
170
+ throw new NubosPilotError(
171
+ 'economy-debt-invalid-status',
172
+ "economy-debt status must be 'open', 'resolved', or 'all'",
173
+ { status: want },
174
+ );
175
+ }
176
+ const out = [];
177
+ for (const d of dirs) {
178
+ const dir = statusDir(d, cwd);
179
+ let names;
180
+ try {
181
+ names = fs.readdirSync(dir);
182
+ } catch {
183
+ continue;
184
+ }
185
+ for (const n of names) {
186
+ if (!n.endsWith('.md')) continue;
187
+ out.push(_parseEntry(path.join(dir, n)));
188
+ }
189
+ }
190
+ out.sort((a, b) => (a.created < b.created ? -1 : a.created > b.created ? 1 : 0));
191
+ return out;
192
+ }
193
+
194
+ /**
195
+ * Mark an open entry resolved: stamp `resolved` + flip status, then move the
196
+ * file from open/ to resolved/. Throws economy-debt-not-found if no open entry
197
+ * carries the id.
198
+ */
199
+ function resolveEntry(id, cwd) {
200
+ const wanted = String(id || '').trim();
201
+ if (!wanted) {
202
+ throw new NubosPilotError('economy-debt-missing-id', 'resolve requires an entry id', {});
203
+ }
204
+ const src = _findById(wanted, 'open', cwd);
205
+ if (!src) {
206
+ throw new NubosPilotError(
207
+ 'economy-debt-not-found',
208
+ 'no open economy-debt entry with id: ' + wanted,
209
+ { id: wanted },
210
+ );
211
+ }
212
+ const entry = _parseEntry(src);
213
+ entry.resolved = new Date().toISOString();
214
+ entry.status = 'resolved';
215
+ const resolvedDir = statusDir('resolved', cwd);
216
+ fs.mkdirSync(resolvedDir, { recursive: true });
217
+ const target = path.join(resolvedDir, path.basename(src));
218
+ fs.writeFileSync(target, _composeMd(entry), 'utf-8');
219
+ fs.rmSync(src);
220
+ return Object.assign({}, entry, { path: target });
221
+ }
222
+
223
+ module.exports = {
224
+ ECONOMY_CATEGORIES,
225
+ STATUSES,
226
+ MAX_NOTE_LENGTH,
227
+ debtRoot,
228
+ statusDir,
229
+ addEntry,
230
+ listEntries,
231
+ resolveEntry,
232
+ _entryId,
233
+ _parseEntry,
234
+ _composeMd,
235
+ };