From 0fc9c97b40437f88d5858e251c2b67390220a53e Mon Sep 17 00:00:00 2001 From: Henrique Franze <53534000+henrique-franze@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:04:52 -0300 Subject: [PATCH] feat(tools): add Pending.ts, open criteria across all ISAs On-demand, read-only CLI that counts open, closed and dropped criteria (plus unchecked Remaining Work items) across the ISAs Pursuit reads. Per discussion #2352: - runs only when called: no hook, no SessionStart wiring, no schedule - criteria come from IsaFrontier's parseClaims; closed phases from Pursuit's isaClosed (no new phase list) - default roots are Pursuit's isaDirs(): MEMORY/WORK plus system ISAs, read with the same //ISA.md shape as liveIsas() - output says criteria Pursuit.ts: export isaClosed and isaDirs so Pending imports them instead of copying. Tests run on synthetic ISAs in temp dirs. --- .../DOCUMENTATION/Pending/PendingSystem.md | 102 +++++++ .../LIFEOS/DOCUMENTATION/Tools/Tools.md | 25 ++ LifeOS/install/LIFEOS/IDEALSTATE/Pursuit.ts | 4 +- LifeOS/install/LIFEOS/TOOLS/Pending.test.ts | 283 ++++++++++++++++++ LifeOS/install/LIFEOS/TOOLS/Pending.ts | 263 ++++++++++++++++ 5 files changed, 675 insertions(+), 2 deletions(-) create mode 100644 LifeOS/install/LIFEOS/DOCUMENTATION/Pending/PendingSystem.md create mode 100644 LifeOS/install/LIFEOS/TOOLS/Pending.test.ts create mode 100644 LifeOS/install/LIFEOS/TOOLS/Pending.ts diff --git a/LifeOS/install/LIFEOS/DOCUMENTATION/Pending/PendingSystem.md b/LifeOS/install/LIFEOS/DOCUMENTATION/Pending/PendingSystem.md new file mode 100644 index 0000000000..91f3fe8f59 --- /dev/null +++ b/LifeOS/install/LIFEOS/DOCUMENTATION/Pending/PendingSystem.md @@ -0,0 +1,102 @@ +--- +last_updated: 2026-11-08T00:00:00Z +last_updated_by: da +convention: lifeos-freshness-v1 +version: 1.0.0 +--- + +# Pending — what is still open across all ISAs + +> The hill-climb is only legible if you can see the remaining distance. Every ISA already states its open criteria; `Pending.ts` adds them up across ISAs, so "what is still open?" has one deterministic answer instead of a manual walk through folders. + +## What it is + +`LIFEOS/TOOLS/Pending.ts` reads the ISAs Pursuit reads and reports, per ISA: open, closed and dropped criteria, unchecked `## Remaining Work` items, phase, last-updated age, and a group label. It runs only when called (no hook, no SessionStart wiring, no schedule) and is read-only: it never writes an ISA. + +An ISA's backlog is the union of its open criteria and its unchecked `## Remaining Work` items (ISAFormat.md v2.19.0). Pending reports the two separately (`open` and `remaining`) and treats either as open work for anomalies. + +**Relation to existing tools.** `IsaFrontier.ts` (`status`, `frontier`) answers "what can I take next?" for one ISA. Pursuit (`LIFEOS/IDEALSTATE/Pursuit.ts`) reads each ISA's phase and `serves:` to say what is moving each ideal-state target. Pending answers "how many criteria are still open?" across all ISAs; nothing else counts them across ISAs. + +## What it reuses + +Pending carries no parser or phase list of its own: + +| What | From | +|---|---| +| Criteria | `parseClaims` in `LIFEOS/TOOLS/IsaFrontier.ts` | +| Default roots | `isaDirs()` in `LIFEOS/IDEALSTATE/Pursuit.ts`: `MEMORY/WORK` plus the `LIFEOS` directory for system ISAs, or `IDEALSTATE_ISA_DIR` when set | +| Which phases are closed | `isaClosed()` in `Pursuit.ts`: the `cairn` bracket from `LIFEOS/TOOLS/ascent.ts` (`complete`, `learn`) plus Pursuit's stopped phases (`abandoned`, `closed`, `cancelled`, `dropped`, `archived`) | +| ISA discovery | `//ISA.md`, one level deep, the same shape as Pursuit's `liveIsas()` | + +Frontmatter is read with the `isa-utils` rule (trailing YAML comments stripped, `#` inside quotes kept), written out locally so the CLI stays off the hook graph, as `IsaFrontier.ts` does. + +## How criteria are counted + +Everything here is `parseClaims` behaviour; the tests in `Pending.test.ts` pin each line. + +- Criteria are read from every criteria section: `## Criteria`, `## ISC Criteria`, `## Claims` (legacy), `## IDEAL STATE CRITERIA`, `### Criteria`, `## Features`, `## Bridge Criteria`, and `## Anti-criteria` (or legacy `## Anti-claims`). Each section ends at the next `#` or `##` heading or a `---` line; `###` subheadings (feature blocks) do not end it. Other sections are not read. +- A line counts when it carries a criterion ID: a checkbox or plain bullet, or a table row. Checkboxes inside code fences are not criteria. +- A parent with nested children (such as `ISC-1` over `ISC-1.1` and `ISC-1.2`, or a `[container]`) is verified through them, so only the leaves are counted, as in `lib/IsaClaims.ts`. `parseClaims` returns the parents too, for dependency edges; Pending keeps the leaves. +- **Closed** = checked (`- [x]`, or a table status cell `passed`, `closed`, `complete`, `done`, `[x]`, `✅`) and not dropped. **Open** = not closed and not dropped; `[DEFERRED-VERIFY]` and partial `[~]` criteria are open. +- **Dropped** = the description contains `[DROPPED`; dropped criteria are neither open nor closed, checked or not. +- CRLF and CR line endings are normalised to LF first. +- Age is the `updated` frontmatter field, falling back to the file's mtime. Only top-level frontmatter keys are read. +- `## Remaining Work` items follow the same section and fence rules: unchecked `- [ ]` lines until the next `#`/`##` heading or `---`, fenced lines skipped. + +## Run + +```bash +bun ~/.claude/LIFEOS/TOOLS/Pending.ts # human-readable +bun ~/.claude/LIFEOS/TOOLS/Pending.ts --json # stable machine shape +bun ~/.claude/LIFEOS/TOOLS/Pending.ts --root ~/Projects --group-field team --idle-days 30 +``` + +`--help` / `-h` prints usage and exits 0. A completed scan exits 0 (anomalies are findings, not failures). A bad argument (unknown flag, `--root` / `--group-field` / `--idle-days` without a value, or a non-positive or non-numeric `--idle-days`) prints a message to stderr and exits 2. + +## Config + +Follows the standard config path (`Config/ConfigSystem.md`): an optional `pending` object in `settings.json`, merged from `settings.system.json` plus the USER overlay. Flags override settings; settings override defaults. + +| Key | Flag | Default | Meaning | +|---|---|---|---| +| `roots` | `--root` (repeatable) | Pursuit's `isaDirs()` | Directories whose `/ISA.md` files are read. `~` and `$HOME` expand. A `roots` array in the USER overlay **replaces** the default, so list the defaults too when extending. | +| `groupField` | `--group-field` | `project` | Frontmatter field used as the group label. A missing or empty field puts the ISA in the literal group `unlabeled`. | +| `idleDays` | `--idle-days` | `14` | Open ISAs not updated for more than this many days are flagged idle. | + +## Anomalies + +Generic only; anything domain-specific belongs in a wrapper. + +| `kind` | Raised when | +|---|---| +| `closed_with_open_criteria` | the phase is closed (`isaClosed`) but at least one criterion or Remaining Work item is still open | +| `idle_with_open_criteria` | the phase is not closed, criteria or Remaining Work items are open, and age exceeds `idleDays` | +| `unreadable` | the file exists but cannot be read | +| `no_frontmatter` | the ISA has no YAML frontmatter block (it is still counted; phase is `unknown`) | + +A nonexistent root is not an anomaly of an ISA; it is listed in `missingRoots` and the scan continues. + +## JSON shape + +```json +{ + "generatedAt": "ISO-8601", + "config": { "roots": ["..."], "groupField": "project", "idleDays": 14 }, + "missingRoots": ["..."], + "totals": { "isas": 0, "open": 0, "closed": 0, "remaining": 0 }, + "groups": [{ "group": "unlabeled", "isas": 0, "open": 0, "closed": 0, "remaining": 0 }], + "isas": [{ "path": "...", "group": "...", "phase": "build", "open": 0, "closed": 0, "dropped": 0, "updated": "ISO-8601", "ageDays": 0, "remaining": 0 }], + "anomalies": [{ "path": "...", "kind": "idle_with_open_criteria", "detail": "..." }] +} +``` + +`open`, `closed` and `dropped` count criteria. Groups are sorted by open plus remaining count (descending), then name. Keys are additive-only; existing keys keep their meaning. + +## Tests + +`LIFEOS/TOOLS/Pending.test.ts` (`bun test LIFEOS/TOOLS/Pending.test.ts`), every fixture a synthetic ISA in a temp dir: + +- **Pending**: counts, each anomaly, every closed phase through `isaClosed`, `unlabeled` and a configurable group field, no-frontmatter, unreadable file, missing root, JSON key order, settings loading and Pursuit's default roots. +- **Pending criteria parsing (parseClaims)**: heading variants, parents counted through their leaves, `[DEFERRED-VERIFY]`, Anti-criteria and Bridge Criteria, code fences, table rows, sections outside the criteria sections, checked-and-dropped, frontmatter comments and nesting, CRLF, `## Remaining Work` with fences and section ends. +- **Pending traversal and output**: one-level discovery, one ISA through two roots or a symlink, human-readable output. +- **Pending CLI**: spawns the CLI for `--help`/`-h`, a `--json` scan, the default roots, and exit code 2 with a stderr message for each bad argument. diff --git a/LifeOS/install/LIFEOS/DOCUMENTATION/Tools/Tools.md b/LifeOS/install/LIFEOS/DOCUMENTATION/Tools/Tools.md index 51d644d2e7..d668d09035 100644 --- a/LifeOS/install/LIFEOS/DOCUMENTATION/Tools/Tools.md +++ b/LifeOS/install/LIFEOS/DOCUMENTATION/Tools/Tools.md @@ -716,6 +716,31 @@ bun ~/.claude/LIFEOS/TOOLS/ArchitectureSummaryGenerator.ts check --- +## Pending.ts - Open Criteria Across All ISAs + +**Location:** `~/.claude/LIFEOS/TOOLS/Pending.ts` + +Read the ISAs Pursuit reads (`MEMORY/WORK` plus the system ISAs) and report open, closed and dropped criteria plus unchecked `## Remaining Work` items per ISA, grouped by a frontmatter label. Criteria come from `parseClaims` and closed phases from Pursuit's `isaClosed`. Flags closed-with-open-work, idle, unreadable and frontmatter-less ISAs. On demand and read-only. See `LIFEOS/DOCUMENTATION/Pending/PendingSystem.md`. + +**Usage:** +```bash +# Human-readable report +bun ~/.claude/LIFEOS/TOOLS/Pending.ts + +# Stable machine-readable shape +bun ~/.claude/LIFEOS/TOOLS/Pending.ts --json + +# Override roots, group field and idle threshold +bun ~/.claude/LIFEOS/TOOLS/Pending.ts --root ~/Projects --group-field team --idle-days 30 +``` + +**When to Use:** +- "what is still open across my work?" +- "which ISAs are marked complete but still have open criteria?" +- Before a weekly review of unfinished work + +--- + ## Doctor.ts - Capability Prober & Health Manifest **Location:** `~/.claude/LIFEOS/TOOLS/Doctor.ts` diff --git a/LifeOS/install/LIFEOS/IDEALSTATE/Pursuit.ts b/LifeOS/install/LIFEOS/IDEALSTATE/Pursuit.ts index 6961f9705b..ef0a41d628 100644 --- a/LifeOS/install/LIFEOS/IDEALSTATE/Pursuit.ts +++ b/LifeOS/install/LIFEOS/IDEALSTATE/Pursuit.ts @@ -39,7 +39,7 @@ export type PursuitSummary = { targets: Tally; goals: Tally }; /** Done is whatever ascent.ts says is done; these are the ways an ISA stops without finishing. */ const STOPPED_PHASES = new Set(["abandoned", "closed", "cancelled", "dropped", "archived"]); -const isaClosed = (phase: string): boolean => phaseBracket(phase) === "cairn" || STOPPED_PHASES.has(phase); +export const isaClosed = (phase: string): boolean => phaseBracket(phase) === "cairn" || STOPPED_PHASES.has(phase); /** An unscheduled or custom-cron workflow counts as moving something only if it ran this recently. */ export const UNSCHEDULED_FRESH_DAYS = 45; const RUNNING_INSTALLS = new Set(["loaded", "deployed"]); @@ -91,7 +91,7 @@ export function liveWorkflows(): WorkflowInfo[] { return out; } -function isaDirs(): string[] { +export function isaDirs(): string[] { if (process.env.IDEALSTATE_ISA_DIR) return [process.env.IDEALSTATE_ISA_DIR]; return [lifeosPath("MEMORY", "WORK"), lifeosPath()]; } diff --git a/LifeOS/install/LIFEOS/TOOLS/Pending.test.ts b/LifeOS/install/LIFEOS/TOOLS/Pending.test.ts new file mode 100644 index 0000000000..28a5bc3aac --- /dev/null +++ b/LifeOS/install/LIFEOS/TOOLS/Pending.test.ts @@ -0,0 +1,283 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { isaDirs } from '../IDEALSTATE/Pursuit'; +import { UNLABELED, formatHuman, loadConfig, parseArgs, scan, type PendingConfig } from './Pending'; + +const NOW = new Date('2030-06-01T00:00:00Z'); +let root: string; + +function isa(name: string, fm: string | null, claims: string[]): string { + const dir = join(root, name); + mkdirSync(dir, { recursive: true }); + const head = fm === null ? '' : `---\n${fm}\n---\n`; + const path = join(dir, 'ISA.md'); + writeFileSync(path, `${head}# Title\n\n## Claims\n\n${claims.join('\n')}\n\n## Decisions\n`); + return path; +} +const cfg = (over: Partial = {}): PendingConfig => ({ roots: [root], groupField: 'project', idleDays: 14, ...over }); + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'pending-')); + isa('a', 'phase: climbing\nproject: alpha\nupdated: 2030-05-30T00:00:00Z', ['- [x] ISC-1: done', '- [ ] ISC-2: todo', '- [ ] ISC-3: todo too', '- [ ] ISC-4: [DROPPED] gone']); + isa('b', 'phase: complete\nproject: alpha\nupdated: 2030-05-31T00:00:00Z', ['- [x] ISC-1: done', '- [ ] ISC-2: forgotten']); + isa('c', 'phase: climbing\nupdated: 2030-01-01T00:00:00Z', ['- [ ] ISC-1: stale']); + isa('d', null, ['- [x] ISC-1: done']); +}); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +describe('Pending', () => { + let r: ReturnType; + beforeAll(() => { r = scan(cfg(), NOW); }); + const by = (n: string) => r.isas.find((i) => i.path === join(root, n, 'ISA.md'))!; + + test('counts open, closed and dropped criteria', () => { + expect(by('a')).toMatchObject({ open: 2, closed: 1, dropped: 1, remaining: 0, phase: 'climbing', ageDays: 2 }); + expect(r.totals).toEqual({ isas: 4, open: 4, closed: 3, remaining: 0 }); + }); + + test('a closed phase with open criteria is an anomaly', () => { + expect(r.anomalies.filter((a) => a.kind === 'closed_with_open_criteria').map((a) => a.path)).toEqual([by('b').path]); + }); + + test.each(['complete', 'learn', 'abandoned', 'Archived'])('phase %s counts as closed, using Pursuit\'s isaClosed', (phase) => { + const i = one(`closed-${phase}`, `---\nphase: ${phase}\nupdated: 2030-05-30T00:00:00Z\n---\n## Criteria\n\n- [ ] ISC-1: open\n`); + const rep = scan(cfg({ roots: [join(root, 'raw', `closed-${phase}`)] }), NOW); + expect(rep.anomalies.map((a) => a.kind)).toEqual(['closed_with_open_criteria']); + expect(i.phase).toBe(phase.toLowerCase()); + }); + + test('idle ISA with open criteria is an anomaly; recent and closed ones are not', () => { + const idle = r.anomalies.filter((a) => a.kind === 'idle_with_open_criteria'); + expect(idle.map((a) => a.path)).toEqual([by('c').path]); + expect(idle.map((a) => a.path)).not.toContain(by('a').path); // recent + expect(idle.map((a) => a.path)).not.toContain(by('b').path); // closed + expect(scan(cfg({ idleDays: 400 }), NOW).anomalies.some((a) => a.kind === 'idle_with_open_criteria')).toBe(false); + }); + + test('missing group field falls into "unlabeled"; field name is configurable', () => { + expect(by('c').group).toBe(UNLABELED); + expect(by('a').group).toBe('alpha'); + expect(scan(cfg({ groupField: 'phase' }), NOW).groups.map((g) => g.group).sort()).toEqual(['climbing', 'complete', UNLABELED].sort()); + }); + + test('ISA without frontmatter is flagged and still counted, using file mtime for age', () => { + expect(r.anomalies.some((a) => a.kind === 'no_frontmatter' && a.path === by('d').path)).toBe(true); + expect(by('d')).toMatchObject({ phase: 'unknown', group: UNLABELED, open: 0, closed: 1 }); + const old = new Date('2030-04-01T00:00:00Z'); + utimesSync(by('d').path, old, old); + expect(scan(cfg(), NOW).isas.find((i) => i.path === by('d').path)!.ageDays).toBe(61); + }); + + test('unreadable ISA is flagged, not fatal', () => { + if (process.getuid?.() === 0) return; + const p = isa('e', 'phase: climbing', ['- [ ] ISC-1: x']); + chmodSync(p, 0o000); + const rep = scan(cfg(), NOW); + chmodSync(p, 0o644); + expect(rep.anomalies.some((a) => a.kind === 'unreadable' && a.path === p)).toBe(true); + }); + + test('nonexistent root is reported, not thrown', () => { + const rep = scan(cfg({ roots: [join(root, 'nope')] }), NOW); + expect(rep.missingRoots).toEqual([join(root, 'nope')]); + expect(rep.isas).toEqual([]); + }); + + test('--json shape is stable', () => { + const { config, json } = parseArgs(['--json', '--root', root, '--idle-days', '30'], cfg()); + expect(json).toBe(true); + expect(config.idleDays).toBe(30); + const out = JSON.parse(JSON.stringify(scan(config, NOW))); + expect(Object.keys(out)).toEqual(['generatedAt', 'config', 'missingRoots', 'totals', 'groups', 'isas', 'anomalies']); + expect(Object.keys(out.isas[0])).toEqual(['path', 'group', 'phase', 'open', 'closed', 'dropped', 'updated', 'ageDays', 'remaining']); + expect(Object.keys(out.groups[0])).toEqual(['group', 'isas', 'open', 'closed', 'remaining']); + expect(Object.keys(out.totals)).toEqual(['isas', 'open', 'closed', 'remaining']); + expect(Object.keys(out.anomalies[0])).toEqual(['path', 'kind', 'detail']); + }); + + test('settings.json `pending` block is read; absent file yields defaults with Pursuit\'s roots', () => { + const sp = join(root, 'settings.json'); + writeFileSync(sp, JSON.stringify({ pending: { roots: [root], groupField: 'team', idleDays: 3 } })); + expect(loadConfig(sp)).toEqual({ roots: [root], groupField: 'team', idleDays: 3 }); + expect(loadConfig(join(root, 'absent.json'))).toEqual({ roots: isaDirs(), groupField: 'project', idleDays: 14 }); + }); +}); + +// ── Fixtures written as raw content (heading variants, CRLF, fences, ...) ── +function raw(name: string, content: string): string { + const dir = join(root, 'raw', name, 'isa'); // //ISA.md, the shape scan() reads + mkdirSync(dir, { recursive: true }); + const path = join(dir, 'ISA.md'); + writeFileSync(path, content); + return path; +} +const one = (name: string, content: string) => { + const p = raw(name, content); + return scan(cfg({ roots: [join(root, 'raw', name)] }), NOW).isas.find((i) => i.path === p)!; +}; +const FM = '---\nphase: climbing\nupdated: 2030-05-30T00:00:00Z\n---\n'; + +describe('Pending criteria parsing (parseClaims)', () => { + test.each(['## Claims', '## Criteria', '## ISC Criteria', '## Features'])('heading variant %s is recognised', (h) => { + const i = one(`h-${h.replace(/\W+/g, '')}`, `${FM}# T\n\n${h}\n\n- [x] ISC-1: a\n- [ ] ISC-2: b\n\n## Decisions\n`); + expect([i.open, i.closed]).toEqual([1, 1]); + }); + + test('a parent with nested children is counted through its leaves; [DEFERRED-VERIFY] counts as open', () => { + const i = one('nested', `${FM}## Criteria\n\n- [ ] ISC-1: parent\n - [x] ISC-1.1: leaf done\n - [ ] ISC-1.2: leaf open\n- [ ] ISC-2: [DEFERRED-VERIFY] needs prod\n`); + expect([i.open, i.closed, i.dropped]).toEqual([2, 1, 0]); + }); + + test('a fully closed split ISA is closed, with no anomaly', () => { + const p = raw('split', `---\nphase: complete\nupdated: 2030-05-30T00:00:00Z\n---\n## Criteria\n\n- [ ] ISC-1: [container] parent\n - [x] ISC-1.1: a\n - [x] ISC-1.2: b\n- [ ] ISC-2: plain parent\n - [x] ISC-2.1: c\n`); + const rep = scan(cfg({ roots: [join(root, 'raw', 'split')] }), NOW); + expect(rep.isas.find((i) => i.path === p)).toMatchObject({ open: 0, closed: 3 }); + expect(rep.anomalies).toEqual([]); + }); + + test('## Anti-criteria and ## Bridge Criteria are read like criteria', () => { + const i = one('anti-bridge', `${FM}## Criteria\n\n- [x] ISC-1: a\n\n## Anti-criteria\n\n- [ ] ISC-A1: must not happen\n\n## Bridge Criteria\n\n- [x] ISC-3: Bridge: holds\n`); + expect([i.open, i.closed]).toEqual([1, 2]); + }); + + test('checkboxes inside code fences are not criteria', () => { + const i = one('fence', `${FM}## Criteria\n\n- [ ] ISC-1: real\n\n\`\`\`\n- [ ] ISC-2: in a fence\n\`\`\`\n`); + expect(i.open).toBe(1); + }); + + test('table rows with an ID are criteria; a passed status cell closes one', () => { + const i = one('table', `${FM}## Criteria\n\n| id | criterion | status |\n|---|---|---|\n| ISC-1 | a | passed |\n| ISC-2 | b | open |\n`); + expect([i.open, i.closed]).toEqual([1, 1]); + }); + + test('sections outside the criteria sections are not read', () => { + const i = one('outside', `${FM}## Problem\n\n- [ ] ISC-9: not a criterion here\n\n## Criteria\n\n- [ ] ISC-1: a\n\n## Decisions\n\n- [ ] ISC-8: nor here\n`); + expect(i.open).toBe(1); + }); + + test('a checked claim carrying [DROPPED] is dropped, not closed', () => { + const i = one('dropped-checked', `${FM}## Claims\n\n- [x] ISC-1: [DROPPED] superseded\n- [x] ISC-2: done\n`); + expect([i.open, i.closed, i.dropped]).toEqual([0, 1, 1]); + }); + + test('trailing YAML comments are stripped like isa-utils; # inside quotes is kept', () => { + const i = one('fm-comment', `---\nphase: complete # REQUIRED\nproject: "fix #12" # note\nupdated: 2030-05-30T00:00:00Z\n---\n## Claims\n\n- [ ] ISC-1: open\n`); + expect(i).toMatchObject({ phase: 'complete', group: 'fix #12' }); + }); + + test('CRLF files parse like LF files, frontmatter included', () => { + const lf = `---\nphase: complete\nproject: crlf\nupdated: 2030-05-30T00:00:00Z\n---\n## Claims\n\n- [x] ISC-1: a\n- [ ] ISC-2: b\n\n## Remaining Work\n\n- [ ] follow-up\n`; + const i = one('crlf', lf.replace(/\n/g, '\r\n')); + expect(i).toMatchObject({ open: 1, closed: 1, remaining: 1, phase: 'complete', group: 'crlf' }); + }); + + test('Remaining Work skips fenced items and ends at a # heading or ---', () => { + const i = one('remaining-fence', `${FM}## Criteria\n\n- [x] ISC-1: a\n\n## Remaining Work\n\n- [ ] real\n\n\`\`\`\n- [ ] in a fence\n\`\`\`\n\n### sub\n\n- [ ] under a subheading\n\n---\n\n- [ ] after a rule\n`); + expect(i.remaining).toBe(2); + }); + + test('indented frontmatter keys do not override top-level ones', () => { + const i = one('fm-nested', `---\nphase: build\nmeta:\n phase: complete\nupdated: 2030-05-30T00:00:00Z\n---\n## Criteria\n\n- [ ] ISC-1: open\n`); + expect(i.phase).toBe('build'); + }); + + test('Remaining Work unchecked items are a separate field and keep ISAs "open"', () => { + const p = raw('remaining', `---\nphase: complete\nupdated: 2030-05-30T00:00:00Z\n---\n## Claims\n\n- [x] ISC-1: a\n\n## Remaining Work\n\n- [ ] one\n- [x] done already\n- [ ] two\n\n## Decisions\n\n- [ ] not remaining work\n`); + const rep = scan(cfg({ roots: [join(root, 'raw', 'remaining')] }), NOW); + expect(rep.isas[0]).toMatchObject({ open: 0, closed: 1, remaining: 2 }); + expect(rep.totals.remaining).toBe(2); + expect(rep.groups[0].remaining).toBe(2); + expect(rep.anomalies.map((a) => [a.kind, a.path])).toEqual([['closed_with_open_criteria', p]]); + const idle = raw('remaining-idle', `---\nphase: climbing\nupdated: 2030-01-01T00:00:00Z\n---\n## Claims\n\n- [x] ISC-1: a\n\n## Remaining Work\n\n- [ ] one\n`); + expect(scan(cfg({ roots: [join(root, 'raw', 'remaining-idle')] }), NOW).anomalies.map((a) => [a.kind, a.path])).toEqual([['idle_with_open_criteria', idle]]); + }); +}); + +describe('Pending traversal and output', () => { + test('reads //ISA.md one level deep, like Pursuit; a deeper ISA is not counted', () => { + const base = mkdtempSync(join(tmpdir(), 'pending-depth-')); + try { + mkdirSync(join(base, 'task', 'nested'), { recursive: true }); + writeFileSync(join(base, 'task', 'ISA.md'), `${FM}## Criteria\n\n- [ ] ISC-1: x\n`); + writeFileSync(join(base, 'task', 'nested', 'ISA.md'), `${FM}## Criteria\n\n- [ ] ISC-1: y\n`); + writeFileSync(join(base, 'ISA.md'), `${FM}## Criteria\n\n- [ ] ISC-1: z\n`); + const rep = scan(cfg({ roots: [base] }), NOW); + expect(rep.isas.map((i) => i.path)).toEqual([join(base, 'task', 'ISA.md')]); + } finally { rmSync(base, { recursive: true, force: true }); } + }); + + test('one ISA reached through two roots or a symlink is reported once', () => { + const base = mkdtempSync(join(tmpdir(), 'pending-sym-')); + try { + mkdirSync(join(base, 'real', 'proj'), { recursive: true }); + writeFileSync(join(base, 'real', 'proj', 'ISA.md'), `${FM}## Criteria\n\n- [ ] ISC-1: x\n`); + mkdirSync(join(base, 'scan')); + symlinkSync(join(base, 'real', 'proj'), join(base, 'scan', 'linked')); + const rep = scan(cfg({ roots: [join(base, 'scan'), join(base, 'real')] }), NOW); + expect(rep.isas.length).toBe(1); + expect(rep.isas[0].open).toBe(1); + } finally { rmSync(base, { recursive: true, force: true }); } + }); + + test('human output shows totals, group headers, per-ISA counts and anomalies', () => { + const out = formatHuman(scan(cfg(), NOW)); + expect(out).toContain('Pending:'); + expect(out).toContain('alpha ('); + expect(out).toContain('remaining'); + expect(out).toContain('Anomalies'); + expect(out).toContain('[closed_with_open_criteria]'); + expect(out).toContain('criteria'); + expect(out).not.toMatch(/claim/i); + }); +}); + +describe('Pending CLI', () => { + const cli = join(import.meta.dir, 'Pending.ts'); + // An empty config root: no settings.json, and LIFEOS resolves under it (CLAUDE_CONFIG_DIR outranks LIFEOS_DIR in Paths.ts). + const configRoot = () => join(root, 'claude-none'); + const lifeos = () => join(configRoot(), 'LIFEOS'); + const env = () => { + const e: Record = { ...process.env, CLAUDE_CONFIG_DIR: configRoot() }; + for (const k of ['IDEALSTATE_ISA_DIR', 'LIFEOS_DIR', 'LIFEOS_SKILLS_DIR', 'CLAUDE_PLUGIN_ROOT']) delete e[k]; + return e; + }; + const run = (...args: string[]) => Bun.spawnSync(['bun', cli, ...args], { env: env() }); + const err = (r: ReturnType) => r.stderr.toString(); + + test('--help and -h print usage and exit 0', () => { + for (const f of ['--help', '-h']) { + const r = run(f); + expect(r.exitCode).toBe(0); + expect(r.stdout.toString()).toContain('Usage: bun LIFEOS/TOOLS/Pending.ts'); + } + }); + + test('a completed scan exits 0 and --json parses', () => { + const r = run('--json', '--root', root); + expect(r.exitCode).toBe(0); + expect(JSON.parse(r.stdout.toString()).totals.isas).toBeGreaterThan(0); + }); + + test('with no --root and no settings, the roots are Pursuit\'s: MEMORY/WORK plus the LIFEOS dir for system ISAs', () => { + const r = run('--json'); + expect(r.exitCode).toBe(0); + expect(JSON.parse(r.stdout.toString()).config.roots).toEqual([join(lifeos(), 'MEMORY', 'WORK'), lifeos()]); + }); + + test.each([ + [['--idle-days'], '--idle-days requires a value'], + [['--idle-days', 'abc'], '--idle-days requires a positive number'], + [['--idle-days', '0'], '--idle-days requires a positive number'], + [['--idle-days', '--json'], '--idle-days requires a value'], + [['--root'], '--root requires a value'], + [['--group-field'], '--group-field requires a value'], + [['--nope'], 'unknown argument: --nope'], + ])('bad argument %j exits 2 with a message on stderr', (args, msg) => { + const r = run(...args); + expect(r.exitCode).toBe(2); + expect(err(r)).toContain(msg); + expect(r.stdout.toString()).toBe(''); + }); +}); diff --git a/LifeOS/install/LIFEOS/TOOLS/Pending.ts b/LifeOS/install/LIFEOS/TOOLS/Pending.ts new file mode 100644 index 0000000000..f126d693a5 --- /dev/null +++ b/LifeOS/install/LIFEOS/TOOLS/Pending.ts @@ -0,0 +1,263 @@ +#!/usr/bin/env bun +/** + * Pending.ts — "what is still open across all my work?" + * + * Reads every ISA under the roots Pursuit reads (task ISAs in MEMORY/WORK plus + * the system ISAs) and reports, per ISA, open vs closed criteria, unchecked + * Remaining Work items, phase, age and a group label, with a few generic + * anomalies. Runs only when called; read-only, it never writes an ISA. + * + * bun LIFEOS/TOOLS/Pending.ts [--json] [--root ]... [--group-field ] [--idle-days ] + * + * Reuses, never copies: criteria come from IsaFrontier's parseClaims, the + * default roots from Pursuit's isaDirs, and "closed" from Pursuit's isaClosed. + * Optional config under the `pending` key of settings.json (Config/ConfigSystem.md): + * { "pending": { "roots": ["~/Projects"], "groupField": "project", "idleDays": 14 } } + * Flags override settings; settings override defaults. Doc: Pending/PendingSystem.md. + * + * Proposed in discussion #2352 (@henrique-franze). + * + * @version 1.0.0 + */ +import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'fs'; +import { join } from 'path'; +import { isaClosed, isaDirs } from '../IDEALSTATE/Pursuit'; +import { parseClaims } from './IsaFrontier'; +import { expandPath, getSettingsPath } from './Paths'; + +const ARTIFACT_FILENAME = 'ISA.md'; +export const UNLABELED = 'unlabeled'; +const DAY_MS = 86_400_000; + +/** `phase: complete # note` → `complete`; a `#` inside quotes is kept. Same rule as isa-utils. */ +function stripTrailingYamlComment(raw: string): string { + let inSingle = false, inDouble = false; + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + if (ch === "'" && !inDouble) inSingle = !inSingle; + else if (ch === '"' && !inSingle) inDouble = !inDouble; + else if (ch === '#' && !inSingle && !inDouble && (i === 0 || raw[i - 1] === ' ' || raw[i - 1] === '\t')) return raw.slice(0, i).trimEnd(); + } + return raw; +} + +/** Flat top-level `key: value` frontmatter, trailing comments and quotes stripped. Expects LF input. */ +function parseFrontmatter(content: string): Record | null { + const match = content.match(/^---\n([\s\S]*?)\n---/); + if (!match) return null; + const fm: Record = {}; + for (const line of match[1].split('\n')) { + const kv = line.match(/^([A-Za-z_][\w-]*):(.*)$/); + if (kv) fm[kv[1]] = stripTrailingYamlComment(kv[2].trim()).replace(/^["']|["']$/g, ''); + } + return fm; +} + +/** Unchecked `- [ ]` items in `## Remaining Work` (ISAFormat.md v2.19.0: the backlog is open criteria plus these). */ +export function countRemaining(content: string): number { + const m = /^##\s+Remaining Work\b[^\n]*$/im.exec(content); + if (!m) return 0; + const rest = content.slice(m.index + m[0].length); + const end = rest.match(/\n(?:#{1,2}\s|---\s*(?:\n|$))/); + let fenced = false; + let n = 0; + // Same section and fence rules as the criteria parser: `#`/`##` or `---` ends it, fenced lines are skipped. + for (const l of (end ? rest.slice(0, end.index) : rest).split('\n')) { + if (/^\s*(?:`{3,}|~{3,})/.test(l)) fenced = !fenced; + else if (!fenced && /^\s*- \[ \]/.test(l)) n++; + } + return n; +} + +export interface PendingConfig { + roots: string[]; + groupField: string; + idleDays: number; +} + +export type AnomalyKind = 'closed_with_open_criteria' | 'idle_with_open_criteria' | 'unreadable' | 'no_frontmatter'; + +export interface Anomaly { path: string; kind: AnomalyKind; detail: string } + +export interface IsaReport { + path: string; + group: string; + phase: string; + open: number; + closed: number; + dropped: number; + updated: string | null; + ageDays: number | null; + remaining: number; +} + +export interface PendingReport { + generatedAt: string; + config: PendingConfig; + missingRoots: string[]; + totals: { isas: number; open: number; closed: number; remaining: number }; + groups: { group: string; isas: number; open: number; closed: number; remaining: number }[]; + isas: IsaReport[]; + anomalies: Anomaly[]; +} + +export function loadConfig(settingsPath = getSettingsPath()): PendingConfig { + let cfg: Record = {}; + try { cfg = JSON.parse(readFileSync(settingsPath, 'utf-8')).pending ?? {}; } catch { /* no settings: defaults */ } + const roots = Array.isArray(cfg.roots) && cfg.roots.length ? cfg.roots.map(String) : isaDirs(); + return { + roots: roots.map(expandPath), + groupField: typeof cfg.groupField === 'string' && cfg.groupField ? cfg.groupField : 'project', + idleDays: typeof cfg.idleDays === 'number' && cfg.idleDays > 0 ? cfg.idleDays : 14, + }; +} + +/** `//ISA.md`, one level deep: the same shape Pursuit's liveIsas reads. */ +function findIsas(root: string): string[] { + let names: string[]; + try { names = readdirSync(root).sort(); } catch { return []; } + return names.map((d) => join(root, d, ARTIFACT_FILENAME)).filter((p) => existsSync(p)); +} + +export function scan(config: PendingConfig, now = new Date()): PendingReport { + const isas: IsaReport[] = []; + const anomalies: Anomaly[] = []; + const missingRoots: string[] = []; + const seen = new Set(); + + for (const root of config.roots) { + if (!existsSync(root)) { missingRoots.push(root); continue; } + for (const path of findIsas(root)) { + let key = path; + try { key = realpathSync(path); } catch { /* unreadable below */ } + if (seen.has(key)) continue; + seen.add(key); + let content: string; + try { content = readFileSync(path, 'utf-8').replace(/\r\n?/g, '\n'); } catch (err) { + anomalies.push({ path, kind: 'unreadable', detail: (err as Error).message }); + continue; + } + const fm = parseFrontmatter(content); + if (!fm) anomalies.push({ path, kind: 'no_frontmatter', detail: 'no YAML frontmatter block' }); + + // parseClaims keeps parent nodes for dependency edges; a parent with nested + // children is verified through them, so only leaves are counted (as IsaClaims does). + const all = parseClaims(content); + const criteria = all.filter((c, i) => !(all[i + 1] && all[i + 1].indent > c.indent)); + const dropped = criteria.filter((c) => c.dropped).length; + const open = criteria.filter((c) => !c.checked && !c.dropped).length; + const closed = criteria.filter((c) => c.checked && !c.dropped).length; + const remaining = countRemaining(content); + const owed = open + remaining; + const phase = (fm?.phase || 'unknown').toLowerCase(); + + // `updated` frontmatter wins; file mtime is the fallback for ISAs that omit it. + const parsed = fm?.updated ? Date.parse(fm.updated) : NaN; + const updatedMs = Number.isNaN(parsed) ? statSync(path).mtimeMs : parsed; + const ageDays = Math.max(0, Math.floor((now.getTime() - updatedMs) / DAY_MS)); + + const owes = `${open} open ${open === 1 ? 'criterion' : 'criteria'}, ${remaining} remaining-work item(s)`; + if (owed > 0 && isaClosed(phase)) { + anomalies.push({ path, kind: 'closed_with_open_criteria', detail: `phase is ${phase} with ${owes}` }); + } else if (owed > 0 && ageDays > config.idleDays) { + anomalies.push({ path, kind: 'idle_with_open_criteria', detail: `${owes}, idle ${ageDays} days (limit ${config.idleDays})` }); + } + + isas.push({ + path, + group: fm?.[config.groupField] || UNLABELED, + phase, open, closed, dropped, + updated: new Date(updatedMs).toISOString(), + ageDays, + remaining, + }); + } + } + + const byGroup = new Map(); + for (const i of isas) { + const g = byGroup.get(i.group) ?? { group: i.group, isas: 0, open: 0, closed: 0, remaining: 0 }; + g.isas++; g.open += i.open; g.closed += i.closed; g.remaining += i.remaining; + byGroup.set(i.group, g); + } + const sum = (k: 'open' | 'closed' | 'remaining') => isas.reduce((s, i) => s + i[k], 0); + return { + generatedAt: now.toISOString(), + config, + missingRoots, + totals: { isas: isas.length, open: sum('open'), closed: sum('closed'), remaining: sum('remaining') }, + groups: [...byGroup.values()].sort((a, b) => b.open + b.remaining - (a.open + a.remaining) || a.group.localeCompare(b.group)), + isas, + anomalies, + }; +} + +export function formatHuman(r: PendingReport): string { + const lines = [`Pending: ${r.totals.open} open / ${r.totals.closed} closed criteria, ${r.totals.remaining} remaining-work item(s), across ${r.totals.isas} ISA(s)`]; + for (const root of r.missingRoots) lines.push(` ! root not found: ${root}`); + for (const g of r.groups) { + lines.push('', `${g.group} (${g.open} open, ${g.closed} closed, ${g.remaining} remaining)`); + for (const i of r.isas.filter((x) => x.group === g.group).sort((a, b) => b.open - a.open)) { + lines.push(` ${String(i.open).padStart(3)} open ${String(i.closed).padStart(3)} closed ${String(i.remaining).padStart(3)} remaining ${i.phase.padEnd(10)} ${String(i.ageDays).padStart(4)}d ${i.path}`); + } + } + if (r.anomalies.length) { + lines.push('', 'Anomalies'); + for (const a of r.anomalies) lines.push(` [${a.kind}] ${a.path} — ${a.detail}`); + } + return lines.join('\n'); +} + +export const USAGE = `Usage: bun LIFEOS/TOOLS/Pending.ts [--json] [--root ]... [--group-field ] [--idle-days ] + +Lists open vs closed criteria (and unchecked Remaining Work items) across ISAs. +Default roots are Pursuit's: MEMORY/WORK plus the system ISAs. +Read-only. Exit 0 on a completed scan, 2 on a bad argument. + + --json stable machine-readable output + --root directory whose /ISA.md files are read (repeatable; replaces the default roots) + --group-field frontmatter field used as group label (default: project) + --idle-days flag open ISAs idle for more than n days (default: 14) + -h, --help show this help +`; + +export function parseArgs(argv: string[], base: PendingConfig): { config: PendingConfig; json: boolean } { + const config = { ...base }; + const roots: string[] = []; + let json = false; + const value = (flag: string, i: number): string => { + const v = argv[i + 1]; + if (v === undefined || v === '' || v.startsWith('--')) throw new Error(`${flag} requires a value`); + return v; + }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--json') json = true; + else if (a === '--root') roots.push(expandPath(value(a, i++))); + else if (a === '--group-field') config.groupField = value(a, i++); + else if (a === '--idle-days') { + const raw = value(a, i++); + const n = Number(raw); + if (!Number.isFinite(n) || n <= 0) throw new Error(`--idle-days requires a positive number, got: ${raw}`); + config.idleDays = n; + } else throw new Error(`unknown argument: ${a}`); + } + if (roots.length) config.roots = roots; + return { config, json }; +} + +if (import.meta.main) { + const args = process.argv.slice(2); + if (args.includes('--help') || args.includes('-h')) { + console.log(USAGE); + process.exit(0); + } + try { + const { config, json } = parseArgs(args, loadConfig()); + const report = scan(config); + console.log(json ? JSON.stringify(report, null, 2) : formatHuman(report)); + } catch (err) { + console.error((err as Error).message); + process.exit(2); + } +}