harnery 0.16.0 → 0.17.0

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/supervisor.d.ts.map +1 -1
  3. package/dist/commands/supervisor.js +184 -3
  4. package/dist/core/supervisor/index.d.ts +3 -0
  5. package/dist/core/supervisor/index.d.ts.map +1 -1
  6. package/dist/core/supervisor/index.js +3 -0
  7. package/dist/core/supervisor/plan-api.d.ts +16 -0
  8. package/dist/core/supervisor/plan-api.d.ts.map +1 -0
  9. package/dist/core/supervisor/plan-api.js +34 -0
  10. package/dist/core/supervisor/plan-read.d.ts +4 -0
  11. package/dist/core/supervisor/plan-read.d.ts.map +1 -0
  12. package/dist/core/supervisor/plan-read.js +269 -0
  13. package/dist/core/supervisor/plan-types.d.ts +113 -0
  14. package/dist/core/supervisor/plan-types.d.ts.map +1 -0
  15. package/dist/core/supervisor/plan-types.js +14 -0
  16. package/dist/core/supervisor/planning.d.ts +26 -0
  17. package/dist/core/supervisor/planning.d.ts.map +1 -0
  18. package/dist/core/supervisor/planning.js +486 -0
  19. package/dist/core/supervisor/read.d.ts +2 -0
  20. package/dist/core/supervisor/read.d.ts.map +1 -1
  21. package/dist/core/supervisor/read.js +2 -0
  22. package/dist/core/supervisor/runner.d.ts +3 -0
  23. package/dist/core/supervisor/runner.d.ts.map +1 -1
  24. package/dist/core/supervisor/runner.js +37 -7
  25. package/dist/core/supervisor/service.d.ts.map +1 -1
  26. package/dist/core/supervisor/service.js +7 -0
  27. package/dist/core/supervisor/state.d.ts +11 -1
  28. package/dist/core/supervisor/state.d.ts.map +1 -1
  29. package/dist/core/supervisor/state.js +186 -7
  30. package/package.json +1 -1
  31. package/src/commands/supervisor.ts +229 -2
  32. package/src/core/supervisor/index.ts +18 -0
  33. package/src/core/supervisor/plan-api.ts +47 -0
  34. package/src/core/supervisor/plan-read.ts +299 -0
  35. package/src/core/supervisor/plan-types.ts +144 -0
  36. package/src/core/supervisor/planning.ts +576 -0
  37. package/src/core/supervisor/read.ts +15 -0
  38. package/src/core/supervisor/runner.ts +39 -2
  39. package/src/core/supervisor/service.ts +7 -0
  40. package/src/core/supervisor/state.ts +235 -6
package/README.md CHANGED
@@ -23,7 +23,7 @@
23
23
  - **Cross-machine presence:** sessions on every machine that shares a repo see each other, labeled by machine. Zero-config over the repo's own git remote (presence refs), with an optional live-socket upgrade via an end-to-end-encrypted relay — the public `relay.harnery.com`, or self-host with `harn relay serve` / the bundled Cloudflare Worker (`relay/worker/`). The relay sees only ciphertext in opaquely-named rooms.
24
24
  - **Coordination-aware workflows:** `harn workflow run <script>` executes bounded, schema-gated multi-subagent workflow scripts — plain JS stages fanning out to headless harness-CLI subagents that are born coordination-registered (heartbeats, events, claim guards), with deterministic code deciding the routing between stages. An optional host-owned policy gates dispatch and declared external mutations with `ALLOW`, `ASK`, and `DENY`; CLI `ASK` requests park durably for an explicit approve/deny and same-run resume, while library callers remain fail-closed by default.
25
25
  - **Durable work above attempts:** `harn work` preserves an objective across bounded workflow attempts, dependencies, approval parks, failures, and review. Its one-shot reconciler derives state from append-only local evidence and reports the next explicit action without silently spawning, retrying, or accepting work.
26
- - **Bounded goal supervision:** `harn supervisor` freezes a specialist team and safety limits around a root durable-work graph, then runs scheduling cycles until success, human attention, no progress, or budget exhaustion. Use explicit foreground ticks or enroll goals in the optional heartbeat-backed background service; specialist roles survive as configuration while every child remains a bounded process.
26
+ - **Bounded goal supervision:** `harn supervisor` freezes a specialist team and safety limits around a root durable-work graph, then runs scheduling cycles until success, human attention, no progress, or budget exhaustion. An optional planner can propose a schema-gated replacement graph from a frozen workflow-template catalog when the active graph has no legal move; proposals require review by default, old graphs remain immutable evidence, and their attempts still consume the goal budget. Use explicit foreground ticks or enroll goals in the optional heartbeat-backed background service.
27
27
  - **Standalone web UI:** `harn web up` boots a local Next.js dashboard for the coord layer, councils, per-project state, and a local coding-agent status view (Claude Code / Codex / Cursor usage, backed by `harn devtools`). Ships with the git clone, not the npm package (see [Install](#install)).
28
28
  - **Backup + sync:** `harn backup` snapshots `.harnery/` via [restic](https://restic.net/); `harn sync` keeps a curated subset live across machines via [rclone](https://rclone.org/) (Google Drive or any rclone remote).
29
29
 
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor.d.ts","sourceRoot":"","sources":["../../src/commands/supervisor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA4DnD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CA2FnF"}
1
+ {"version":3,"file":"supervisor.d.ts","sourceRoot":"","sources":["../../src/commands/supervisor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAmEnD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CA8FnF"}
@@ -1,10 +1,10 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { resolve } from "node:path";
2
+ import { dirname, isAbsolute, resolve } from "node:path";
3
3
  import { workflowSubscriptionOnly } from "../core/config.js";
4
4
  import { createBuiltinHarnessRegistry } from "../core/harnesses/index.js";
5
5
  import { findCoordRoot } from "../core/hooks/resolve/coord-root.js";
6
6
  import { loadPolicyFile } from "../core/policy/index.js";
7
- import { configureSupervisorService, createSupervisor, listSupervisors, readSupervisor, readSupervisorServiceConfig, readSupervisorServiceStatus, requestSupervisorServiceStop, runSupervisor, runSupervisorServiceDaemon, spawnSupervisorService, supervisorServiceLogPath, } from "../core/supervisor/index.js";
7
+ import { approveSupervisorPlan, configureSupervisorService, createSupervisor, listSupervisors, readSupervisor, readSupervisorPlan, readSupervisorServiceConfig, readSupervisorServiceStatus, rejectSupervisorPlan, requestSupervisorServiceStop, runSupervisor, runSupervisorServiceDaemon, spawnSupervisorService, supervisorServiceLogPath, } from "../core/supervisor/index.js";
8
8
  export function registerSupervisorCommand(program, emit) {
9
9
  const registry = createBuiltinHarnessRegistry();
10
10
  const supervisor = program
@@ -25,6 +25,7 @@ export function registerSupervisorCommand(program, emit) {
25
25
  .option("--accept-passing-proof", "Allow the supervisor to explicitly accept passing proof")
26
26
  .option("--no-resume-approved", "Stop after an approval instead of resuming its parked run")
27
27
  .option("--retry-blocked", "Allow bounded retry of blocked work")
28
+ .option("--replanning <file>", "Frozen planner policy and allowed workflow-template catalog")
28
29
  .option("--json", "Emit the complete supervisor record as JSON")
29
30
  .action((rootWorkId, opts) => {
30
31
  withSupervisorRoot(emit, (coordRoot) => {
@@ -53,6 +54,7 @@ export function registerSupervisorCommand(program, emit) {
53
54
  resume_approved: opts.resumeApproved,
54
55
  retry_blocked: opts.retryBlocked,
55
56
  },
57
+ replanning: opts.replanning ? readReplanningFile(opts.replanning) : undefined,
56
58
  }), opts.json, emit, true);
57
59
  });
58
60
  });
@@ -84,10 +86,78 @@ export function registerSupervisorCommand(program, emit) {
84
86
  emitSupervisor(readSupervisor(coordRoot, goalId), opts.json, emit, true);
85
87
  });
86
88
  });
89
+ registerPlanCommand(supervisor, emit);
87
90
  registerServiceCommand(supervisor, registry, emit);
88
91
  registerRunCommand(supervisor, "tick", registry, emit);
89
92
  registerRunCommand(supervisor, "run", registry, emit);
90
93
  }
94
+ function registerPlanCommand(supervisor, emit) {
95
+ const plan = supervisor
96
+ .command("plan")
97
+ .description("Inspect and resolve bounded planner proposals for a durable goal.");
98
+ plan
99
+ .command("list <goal-id>")
100
+ .description("List append-only replanning attempts for one goal.")
101
+ .option("--json", "Emit complete plan records as JSON")
102
+ .action((goalId, opts) => {
103
+ withSupervisorRoot(emit, (coordRoot) => {
104
+ const plans = readSupervisor(coordRoot, goalId).plans;
105
+ if (opts.json) {
106
+ emit.config({ format: "json" });
107
+ emit.data(plans);
108
+ }
109
+ else if (plans.length === 0) {
110
+ emit.text(`supervisor ${goalId} has no replanning attempts\n`);
111
+ }
112
+ else {
113
+ emit.text(`${plans.map(renderPlanRow).join("\n")}\n`);
114
+ }
115
+ });
116
+ });
117
+ plan
118
+ .command("show <goal-id> <plan-id>")
119
+ .description("Show one planner request, schema-gated proposal, and audit events.")
120
+ .option("--json", "Emit the complete plan record as JSON")
121
+ .action((goalId, planId, opts) => {
122
+ withSupervisorRoot(emit, (coordRoot) => {
123
+ emitPlan(readSupervisorPlan(coordRoot, goalId, planId), opts.json, emit);
124
+ });
125
+ });
126
+ plan
127
+ .command("approve <goal-id> <plan-id>")
128
+ .description("Materialize a reviewed proposal and advance the active immutable root.")
129
+ .option("--actor <name>", "Actor recorded on the plan decision")
130
+ .option("--reason <text>", "Reason for approval")
131
+ .option("--json", "Emit the plan outcome as JSON")
132
+ .action((goalId, planId, opts) => {
133
+ withSupervisorRoot(emit, (coordRoot) => {
134
+ emitPlanOutcome(approveSupervisorPlan({
135
+ coordRoot,
136
+ goalId,
137
+ planId,
138
+ actor: opts.actor,
139
+ reason: opts.reason,
140
+ }), opts.json, emit);
141
+ });
142
+ });
143
+ plan
144
+ .command("reject <goal-id> <plan-id>")
145
+ .description("Reject a pending proposal without mutating durable work.")
146
+ .requiredOption("--reason <text>", "Reason the proposal is rejected")
147
+ .option("--actor <name>", "Actor recorded on the plan decision")
148
+ .option("--json", "Emit the plan outcome as JSON")
149
+ .action((goalId, planId, opts) => {
150
+ withSupervisorRoot(emit, (coordRoot) => {
151
+ emitPlanOutcome(rejectSupervisorPlan({
152
+ coordRoot,
153
+ goalId,
154
+ planId,
155
+ actor: opts.actor,
156
+ reason: opts.reason,
157
+ }), opts.json, emit);
158
+ });
159
+ });
160
+ }
91
161
  function registerServiceCommand(supervisor, registry, emit) {
92
162
  const service = supervisor
93
163
  .command("service")
@@ -355,6 +425,56 @@ function readTeamFile(path) {
355
425
  }
356
426
  return value;
357
427
  }
428
+ function readReplanningFile(path) {
429
+ const absolute = resolve(path);
430
+ let value;
431
+ try {
432
+ value = JSON.parse(readFileSync(absolute, "utf8"));
433
+ }
434
+ catch (error) {
435
+ throw new Error(`cannot read supervisor replanning policy at ${absolute}: ${error.message}`);
436
+ }
437
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
438
+ throw new Error("supervisor replanning policy must be a JSON object");
439
+ }
440
+ const config = value;
441
+ if (typeof config.planner_specialist !== "string") {
442
+ throw new Error("supervisor replanning planner_specialist must be a string");
443
+ }
444
+ if (!config.templates ||
445
+ typeof config.templates !== "object" ||
446
+ Array.isArray(config.templates)) {
447
+ throw new Error("supervisor replanning templates must be an object");
448
+ }
449
+ const base = dirname(absolute);
450
+ const templates = Object.fromEntries(Object.entries(config.templates).map(([id, raw]) => {
451
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
452
+ throw new Error(`supervisor replanning template ${id} must be an object`);
453
+ }
454
+ const template = raw;
455
+ if (typeof template.workflow !== "string") {
456
+ throw new Error(`supervisor replanning template ${id} workflow must be a string`);
457
+ }
458
+ return [
459
+ id,
460
+ {
461
+ workflowPath: isAbsolute(template.workflow)
462
+ ? template.workflow
463
+ : resolve(base, template.workflow),
464
+ maxAttempts: jsonInteger(template.max_attempts, `template ${id} max_attempts`),
465
+ root: jsonBoolean(template.root, `template ${id} root`),
466
+ },
467
+ ];
468
+ }));
469
+ return {
470
+ plannerSpecialist: config.planner_specialist,
471
+ autoApply: jsonBoolean(config.auto_apply, "replanning auto_apply"),
472
+ maxReplans: jsonInteger(config.max_replans, "replanning max_replans"),
473
+ maxWorkItemsPerPlan: jsonInteger(config.max_work_items_per_plan, "replanning max_work_items_per_plan"),
474
+ maxTotalWorkItems: jsonInteger(config.max_total_work_items, "replanning max_total_work_items"),
475
+ templates,
476
+ };
477
+ }
358
478
  function emitSupervisor(record, json, emit, detail = false) {
359
479
  if (json) {
360
480
  emit.config({ format: "json" });
@@ -369,7 +489,7 @@ function emitSupervisor(record, json, emit, detail = false) {
369
489
  const lines = [
370
490
  `${record.intent.id}: ${record.intent.title}`,
371
491
  `state: ${projection.state}`,
372
- `root: ${record.intent.root_work_id}`,
492
+ `root: ${projection.root_work_id}`,
373
493
  `reason: ${projection.reason}`,
374
494
  `next: ${projection.next_action}`,
375
495
  `work: ${projection.work_ids.length}`,
@@ -378,6 +498,14 @@ function emitSupervisor(record, json, emit, detail = false) {
378
498
  `automation: accept=${record.intent.automation.accept_passing_proof}, ` +
379
499
  `resume=${record.intent.automation.resume_approved}, retry=${record.intent.automation.retry_blocked}`,
380
500
  ];
501
+ if (record.intent.replanning) {
502
+ lines.push(`replanning: generation=${projection.plan_generation}, used=${projection.replans_used}/${record.intent.replanning.max_replans}, auto_apply=${record.intent.replanning.auto_apply}`);
503
+ if (projection.root_work_id !== record.intent.root_work_id) {
504
+ lines.push(`original root: ${record.intent.root_work_id}`);
505
+ }
506
+ if (projection.pending_plan_id)
507
+ lines.push(`pending plan: ${projection.pending_plan_id}`);
508
+ }
381
509
  if (projection.attention_work.length) {
382
510
  lines.push(`attention: ${projection.attention_work.join(", ")}`);
383
511
  }
@@ -392,6 +520,7 @@ function emitSupervisorReport(report, json, emit) {
392
520
  emit.text(`supervisor ${report.goal_id}: ${report.stop_reason}\n` +
393
521
  `reason: ${report.reason}\n` +
394
522
  `cycles: ${report.cycles}; dispatches: ${report.dispatches}; acceptances: ${report.acceptances}\n` +
523
+ `replans: ${report.replans}\n` +
395
524
  `state: ${report.projection.state}; next: ${report.projection.next_action}\n`);
396
525
  }
397
526
  function renderSupervisorRow(record) {
@@ -405,6 +534,58 @@ function integer(value) {
405
534
  throw new Error(`expected a positive integer, got ${JSON.stringify(value)}`);
406
535
  return Number.parseInt(value, 10);
407
536
  }
537
+ function jsonInteger(value, field) {
538
+ if (value === undefined)
539
+ return undefined;
540
+ if (!Number.isSafeInteger(value) || value < 1) {
541
+ throw new Error(`${field} must be a positive integer`);
542
+ }
543
+ return value;
544
+ }
545
+ function jsonBoolean(value, field) {
546
+ if (value === undefined)
547
+ return undefined;
548
+ if (typeof value !== "boolean")
549
+ throw new Error(`${field} must be boolean`);
550
+ return value;
551
+ }
552
+ function emitPlan(plan, json, emit) {
553
+ if (json) {
554
+ emit.config({ format: "json" });
555
+ emit.data(plan);
556
+ return;
557
+ }
558
+ const lines = [
559
+ `${plan.request.id}: ${plan.status}`,
560
+ `goal: ${plan.request.goal_id}`,
561
+ `sequence: ${plan.request.sequence}`,
562
+ `prior root: ${plan.request.prior_root_work_id}`,
563
+ `planner run: ${plan.request.workflow_run_id}`,
564
+ ];
565
+ if (plan.proposal) {
566
+ lines.push(`decision: ${plan.proposal.decision}`);
567
+ lines.push(`rationale: ${plan.proposal.rationale}`);
568
+ lines.push(`proposed work: ${plan.proposal.work.length}`);
569
+ }
570
+ if (plan.root_work_id)
571
+ lines.push(`applied root: ${plan.root_work_id}`);
572
+ if (plan.approval_id)
573
+ lines.push(`approval: ${plan.approval_id}`);
574
+ emit.text(`${lines.join("\n")}\n`);
575
+ }
576
+ function emitPlanOutcome(outcome, json, emit) {
577
+ if (json) {
578
+ emit.config({ format: "json" });
579
+ emit.data(outcome);
580
+ return;
581
+ }
582
+ emit.text(`supervisor plan ${outcome.plan_id}: ${outcome.status}\n` +
583
+ `${outcome.reason ? `reason: ${outcome.reason}\n` : ""}` +
584
+ `${outcome.root_work_id ? `root: ${outcome.root_work_id}\n` : ""}`);
585
+ }
586
+ function renderPlanRow(plan) {
587
+ return `${plan.request.id} ${plan.status.padEnd(18)} ${plan.request.prior_root_work_id}`;
588
+ }
408
589
  function delay(ms) {
409
590
  return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
410
591
  }
@@ -1,3 +1,6 @@
1
+ export { approveSupervisorPlan, rejectSupervisorPlan } from "./plan-api.js";
2
+ export { readSupervisorPlan, readSupervisorPlans } from "./plan-read.js";
3
+ export { type CreateSupervisorPlanTemplateInput, type CreateSupervisorReplanningInput, SUPERVISOR_PLAN_SCHEMA_VERSION, type SupervisorPlanEvent, type SupervisorPlanEventType, type SupervisorPlanHistory, type SupervisorPlanOutcome, type SupervisorPlanProposal, type SupervisorPlanRecord, type SupervisorPlanRequest, type SupervisorPlanStatus, type SupervisorPlanTemplate, type SupervisorPlanWorkSpec, type SupervisorReplanningPolicy, } from "./plan-types.js";
1
4
  export { type RunSupervisorInput, runSupervisor, type SupervisorDispatchOutcome, type SupervisorRunReport, type SupervisorStopReason, } from "./runner.js";
2
5
  export { type ConfigureSupervisorServiceInput, configureSupervisorService, type RunSupervisorServiceDaemonInput, type RunSupervisorServiceSweepInput, readSupervisorServiceConfig, readSupervisorServiceRuntime, readSupervisorServiceStatus, requestSupervisorServiceStop, runSupervisorServiceDaemon, runSupervisorServiceSweep, SUPERVISOR_SERVICE_CONFIG_SCHEMA_VERSION, SUPERVISOR_SERVICE_RUNTIME_SCHEMA_VERSION, SUPERVISOR_SERVICE_STATUS_SCHEMA_VERSION, type SupervisorServiceConfig, type SupervisorServiceEngineConfig, type SupervisorServiceGoalRuntime, type SupervisorServiceGoalState, type SupervisorServiceProcessState, type SupervisorServiceRuntime, type SupervisorServiceStatus, type SupervisorServiceStatusRecord, type SupervisorServiceSweepOutcome, type SupervisorServiceSweepReport, spawnSupervisorService, supervisorServiceLogPath, } from "./service.js";
3
6
  export { assertSupervisorId, type CreateSupervisorInput, collectSupervisorWork, createSupervisor, listSupervisors, newSupervisorId, readSupervisor, SUPERVISOR_INTENT_SCHEMA_VERSION, type SupervisorAutomationPolicy, type SupervisorIntent, type SupervisorLimits, type SupervisorNextAction, type SupervisorProjection, type SupervisorRecord, type SupervisorState, } from "./state.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/supervisor/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EACvB,aAAa,EACb,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,GAC1B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,+BAA+B,EACpC,0BAA0B,EAC1B,KAAK,+BAA+B,EACpC,KAAK,8BAA8B,EACnC,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC3B,4BAA4B,EAC5B,0BAA0B,EAC1B,yBAAyB,EACzB,wCAAwC,EACxC,yCAAyC,EACzC,wCAAwC,EACxC,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,6BAA6B,EAClC,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,KAAK,qBAAqB,EAC1B,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,cAAc,EACd,gCAAgC,EAChC,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,eAAe,GACrB,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/supervisor/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACzE,OAAO,EACL,KAAK,iCAAiC,EACtC,KAAK,+BAA+B,EACpC,8BAA8B,EAC9B,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,KAAK,0BAA0B,GAChC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,KAAK,kBAAkB,EACvB,aAAa,EACb,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,GAC1B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,+BAA+B,EACpC,0BAA0B,EAC1B,KAAK,+BAA+B,EACpC,KAAK,8BAA8B,EACnC,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC3B,4BAA4B,EAC5B,0BAA0B,EAC1B,yBAAyB,EACzB,wCAAwC,EACxC,yCAAyC,EACzC,wCAAwC,EACxC,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,KAAK,0BAA0B,EAC/B,KAAK,6BAA6B,EAClC,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,KAAK,6BAA6B,EAClC,KAAK,4BAA4B,EACjC,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,KAAK,qBAAqB,EAC1B,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,cAAc,EACd,gCAAgC,EAChC,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,eAAe,GACrB,MAAM,YAAY,CAAC"}
@@ -1,3 +1,6 @@
1
+ export { approveSupervisorPlan, rejectSupervisorPlan } from "./plan-api.js";
2
+ export { readSupervisorPlan, readSupervisorPlans } from "./plan-read.js";
3
+ export { SUPERVISOR_PLAN_SCHEMA_VERSION, } from "./plan-types.js";
1
4
  export { runSupervisor, } from "./runner.js";
2
5
  export { configureSupervisorService, readSupervisorServiceConfig, readSupervisorServiceRuntime, readSupervisorServiceStatus, requestSupervisorServiceStop, runSupervisorServiceDaemon, runSupervisorServiceSweep, SUPERVISOR_SERVICE_CONFIG_SCHEMA_VERSION, SUPERVISOR_SERVICE_RUNTIME_SCHEMA_VERSION, SUPERVISOR_SERVICE_STATUS_SCHEMA_VERSION, spawnSupervisorService, supervisorServiceLogPath, } from "./service.js";
3
6
  export { assertSupervisorId, collectSupervisorWork, createSupervisor, listSupervisors, newSupervisorId, readSupervisor, SUPERVISOR_INTENT_SCHEMA_VERSION, } from "./state.js";
@@ -0,0 +1,16 @@
1
+ import type { SupervisorPlanOutcome } from "./plan-types.js";
2
+ export declare function approveSupervisorPlan(input: {
3
+ coordRoot: string;
4
+ goalId: string;
5
+ planId: string;
6
+ actor?: string;
7
+ reason?: string;
8
+ }): SupervisorPlanOutcome;
9
+ export declare function rejectSupervisorPlan(input: {
10
+ coordRoot: string;
11
+ goalId: string;
12
+ planId: string;
13
+ actor?: string;
14
+ reason: string;
15
+ }): SupervisorPlanOutcome;
16
+ //# sourceMappingURL=plan-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan-api.d.ts","sourceRoot":"","sources":["../../../src/core/supervisor/plan-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAI7D,wBAAgB,qBAAqB,CAAC,KAAK,EAAE;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,qBAAqB,CAcxB;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,qBAAqB,CAcxB"}
@@ -0,0 +1,34 @@
1
+ import { applySupervisorPlanProposal, rejectSupervisorPlanProposal } from "./planning.js";
2
+ import { acquireSupervisorLease, readSupervisorIgnoringLease } from "./state.js";
3
+ export function approveSupervisorPlan(input) {
4
+ const actor = input.actor?.trim() || `supervisor:${input.goalId}`;
5
+ const release = acquireSupervisorLease(input.coordRoot, input.goalId);
6
+ try {
7
+ return applySupervisorPlanProposal({
8
+ coordRoot: input.coordRoot,
9
+ record: readSupervisorIgnoringLease(input.coordRoot, input.goalId),
10
+ planId: input.planId,
11
+ actor,
12
+ reason: input.reason,
13
+ });
14
+ }
15
+ finally {
16
+ release();
17
+ }
18
+ }
19
+ export function rejectSupervisorPlan(input) {
20
+ const actor = input.actor?.trim() || `supervisor:${input.goalId}`;
21
+ const release = acquireSupervisorLease(input.coordRoot, input.goalId);
22
+ try {
23
+ return rejectSupervisorPlanProposal({
24
+ coordRoot: input.coordRoot,
25
+ goalId: input.goalId,
26
+ planId: input.planId,
27
+ actor,
28
+ reason: input.reason,
29
+ });
30
+ }
31
+ finally {
32
+ release();
33
+ }
34
+ }
@@ -0,0 +1,4 @@
1
+ import { type SupervisorPlanHistory, type SupervisorPlanRecord } from "./plan-types.js";
2
+ export declare function readSupervisorPlans(coordRootRaw: string, goalId: string, originalRootWorkId: string): SupervisorPlanHistory;
3
+ export declare function readSupervisorPlan(coordRootRaw: string, goalId: string, planId: string): SupervisorPlanRecord;
4
+ //# sourceMappingURL=plan-read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan-read.d.ts","sourceRoot":"","sources":["../../../src/core/supervisor/plan-read.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,qBAAqB,EAE1B,KAAK,oBAAoB,EAE1B,MAAM,iBAAiB,CAAC;AAsBzB,wBAAgB,mBAAmB,CACjC,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,MAAM,GACzB,qBAAqB,CAoDvB;AAED,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,oBAAoB,CAetB"}
@@ -0,0 +1,269 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { SUPERVISOR_PLAN_SCHEMA_VERSION, } from "./plan-types.js";
4
+ const PLAN_ID = /^plan-[0-9]{4}-[a-f0-9]{8}$/;
5
+ const GOAL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
6
+ const WORK_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
7
+ const APPROVAL_ID = /^apr-[a-f0-9]{20}$/;
8
+ const PLAN_KEY = /^[a-z][a-z0-9-]{0,31}$/;
9
+ const TEMPLATE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
+ const MAX_PLANS = 100;
11
+ const MAX_RECORD_BYTES = 256 * 1024;
12
+ const MAX_EVENTS_BYTES = 512 * 1024;
13
+ const MAX_EVENTS = 100;
14
+ const EVENT_TYPES = new Set([
15
+ "plan.awaiting_approval",
16
+ "plan.resumed",
17
+ "plan.proposed",
18
+ "plan.applied",
19
+ "plan.rejected",
20
+ "plan.attention",
21
+ "plan.failed",
22
+ ]);
23
+ export function readSupervisorPlans(coordRootRaw, goalId, originalRootWorkId) {
24
+ assertId(goalId, GOAL_ID, "supervisor id");
25
+ assertId(originalRootWorkId, WORK_ID, "work id");
26
+ const coordRoot = resolve(coordRootRaw);
27
+ const root = plansRoot(coordRoot, goalId);
28
+ if (!existsSync(root)) {
29
+ return {
30
+ plans: [],
31
+ active_root_work_id: originalRootWorkId,
32
+ generation: 0,
33
+ applied_work_ids: [],
34
+ materialized_work_ids: [],
35
+ };
36
+ }
37
+ const entries = readdirSync(root, { withFileTypes: true })
38
+ .filter((entry) => entry.isDirectory() && PLAN_ID.test(entry.name))
39
+ .map((entry) => entry.name);
40
+ if (entries.length > MAX_PLANS)
41
+ throw new Error(`supervisor plan history exceeds ${MAX_PLANS}`);
42
+ const plans = entries
43
+ .map((planId) => readSupervisorPlan(coordRootRaw, goalId, planId))
44
+ .sort((left, right) => left.request.sequence - right.request.sequence);
45
+ const sequences = new Set();
46
+ for (const plan of plans) {
47
+ if (sequences.has(plan.request.sequence)) {
48
+ throw new Error(`supervisor ${goalId} has duplicate plan sequence ${plan.request.sequence}`);
49
+ }
50
+ sequences.add(plan.request.sequence);
51
+ }
52
+ let activeRoot = originalRootWorkId;
53
+ let generation = 0;
54
+ const appliedWork = new Set();
55
+ const materializedWork = new Set();
56
+ for (const plan of plans) {
57
+ for (const spec of plan.proposal?.work ?? []) {
58
+ const workId = `${plan.request.id}-${spec.key}`;
59
+ if (existsSync(join(coordRoot, ".harnery", "work", workId, "intent.json"))) {
60
+ materializedWork.add(workId);
61
+ }
62
+ }
63
+ if (plan.status !== "applied" || !plan.root_work_id)
64
+ continue;
65
+ activeRoot = plan.root_work_id;
66
+ generation++;
67
+ for (const workId of plan.work_ids)
68
+ appliedWork.add(workId);
69
+ }
70
+ return {
71
+ plans,
72
+ active_root_work_id: activeRoot,
73
+ generation,
74
+ applied_work_ids: [...appliedWork],
75
+ materialized_work_ids: [...materializedWork],
76
+ latest: plans.at(-1),
77
+ };
78
+ }
79
+ export function readSupervisorPlan(coordRootRaw, goalId, planId) {
80
+ assertId(goalId, GOAL_ID, "supervisor id");
81
+ assertId(planId, PLAN_ID, "supervisor plan id");
82
+ const coordRoot = resolve(coordRootRaw);
83
+ const dir = planDir(coordRoot, goalId, planId);
84
+ const request = readJson(join(dir, "request.json"), "plan request");
85
+ validateRequest(request, goalId, planId);
86
+ const proposalPath = join(dir, "proposal.json");
87
+ const proposal = existsSync(proposalPath)
88
+ ? readJson(proposalPath, "plan proposal")
89
+ : undefined;
90
+ if (proposal)
91
+ validateProposalEnvelope(proposal, planId);
92
+ const events = readEvents(join(dir, "events.jsonl"), planId);
93
+ const derived = deriveStatus(coordRoot, events, proposal);
94
+ return { request, proposal, events, ...derived };
95
+ }
96
+ function deriveStatus(coordRoot, events, proposal) {
97
+ const latest = events.at(-1);
98
+ const applied = [...events].reverse().find((event) => event.event === "plan.applied");
99
+ if (applied) {
100
+ return {
101
+ status: "applied",
102
+ root_work_id: applied.root_work_id,
103
+ work_ids: applied.work_ids ?? [],
104
+ reason: applied.reason,
105
+ };
106
+ }
107
+ if (latest?.event === "plan.rejected") {
108
+ return { status: "rejected", work_ids: [], reason: latest.reason };
109
+ }
110
+ if (latest?.event === "plan.attention") {
111
+ return { status: "attention", work_ids: [], reason: latest.reason };
112
+ }
113
+ if (latest?.event === "plan.failed") {
114
+ return { status: "failed", work_ids: [], reason: latest.reason };
115
+ }
116
+ const parked = [...events].reverse().find((event) => event.event === "plan.awaiting_approval");
117
+ const resumedAfterPark = parked !== undefined &&
118
+ events.some((event) => event.event === "plan.resumed" && event.seq > parked.seq);
119
+ if (parked?.approval_id && !resumedAfterPark) {
120
+ return {
121
+ status: approvalIsResolved(coordRoot, parked.approval_id) ? "resumable" : "awaiting_approval",
122
+ approval_id: parked.approval_id,
123
+ work_ids: [],
124
+ reason: parked.reason,
125
+ };
126
+ }
127
+ if (proposal)
128
+ return { status: "proposed", work_ids: [], reason: proposal.rationale };
129
+ return { status: "interrupted", work_ids: [], reason: latest?.reason };
130
+ }
131
+ function readEvents(path, planId) {
132
+ if (!existsSync(path))
133
+ return [];
134
+ const size = statSync(path).size;
135
+ if (size > MAX_EVENTS_BYTES)
136
+ throw new Error("supervisor plan events exceed their byte limit");
137
+ const body = readFileSync(path, "utf8");
138
+ if (body && !body.endsWith("\n"))
139
+ throw new Error(`supervisor plan ${planId} has a partial event`);
140
+ const lines = body.split("\n").filter(Boolean);
141
+ if (lines.length > MAX_EVENTS)
142
+ throw new Error(`supervisor plan exceeds ${MAX_EVENTS} events`);
143
+ return lines.map((line, index) => {
144
+ let event;
145
+ try {
146
+ event = JSON.parse(line);
147
+ }
148
+ catch (error) {
149
+ throw new Error(`cannot parse supervisor plan ${planId} event ${index + 1}: ${error.message}`);
150
+ }
151
+ validateEvent(event, planId, index + 1);
152
+ return event;
153
+ });
154
+ }
155
+ function validateRequest(request, goalId, planId) {
156
+ if (request.schema_version !== SUPERVISOR_PLAN_SCHEMA_VERSION ||
157
+ request.id !== planId ||
158
+ request.goal_id !== goalId ||
159
+ !Number.isSafeInteger(request.sequence) ||
160
+ request.sequence < 1 ||
161
+ request.sequence > MAX_PLANS ||
162
+ typeof request.trigger_fingerprint !== "string" ||
163
+ request.trigger_fingerprint.length < 1 ||
164
+ request.trigger_fingerprint.length > 64_000 ||
165
+ !WORK_ID.test(request.prior_root_work_id) ||
166
+ !/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(request.workflow_run_id) ||
167
+ !validTimestamp(request.created_at)) {
168
+ throw new Error(`supervisor plan request ${planId} has an unsupported schema`);
169
+ }
170
+ }
171
+ function validateProposalEnvelope(proposal, planId) {
172
+ if (proposal.schema_version !== SUPERVISOR_PLAN_SCHEMA_VERSION ||
173
+ proposal.plan_id !== planId ||
174
+ !["apply", "attention"].includes(proposal.decision) ||
175
+ typeof proposal.rationale !== "string" ||
176
+ proposal.rationale.length < 1 ||
177
+ proposal.rationale.length > 2_000 ||
178
+ !Array.isArray(proposal.work) ||
179
+ proposal.work.length > 25 ||
180
+ typeof proposal.root !== "string" ||
181
+ proposal.root.length > 32 ||
182
+ !validTimestamp(proposal.proposed_at)) {
183
+ throw new Error(`supervisor plan proposal ${planId} has an unsupported schema`);
184
+ }
185
+ for (const [index, spec] of proposal.work.entries()) {
186
+ if (!spec ||
187
+ typeof spec !== "object" ||
188
+ !PLAN_KEY.test(spec.key) ||
189
+ typeof spec.title !== "string" ||
190
+ spec.title.length < 1 ||
191
+ spec.title.length > 200 ||
192
+ typeof spec.objective !== "string" ||
193
+ spec.objective.length < 1 ||
194
+ spec.objective.length > 4_000 ||
195
+ !Array.isArray(spec.acceptance) ||
196
+ spec.acceptance.length > 50 ||
197
+ spec.acceptance.some((value) => typeof value !== "string" || value.length > 500) ||
198
+ !Array.isArray(spec.dependencies) ||
199
+ spec.dependencies.length > 50 ||
200
+ spec.dependencies.some((value) => typeof value !== "string" || value.length > 100) ||
201
+ !TEMPLATE_ID.test(spec.template)) {
202
+ throw new Error(`supervisor plan proposal ${planId} work[${index}] is invalid`);
203
+ }
204
+ }
205
+ }
206
+ function validateEvent(event, planId, sequence) {
207
+ if (event.schema_version !== SUPERVISOR_PLAN_SCHEMA_VERSION ||
208
+ event.plan_id !== planId ||
209
+ event.seq !== sequence ||
210
+ !EVENT_TYPES.has(event.event) ||
211
+ !validTimestamp(event.ts) ||
212
+ typeof event.actor !== "string" ||
213
+ event.actor.length < 1 ||
214
+ event.actor.length > 200 ||
215
+ typeof event.reason !== "string" ||
216
+ event.reason.length < 1 ||
217
+ event.reason.length > 2_000) {
218
+ throw new Error(`supervisor plan ${planId} event ${sequence} has an unsupported schema`);
219
+ }
220
+ if (event.approval_id !== undefined && !APPROVAL_ID.test(event.approval_id)) {
221
+ throw new Error(`supervisor plan ${planId} event ${sequence} has an invalid approval id`);
222
+ }
223
+ if (event.root_work_id !== undefined && !WORK_ID.test(event.root_work_id)) {
224
+ throw new Error(`supervisor plan ${planId} event ${sequence} has an invalid root work id`);
225
+ }
226
+ if (event.work_ids !== undefined) {
227
+ if (!Array.isArray(event.work_ids) || event.work_ids.some((id) => !WORK_ID.test(id))) {
228
+ throw new Error(`supervisor plan ${planId} event ${sequence} has invalid work ids`);
229
+ }
230
+ }
231
+ }
232
+ function approvalIsResolved(coordRoot, approvalId) {
233
+ const path = join(coordRoot, ".harnery", "approvals", approvalId, "decision.json");
234
+ if (!existsSync(path))
235
+ return false;
236
+ try {
237
+ const value = readJson(path, "workflow approval decision");
238
+ return value.approval_id === approvalId && ["allow", "deny"].includes(String(value.verdict));
239
+ }
240
+ catch {
241
+ return false;
242
+ }
243
+ }
244
+ function readJson(path, label) {
245
+ if (!existsSync(path))
246
+ throw new Error(`${label} does not exist at ${path}`);
247
+ const size = statSync(path).size;
248
+ if (size <= 0 || size > MAX_RECORD_BYTES)
249
+ throw new Error(`${label} has invalid size ${size}`);
250
+ try {
251
+ return JSON.parse(readFileSync(path, "utf8"));
252
+ }
253
+ catch (error) {
254
+ throw new Error(`cannot parse ${label} at ${path}: ${error.message}`);
255
+ }
256
+ }
257
+ function plansRoot(coordRoot, goalId) {
258
+ return join(coordRoot, ".harnery", "supervisors", goalId, "plans");
259
+ }
260
+ function planDir(coordRoot, goalId, planId) {
261
+ return join(plansRoot(coordRoot, goalId), planId);
262
+ }
263
+ function assertId(value, pattern, label) {
264
+ if (!pattern.test(value))
265
+ throw new Error(`invalid ${label} ${JSON.stringify(value)}`);
266
+ }
267
+ function validTimestamp(value) {
268
+ return typeof value === "string" && value.length <= 40 && Number.isFinite(Date.parse(value));
269
+ }