@dreki-gg/pi-plan-mode 0.26.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/extensions/plan-mode/__tests__/initiative-status.test.ts +5 -5
  3. package/extensions/plan-mode/__tests__/plan-references-context.test.ts +4 -4
  4. package/extensions/plan-mode/__tests__/reconcile-plans.test.ts +3 -3
  5. package/extensions/plan-mode/__tests__/resolve-plan.test.ts +4 -4
  6. package/extensions/plan-mode/__tests__/revise-plan.test.ts +4 -4
  7. package/extensions/plan-mode/__tests__/submit-initiative.test.ts +2 -2
  8. package/extensions/plan-mode/__tests__/submit-plan.test.ts +3 -3
  9. package/extensions/plan-mode/__tests__/update-initiative.test.ts +2 -2
  10. package/extensions/plan-mode/__tests__/update-plan.test.ts +2 -2
  11. package/extensions/plan-mode/__tests__/utils.test.ts +2 -1
  12. package/extensions/plan-mode/commands/list-initiatives.ts +19 -109
  13. package/extensions/plan-mode/commands/list-plans.ts +21 -168
  14. package/extensions/plan-mode/exec-pending.ts +59 -0
  15. package/extensions/plan-mode/index.ts +8 -7
  16. package/extensions/plan-mode/references/context.ts +5 -5
  17. package/extensions/plan-mode/references/plan-index.ts +1 -1
  18. package/extensions/plan-mode/resolve-plan.ts +4 -4
  19. package/extensions/plan-mode/resume.ts +6 -5
  20. package/extensions/plan-mode/tools/add-task.ts +1 -1
  21. package/extensions/plan-mode/tools/initiative-status.ts +6 -6
  22. package/extensions/plan-mode/tools/preview-prototype.ts +3 -3
  23. package/extensions/plan-mode/tools/reconcile-plans.ts +2 -2
  24. package/extensions/plan-mode/tools/revise-plan.ts +7 -7
  25. package/extensions/plan-mode/tools/submit-initiative.ts +4 -4
  26. package/extensions/plan-mode/tools/submit-plan.ts +7 -7
  27. package/extensions/plan-mode/tools/update-initiative.ts +2 -2
  28. package/extensions/plan-mode/tools/update-plan.ts +3 -3
  29. package/extensions/plan-mode/types.ts +17 -59
  30. package/extensions/plan-mode/utils.ts +2 -29
  31. package/package.json +2 -1
  32. package/extensions/plan-mode/__tests__/atomic-write.test.ts +0 -45
  33. package/extensions/plan-mode/__tests__/concurrent-writes.test.ts +0 -85
  34. package/extensions/plan-mode/__tests__/initiative-readiness.test.ts +0 -159
  35. package/extensions/plan-mode/__tests__/initiatives-manifest.test.ts +0 -89
  36. package/extensions/plan-mode/__tests__/list-initiatives.test.ts +0 -59
  37. package/extensions/plan-mode/__tests__/list-plans.test.ts +0 -253
  38. package/extensions/plan-mode/__tests__/plan-storage.test.ts +0 -57
  39. package/extensions/plan-mode/__tests__/plans-manifest.test.ts +0 -120
  40. package/extensions/plan-mode/__tests__/reconcile.test.ts +0 -188
  41. package/extensions/plan-mode/__tests__/schema.test.ts +0 -334
  42. package/extensions/plan-mode/__tests__/task-status.test.ts +0 -74
  43. package/extensions/plan-mode/__tests__/task-storage.test.ts +0 -101
  44. package/extensions/plan-mode/effects/filesystem.ts +0 -65
  45. package/extensions/plan-mode/effects/runtime.ts +0 -24
  46. package/extensions/plan-mode/errors.ts +0 -105
  47. package/extensions/plan-mode/initiative.ts +0 -172
  48. package/extensions/plan-mode/plan-storage.ts +0 -6
  49. package/extensions/plan-mode/reconcile.ts +0 -235
  50. package/extensions/plan-mode/schema.ts +0 -99
  51. package/extensions/plan-mode/storage/atomic-write.ts +0 -75
  52. package/extensions/plan-mode/storage/file-lock.ts +0 -49
  53. package/extensions/plan-mode/storage/initiatives-manifest.ts +0 -154
  54. package/extensions/plan-mode/storage/plan-storage.ts +0 -88
  55. package/extensions/plan-mode/storage/plans-manifest.ts +0 -174
  56. package/extensions/plan-mode/storage/task-storage.ts +0 -111
  57. package/extensions/plan-mode/task-status.ts +0 -46
@@ -1,99 +0,0 @@
1
- /**
2
- * Effect Schema definitions for plan-mode persisted records.
3
- *
4
- * These replace the hand-rolled type guards. Schemas are the single source of
5
- * truth for record shape; the mutable TS interfaces in `types.ts` are kept for
6
- * the imperative orchestration code (which mutates tasks in place) and are
7
- * structurally compatible with the decoded values.
8
- */
9
-
10
- import { Schema } from 'effect';
11
-
12
- export const TaskStatusSchema = Schema.Literal('pending', 'done', 'skipped', 'blocked', 'deferred');
13
-
14
- export const TaskOriginSchema = Schema.Literal('plan', 'discovered');
15
-
16
- export const TaskRecordSchema = Schema.Struct({
17
- _type: Schema.Literal('task'),
18
- id: Schema.String,
19
- description: Schema.String,
20
- details: Schema.optional(Schema.String),
21
- status: TaskStatusSchema,
22
- origin: Schema.optional(TaskOriginSchema),
23
- depends_on: Schema.optional(Schema.mutable(Schema.Array(Schema.String))),
24
- notes: Schema.optional(Schema.String),
25
- created_at: Schema.String,
26
- updated_at: Schema.String,
27
- });
28
-
29
- export const TaskMetaSchema = Schema.Struct({
30
- _type: Schema.Literal('meta'),
31
- title: Schema.String,
32
- plan_name: Schema.String,
33
- created_at: Schema.String,
34
- /** Optional git commit the plan was written against (back-compat: absent on older plans). */
35
- base_commit: Schema.optional(Schema.String),
36
- });
37
-
38
- /** A single tasks.jsonl line is either the meta record or a task record. */
39
- export const TasksLineSchema = Schema.Union(TaskMetaSchema, TaskRecordSchema);
40
-
41
- /**
42
- * Plan lifecycle statuses.
43
- * - in-progress: active, tracked, eligible for auto-resolution
44
- * - done: completed (all tasks resolved)
45
- * - superseded: closed because another plan absorbed the work
46
- * - abandoned: closed without shipping (rejected / won't do)
47
- * Only `in-progress` is treated as active; the rest are terminal.
48
- */
49
- export const PlanStatusSchema = Schema.Literal('in-progress', 'done', 'superseded', 'abandoned');
50
-
51
- export const PlanManifestEntrySchema = Schema.Struct({
52
- _type: Schema.Literal('plan'),
53
- name: Schema.String,
54
- status: PlanStatusSchema,
55
- title: Schema.String,
56
- created_at: Schema.String,
57
- completed_at: Schema.NullOr(Schema.String),
58
- /** Optional human-readable reason, used for terminal statuses. */
59
- reason: Schema.optional(Schema.String),
60
- /** Parent initiative name (kebab). Absent = standalone flat plan. */
61
- initiative: Schema.optional(Schema.String),
62
- /**
63
- * Plan-level dependencies: names of plans this plan depends on. Distinct from
64
- * the task-level `depends_on` above. Cross-initiative references are allowed.
65
- */
66
- depends_on: Schema.optional(Schema.mutable(Schema.Array(Schema.String))),
67
- });
68
-
69
- /**
70
- * Initiative lifecycle statuses reuse the plan lifecycle literals. An
71
- * initiative's status is a projection of its member plans' statuses, with the
72
- * same terminal-guard semantics as plans.
73
- */
74
- export const InitiativeStatusSchema = PlanStatusSchema;
75
-
76
- export const InitiativeManifestEntrySchema = Schema.Struct({
77
- _type: Schema.Literal('initiative'),
78
- name: Schema.String,
79
- status: InitiativeStatusSchema,
80
- title: Schema.String,
81
- created_at: Schema.String,
82
- completed_at: Schema.NullOr(Schema.String),
83
- /** Optional human-readable reason, used for terminal statuses. */
84
- reason: Schema.optional(Schema.String),
85
- });
86
-
87
- export const ExecPendingConfigSchema = Schema.Struct({
88
- model: Schema.Struct({ provider: Schema.String, id: Schema.String }),
89
- thinking: Schema.String,
90
- });
91
-
92
- export const decodeTaskRecord = Schema.decodeUnknownEither(TaskRecordSchema);
93
- export const decodeTaskMeta = Schema.decodeUnknownEither(TaskMetaSchema);
94
- export const decodeTasksLine = Schema.decodeUnknownEither(TasksLineSchema);
95
- export const decodePlanManifestEntry = Schema.decodeUnknownEither(PlanManifestEntrySchema);
96
- export const decodeInitiativeManifestEntry = Schema.decodeUnknownEither(
97
- InitiativeManifestEntrySchema,
98
- );
99
- export const decodeExecPendingConfig = Schema.decodeUnknownEither(ExecPendingConfigSchema);
@@ -1,75 +0,0 @@
1
- import { Effect } from 'effect';
2
- import { createWriteStream } from 'node:fs';
3
- import { open, rename, rm } from 'node:fs/promises';
4
- import { dirname, join } from 'node:path';
5
- import { randomUUID } from 'node:crypto';
6
- import { PlanWriteError } from '../errors.js';
7
-
8
- export interface AtomicWriteOptions {
9
- /** Test seam: file mode for the temporary file. */
10
- mode?: number;
11
- }
12
-
13
- /**
14
- * Atomically write `data` to `path`: write to a temp file, fsync, rename into
15
- * place, then best-effort fsync the directory. Failures surface as
16
- * `PlanWriteError`.
17
- */
18
- export function writeFileAtomic(
19
- path: string,
20
- data: string | Buffer,
21
- options: AtomicWriteOptions = {},
22
- ): Effect.Effect<void, PlanWriteError> {
23
- return Effect.tryPromise({
24
- try: () => writeFileAtomicPromise(path, data, options),
25
- catch: (cause) => new PlanWriteError({ path, cause }),
26
- });
27
- }
28
-
29
- async function writeFileAtomicPromise(
30
- path: string,
31
- data: string | Buffer,
32
- options: AtomicWriteOptions,
33
- ): Promise<void> {
34
- const dir = dirname(path);
35
- const tempPath = join(dir, `.${process.pid}.${randomUUID()}.tmp`);
36
- let completed = false;
37
-
38
- try {
39
- await writeAndSync(tempPath, data, options.mode);
40
- await rename(tempPath, path);
41
- completed = true;
42
- await syncDirectory(dir);
43
- } finally {
44
- if (!completed) {
45
- await rm(tempPath, { force: true }).catch(() => undefined);
46
- }
47
- }
48
- }
49
-
50
- async function writeAndSync(path: string, data: string | Buffer, mode?: number): Promise<void> {
51
- await new Promise<void>((resolve, reject) => {
52
- const stream = createWriteStream(path, { flags: 'wx', mode });
53
- stream.once('error', reject);
54
- stream.once('finish', resolve);
55
- stream.end(data);
56
- });
57
-
58
- const handle = await open(path, 'r+');
59
- try {
60
- await handle.sync();
61
- } finally {
62
- await handle.close();
63
- }
64
- }
65
-
66
- async function syncDirectory(dir: string): Promise<void> {
67
- // Directory fsync is best-effort: supported on Unix, not always elsewhere.
68
- const handle = await open(dir, 'r').catch(() => undefined);
69
- if (!handle) return;
70
- try {
71
- await handle.sync().catch(() => undefined);
72
- } finally {
73
- await handle.close().catch(() => undefined);
74
- }
75
- }
@@ -1,49 +0,0 @@
1
- /**
2
- * Process-wide keyed mutex for serializing read-modify-write on shared files.
3
- *
4
- * Pi runs every tool call in a single Node process. When several tool calls run
5
- * in one block (e.g. three `submit_initiative` calls, or concurrent
6
- * `submit_plan` / `revise_plan`), each does an independent
7
- * read → modify → write against the same registry file. Without serialization
8
- * their reads all observe the same starting state and the last write clobbers
9
- * the rest — a classic lost-update race.
10
- *
11
- * `withFileLock` wraps a read-modify-write critical section so only one runs at
12
- * a time per `key` (the registry path). The semaphore is created eagerly with
13
- * `unsafeMakeSemaphore` and cached per key, so its permit count lives in plain
14
- * shared memory and serializes correctly even across independent
15
- * `Effect.runPromise` invocations (separate tool executes).
16
- *
17
- * NOTE: this guards against in-process concurrency only. Atomic writes
18
- * (`writeFileAtomic`) still protect against torn files from other processes,
19
- * but cross-process registry coordination is out of scope.
20
- */
21
-
22
- import { Effect } from 'effect';
23
-
24
- const locks = new Map<string, Effect.Semaphore>();
25
-
26
- function lockFor(key: string): Effect.Semaphore {
27
- let lock = locks.get(key);
28
- if (!lock) {
29
- lock = Effect.unsafeMakeSemaphore(1);
30
- locks.set(key, lock);
31
- }
32
- return lock;
33
- }
34
-
35
- /**
36
- * Run `effect` while holding the single permit for `key`. Concurrent callers
37
- * with the same key queue and run one at a time; the permit is always released,
38
- * even on failure or interruption.
39
- *
40
- * Do NOT nest `withFileLock` for the same key inside another — the permit is
41
- * not reentrant and would deadlock. Express composite read-modify-write as one
42
- * locked section instead.
43
- */
44
- export function withFileLock<A, E, R>(
45
- key: string,
46
- effect: Effect.Effect<A, E, R>,
47
- ): Effect.Effect<A, E, R> {
48
- return Effect.suspend(() => lockFor(key).withPermits(1)(effect));
49
- }
@@ -1,154 +0,0 @@
1
- /**
2
- * `.plans/initiatives.jsonl` registry — the initiative-level sibling of
3
- * `plans-manifest.ts`.
4
- *
5
- * An initiative groups multiple plans. Its `status` is a PROJECTION of its
6
- * member plans' statuses (see `reconcileInitiativeStatus` in `../initiative.ts`
7
- * for the projection wiring): `done` when every member plan is terminal,
8
- * `in-progress` otherwise. Manually-set terminal statuses (`superseded` /
9
- * `abandoned` via `update_initiative`) are never auto-overridden.
10
- *
11
- * This module is intentionally dependency-light: it knows how to read/write the
12
- * registry. The projection (which must read the PLANS manifest) lives in
13
- * `../initiative.ts` to keep the dependency direction one-way and cycle-free.
14
- */
15
-
16
- import { Effect, Either, Option } from 'effect';
17
- import { FileSystem } from '../effects/filesystem.js';
18
- import { JsonlParseError, JsonlValidationError, PlanWriteError } from '../errors.js';
19
- import { decodeInitiativeManifestEntry } from '../schema.js';
20
- import type { InitiativeStatus } from '../types.js';
21
- import { withFileLock } from './file-lock.js';
22
-
23
- const MANIFEST_DIR = '.plans';
24
- const MANIFEST_PATH = '.plans/initiatives.jsonl';
25
-
26
- export interface InitiativeManifestEntry {
27
- _type: 'initiative';
28
- name: string;
29
- status: InitiativeStatus;
30
- title: string;
31
- created_at: string;
32
- completed_at: string | null;
33
- reason?: string;
34
- }
35
-
36
- /** A status is terminal (closed) when it is anything other than in-progress. */
37
- export function isTerminalStatus(status: InitiativeStatus): boolean {
38
- return status !== 'in-progress';
39
- }
40
-
41
- type ReadError = JsonlParseError | JsonlValidationError;
42
-
43
- export function readInitiativesManifest(): Effect.Effect<
44
- InitiativeManifestEntry[],
45
- ReadError,
46
- FileSystem
47
- > {
48
- return Effect.gen(function* () {
49
- const fs = yield* FileSystem;
50
- // A missing or unreadable manifest is treated as "no initiatives".
51
- const maybeText = yield* Effect.option(fs.readFileString(MANIFEST_PATH));
52
- if (Option.isNone(maybeText)) return [];
53
-
54
- const entries: InitiativeManifestEntry[] = [];
55
- for (const [index, raw] of maybeText.value.split(/\r?\n/).entries()) {
56
- if (!raw.trim()) continue;
57
- const line = index + 1;
58
-
59
- let parsed: unknown;
60
- try {
61
- parsed = JSON.parse(raw);
62
- } catch (cause) {
63
- return yield* Effect.fail(new JsonlParseError({ path: MANIFEST_PATH, line, cause }));
64
- }
65
-
66
- const decoded = decodeInitiativeManifestEntry(parsed);
67
- if (Either.isLeft(decoded)) {
68
- return yield* Effect.fail(
69
- new JsonlValidationError({ path: MANIFEST_PATH, line, reason: decoded.left.message }),
70
- );
71
- }
72
- entries.push(decoded.right);
73
- }
74
- return entries;
75
- });
76
- }
77
-
78
- export function writeInitiativesManifest(
79
- entries: InitiativeManifestEntry[],
80
- ): Effect.Effect<void, PlanWriteError, FileSystem> {
81
- return Effect.gen(function* () {
82
- const fs = yield* FileSystem;
83
- yield* fs.makeDir(MANIFEST_DIR);
84
- const content =
85
- entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length ? '\n' : '');
86
- yield* fs.writeFileAtomic(MANIFEST_PATH, content);
87
- });
88
- }
89
-
90
- export interface InitiativeUpsert {
91
- status: InitiativeStatus;
92
- title?: string;
93
- reason?: string;
94
- }
95
-
96
- /**
97
- * Pure transform: upsert `name` into the in-memory `entries` array, preserving
98
- * created_at from any existing entry. No IO — shared by the locked
99
- * `upsertInitiativeEntry` and `reconcileInitiativeStatus` so both flow through
100
- * one serialized read-modify-write and never nest locks.
101
- */
102
- export function applyInitiativeUpsert(
103
- entries: InitiativeManifestEntry[],
104
- name: string,
105
- updates: InitiativeUpsert,
106
- ): void {
107
- const now = new Date().toISOString();
108
- const index = entries.findIndex((entry) => entry.name === name);
109
- const existing = index === -1 ? undefined : entries[index];
110
- const entry: InitiativeManifestEntry = {
111
- _type: 'initiative',
112
- name,
113
- status: updates.status,
114
- title: updates.title ?? existing?.title ?? 'Untitled initiative',
115
- created_at: existing?.created_at ?? now,
116
- // Terminal statuses record a completion timestamp; reopening clears it.
117
- completed_at: isTerminalStatus(updates.status) ? (existing?.completed_at ?? now) : null,
118
- reason: updates.reason ?? existing?.reason,
119
- };
120
- if (index === -1) entries.push(entry);
121
- else entries[index] = entry;
122
- }
123
-
124
- /**
125
- * Serialized read-modify-write of the initiatives registry. Holds a
126
- * process-wide lock on the manifest path across the whole read → transform →
127
- * write so concurrent tool calls cannot clobber each other. `transform` may run
128
- * IO (e.g. read the plans manifest to project status) and mutates the entries
129
- * array in place, returning `true` when it changed something.
130
- */
131
- export function mutateInitiativesManifest<E, R>(
132
- transform: (entries: InitiativeManifestEntry[]) => Effect.Effect<boolean, E, R>,
133
- ): Effect.Effect<void, ReadError | PlanWriteError | E, FileSystem | R> {
134
- return withFileLock(
135
- MANIFEST_PATH,
136
- Effect.gen(function* () {
137
- const entries = yield* readInitiativesManifest();
138
- const changed = yield* transform(entries);
139
- if (changed) yield* writeInitiativesManifest(entries);
140
- }),
141
- );
142
- }
143
-
144
- export function upsertInitiativeEntry(
145
- name: string,
146
- updates: InitiativeUpsert,
147
- ): Effect.Effect<void, ReadError | PlanWriteError, FileSystem> {
148
- return mutateInitiativesManifest((entries) =>
149
- Effect.sync(() => {
150
- applyInitiativeUpsert(entries, name, updates);
151
- return true;
152
- }),
153
- );
154
- }
@@ -1,88 +0,0 @@
1
- /**
2
- * Plan disk I/O — exec-pending markers and handoff documents.
3
- */
4
-
5
- import { Effect, Either, Option } from 'effect';
6
- import { FileSystem } from '../effects/filesystem.js';
7
- import type { PlanWriteError } from '../errors.js';
8
- import { decodeExecPendingConfig } from '../schema.js';
9
- import type { ExecPendingConfig } from '../types.js';
10
- import { EXEC_PENDING_FILE } from '../constants.js';
11
-
12
- const PLANS_DIR = '.plans';
13
-
14
- export function writeExecPending(
15
- dir: string,
16
- config: ExecPendingConfig,
17
- ): Effect.Effect<void, PlanWriteError, FileSystem> {
18
- return Effect.gen(function* () {
19
- const fs = yield* FileSystem;
20
- yield* fs.makeDir(dir);
21
- yield* fs.writeFileString(
22
- `${dir}/${EXEC_PENDING_FILE}`,
23
- JSON.stringify(config, null, 2) + '\n',
24
- );
25
- });
26
- }
27
-
28
- export function readAndClearExecPending(): Effect.Effect<
29
- { planDir: string; config: ExecPendingConfig } | undefined,
30
- never,
31
- FileSystem
32
- > {
33
- return Effect.gen(function* () {
34
- const fs = yield* FileSystem;
35
- const maybeDirs = yield* Effect.option(fs.listDirectories(PLANS_DIR));
36
- if (Option.isNone(maybeDirs)) return undefined;
37
-
38
- for (const name of maybeDirs.value) {
39
- const dir = `${PLANS_DIR}/${name}`;
40
- const markerPath = `${dir}/${EXEC_PENDING_FILE}`;
41
- const maybeText = yield* Effect.option(fs.readFileString(markerPath));
42
- if (Option.isNone(maybeText)) continue;
43
-
44
- let parsed: unknown;
45
- try {
46
- parsed = JSON.parse(maybeText.value);
47
- } catch {
48
- continue;
49
- }
50
- const decoded = decodeExecPendingConfig(parsed);
51
- if (Either.isLeft(decoded)) continue;
52
-
53
- yield* Effect.ignore(fs.removeFile(markerPath));
54
- return { planDir: dir, config: decoded.right };
55
- }
56
- return undefined;
57
- });
58
- }
59
-
60
- export function saveHandoff(
61
- planDir: string,
62
- content: string,
63
- ): Effect.Effect<void, PlanWriteError, FileSystem> {
64
- return Effect.gen(function* () {
65
- const fs = yield* FileSystem;
66
- yield* fs.makeDir(planDir);
67
- yield* fs.writeFileString(`${planDir}/HANDOFF.md`, content);
68
- });
69
- }
70
-
71
- export function loadHandoff(planDir: string): Effect.Effect<string | undefined, never, FileSystem> {
72
- return Effect.gen(function* () {
73
- const fs = yield* FileSystem;
74
- const maybeText = yield* Effect.option(fs.readFileString(`${planDir}/HANDOFF.md`));
75
- return Option.getOrUndefined(maybeText);
76
- });
77
- }
78
-
79
- export function saveInitiative(
80
- initiativeDir: string,
81
- content: string,
82
- ): Effect.Effect<void, PlanWriteError, FileSystem> {
83
- return Effect.gen(function* () {
84
- const fs = yield* FileSystem;
85
- yield* fs.makeDir(initiativeDir);
86
- yield* fs.writeFileString(`${initiativeDir}/INITIATIVE.md`, content);
87
- });
88
- }
@@ -1,174 +0,0 @@
1
- import { Effect, Either, Option } from 'effect';
2
- import { FileSystem } from '../effects/filesystem.js';
3
- import { JsonlParseError, JsonlValidationError, PlanWriteError } from '../errors.js';
4
- import { decodePlanManifestEntry } from '../schema.js';
5
- import type { PlanStatus } from '../types.js';
6
- import { withFileLock } from './file-lock.js';
7
-
8
- const MANIFEST_DIR = '.plans';
9
- const MANIFEST_PATH = '.plans/plans.jsonl';
10
-
11
- export interface PlanManifestEntry {
12
- _type: 'plan';
13
- name: string;
14
- status: PlanStatus;
15
- title: string;
16
- created_at: string;
17
- completed_at: string | null;
18
- reason?: string;
19
- /** Parent initiative name (kebab). Absent = standalone flat plan. */
20
- initiative?: string;
21
- /** Plan-level dependencies (plan names). Cross-initiative allowed. */
22
- depends_on?: string[];
23
- }
24
-
25
- /** A status is terminal (closed) when it is anything other than in-progress. */
26
- export function isTerminalStatus(status: PlanStatus): boolean {
27
- return status !== 'in-progress';
28
- }
29
-
30
- type ReadError = JsonlParseError | JsonlValidationError;
31
-
32
- export function readPlansManifest(): Effect.Effect<PlanManifestEntry[], ReadError, FileSystem> {
33
- return Effect.gen(function* () {
34
- const fs = yield* FileSystem;
35
- // A missing or unreadable manifest is treated as "no plans".
36
- const maybeText = yield* Effect.option(fs.readFileString(MANIFEST_PATH));
37
- if (Option.isNone(maybeText)) return [];
38
-
39
- const entries: PlanManifestEntry[] = [];
40
- for (const [index, raw] of maybeText.value.split(/\r?\n/).entries()) {
41
- if (!raw.trim()) continue;
42
- const line = index + 1;
43
-
44
- let parsed: unknown;
45
- try {
46
- parsed = JSON.parse(raw);
47
- } catch (cause) {
48
- return yield* Effect.fail(new JsonlParseError({ path: MANIFEST_PATH, line, cause }));
49
- }
50
-
51
- const decoded = decodePlanManifestEntry(parsed);
52
- if (Either.isLeft(decoded)) {
53
- return yield* Effect.fail(
54
- new JsonlValidationError({ path: MANIFEST_PATH, line, reason: decoded.left.message }),
55
- );
56
- }
57
- entries.push(decoded.right);
58
- }
59
- return entries;
60
- });
61
- }
62
-
63
- export function writePlansManifest(
64
- entries: PlanManifestEntry[],
65
- ): Effect.Effect<void, PlanWriteError, FileSystem> {
66
- return Effect.gen(function* () {
67
- const fs = yield* FileSystem;
68
- yield* fs.makeDir(MANIFEST_DIR);
69
- const content =
70
- entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length ? '\n' : '');
71
- yield* fs.writeFileAtomic(MANIFEST_PATH, content);
72
- });
73
- }
74
-
75
- export interface PlanUpsert {
76
- status: PlanStatus;
77
- title?: string;
78
- reason?: string;
79
- /** Parent initiative name; preserved when omitted. */
80
- initiative?: string;
81
- /** Plan-level dependencies (plan names); preserved when omitted. */
82
- depends_on?: string[];
83
- }
84
-
85
- /**
86
- * Pure transform: upsert `name` into the in-memory `entries` array, preserving
87
- * created_at / membership / deps from any existing entry. No IO — shared by the
88
- * locked `upsertPlanEntry` and `reconcilePlanStatus` so both flow through one
89
- * serialized read-modify-write and never nest locks.
90
- */
91
- export function applyPlanUpsert(
92
- entries: PlanManifestEntry[],
93
- name: string,
94
- updates: PlanUpsert,
95
- ): void {
96
- const now = new Date().toISOString();
97
- const index = entries.findIndex((entry) => entry.name === name);
98
- const existing = index === -1 ? undefined : entries[index];
99
- const entry: PlanManifestEntry = {
100
- _type: 'plan',
101
- name,
102
- status: updates.status,
103
- title: updates.title ?? existing?.title ?? 'Untitled plan',
104
- created_at: existing?.created_at ?? now,
105
- // Terminal statuses record a completion timestamp; reopening clears it.
106
- completed_at: isTerminalStatus(updates.status) ? (existing?.completed_at ?? now) : null,
107
- reason: updates.reason ?? existing?.reason,
108
- // Membership + plan-level deps are preserved across status-only upserts.
109
- initiative: updates.initiative ?? existing?.initiative,
110
- depends_on: updates.depends_on ?? existing?.depends_on,
111
- };
112
- if (index === -1) entries.push(entry);
113
- else entries[index] = entry;
114
- }
115
-
116
- /**
117
- * Serialized read-modify-write of the plans registry. Holds a process-wide lock
118
- * on the manifest path across the whole read → transform → write so concurrent
119
- * tool calls cannot clobber each other (lost-update race). `transform` mutates
120
- * the entries array in place and returns `true` when it changed something
121
- * (return `false` to skip the rewrite).
122
- */
123
- export function mutatePlansManifest(
124
- transform: (entries: PlanManifestEntry[]) => boolean,
125
- ): Effect.Effect<void, ReadError | PlanWriteError, FileSystem> {
126
- return withFileLock(
127
- MANIFEST_PATH,
128
- Effect.gen(function* () {
129
- const entries = yield* readPlansManifest();
130
- const changed = transform(entries);
131
- if (changed) yield* writePlansManifest(entries);
132
- }),
133
- );
134
- }
135
-
136
- export function upsertPlanEntry(
137
- name: string,
138
- updates: PlanUpsert,
139
- ): Effect.Effect<void, ReadError | PlanWriteError, FileSystem> {
140
- return mutatePlansManifest((entries) => {
141
- applyPlanUpsert(entries, name, updates);
142
- return true;
143
- });
144
- }
145
-
146
- /**
147
- * Reconcile a plan's registry status from its task state.
148
- *
149
- * The registry `status` is a PROJECTION of task state, not a parallel flag.
150
- * Call this wherever tasks are written so completion is never coupled to a
151
- * formal in-session execution run (see FEEDBACK #1). `finalizable` means every
152
- * active task is resolved AND no deferred follow-ups remain.
153
- *
154
- * Guard: a manually-set terminal status (`superseded` / `abandoned`) is never
155
- * auto-overridden — only `in-progress` ⇄ `done` is derived from tasks.
156
- */
157
- export function reconcilePlanStatus(
158
- name: string,
159
- finalizable: boolean,
160
- title?: string,
161
- ): Effect.Effect<void, ReadError | PlanWriteError, FileSystem> {
162
- return mutatePlansManifest((entries) => {
163
- const existing = entries.find((entry) => entry.name === name);
164
- // Reconcile only reflects task state for KNOWN plans; never conjure an
165
- // entry for an unregistered plan (orphans are surfaced, not auto-created).
166
- if (!existing) return false;
167
- // Do not resurrect / clobber an explicitly closed plan.
168
- if (existing.status === 'superseded' || existing.status === 'abandoned') return false;
169
- const status: PlanStatus = finalizable ? 'done' : 'in-progress';
170
- if (existing.status === status) return false; // no change
171
- applyPlanUpsert(entries, name, { status, title });
172
- return true;
173
- });
174
- }