@cardor/agent-harness-kit 1.10.5 → 2.0.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.
@@ -5,9 +5,6 @@ description: >
5
5
  relevant files, understands existing patterns, and produces a structured analysis for the
6
6
  builder to use. Invoke after the lead has defined a plan and before the builder starts.
7
7
  Never invoke for tasks that require writing or modifying files.
8
- tools:
9
- - Read
10
- - Bash
11
8
  ---
12
9
 
13
10
  # Explorer Agent — {{projectName}}
@@ -21,11 +18,13 @@ You are the **explorer agent** for `{{projectName}}`. Your job is to read and un
21
18
  - Search project docs for relevant guidance
22
19
  - Produce a structured analysis the builder can act on directly
23
20
 
24
- ## Allowed paths
21
+ ## Scope
25
22
 
26
- You may read files under: `{{allowedPaths}}`
23
+ You may read anything inside the project.
27
24
 
28
- If you need to read outside these paths, record that as a blocker do not proceed.
25
+ You never write. Your write tools are disabled, so do not plan changes that require
26
+ editing files — describe them for the builder instead. If a task genuinely requires
27
+ reading outside the project root, record that as a blocker — do not proceed.
29
28
 
30
29
  ---
31
30
 
@@ -35,18 +34,21 @@ These calls are **not optional**. The dashboard cannot display what you do not r
35
34
 
36
35
  ### Log every tool call you make
37
36
 
38
- After **each** tool invocation (Read, Bash, grep, docs.search), call:
37
+ `actions.record_tool` is **batch-only** — it takes an array of calls, never a single bespoke call. Accumulate the tool invocations you make (Read, Bash, grep, docs.search) as you go, and flush them periodically — every few calls, or at a natural checkpoint like finishing a file or a research thread — via:
39
38
 
40
39
  ```
41
- actions.record_tool(actionId, '<ToolName>', '<args-summary>', '<why>')
40
+ actions.record_tool(actionId, calls: [
41
+ { toolName: '<ToolName>', argsJson: '<args-summary>', resultSummary: '<why>' },
42
+ ...
43
+ ])
42
44
  ```
43
45
 
44
- Examples:
45
- - `actions.record_tool(actionId, 'Read', 'src/auth/middleware.ts', 'find existing JWT pattern')`
46
- - `actions.record_tool(actionId, 'Bash', 'grep -r "refreshToken" src/', 'locate all refresh token usages')`
47
- - `actions.record_tool(actionId, 'docs.search', 'authentication middleware', 'check project docs for auth guidance')`
46
+ Even a single tool call must go through this array shape — a one-element array, never a bespoke single-call form.
48
47
 
49
- **Every single tool call must be logged.** No silent reads. The Tools dashboard is built entirely from these `actions.record_tool` calls.
48
+ Example flush after a few calls:
49
+ - `actions.record_tool(actionId, calls: [{ toolName: 'Read', argsJson: 'src/auth/middleware.ts', resultSummary: 'find existing JWT pattern' }, { toolName: 'Bash', argsJson: 'grep -r "refreshToken" src/', resultSummary: 'locate all refresh token usages' }, { toolName: 'docs.search', argsJson: 'authentication middleware', resultSummary: 'check project docs for auth guidance' }])`
50
+
51
+ **Every tool call must be logged, eventually, in a batch.** No silent reads. The Tools dashboard is built entirely from these `actions.record_tool` calls — accumulate as you work and flush before completing, don't let entries pile up unflushed.
50
52
 
51
53
  ---
52
54
 
@@ -82,7 +84,7 @@ Do NOT read the entire codebase. Be targeted.
82
84
 
83
85
  ### 5. Log every tool call as you make it
84
86
 
85
- Log each invocation as described in the **MANDATORY TRACKING** section above — do it immediately after each tool call, not at the end.
87
+ Accumulate each invocation as described in the **MANDATORY TRACKING** section above and flush periodically in batches don't wait until the very end to record everything at once.
86
88
 
87
89
  ### 6. Produce a structured analysis
88
90
 
@@ -5,9 +5,6 @@ description: >
5
5
  delegate to explorer, builder, and reviewer in sequence, and close the session correctly.
6
6
  Invoke when starting a new work session, picking up a pending task, or when another agent
7
7
  reports a blocker that requires re-coordination.
8
- tools:
9
- - Read
10
- - Bash
11
8
  ---
12
9
 
13
10
  # Lead Agent — {{projectName}}
@@ -73,7 +70,10 @@ When in lightweight mode:
73
70
 
74
71
  ### File creation in lightweight mode
75
72
 
76
- You may only create files in lightweight mode if the user **explicitly** asks to save the output (e.g., "write the triage report to TRIAGE.md"). Even then, do not use the full harness pipeline — just write the file directly.
73
+ Your Write and Edit tools are disabled, so you cannot save output yourself not even in
74
+ lightweight mode. If the user **explicitly** asks to persist the result (e.g., "write the
75
+ triage report to TRIAGE.md"), delegate that single write to the builder. Do not spin up the
76
+ full harness pipeline for it; hand the builder the exact content and target path.
77
77
 
78
78
  > **If in lightweight mode: skip Step 1 (Orient) entirely.** No health.sh, no MCP calls.
79
79
 
@@ -95,18 +95,21 @@ These calls are **not optional**. The dashboard cannot display what you do not r
95
95
 
96
96
  ### Log every tool call you make
97
97
 
98
- After **each** tool invocation (Bash, tasks.get, tasks.claim, actions.get), call:
98
+ `actions.record_tool` is **batch-only** — it takes an array of calls, never a single bespoke call. As you work, accumulate the tool invocations you make (Bash, tasks.get, tasks.claim, actions.get) and flush them periodically — every few calls, or at a natural checkpoint — via:
99
99
 
100
100
  ```
101
- actions.record_tool(actionId, '<ToolName>', '<args-summary>', '<why>')
101
+ actions.record_tool(actionId, calls: [
102
+ { toolName: '<ToolName>', argsJson: '<args-summary>', resultSummary: '<why/result>' },
103
+ ...
104
+ ])
102
105
  ```
103
106
 
104
- Examples:
105
- - `actions.record_tool(actionId, 'Bash', 'bash health.sh', 'verify codebase health before making changes')`
106
- - `actions.record_tool(actionId, 'tasks.get', 'pending', 'find next task to claim')`
107
- - `actions.record_tool(actionId, 'actions.get', 'taskId=abc123', 'read action history to resume in-progress task')`
107
+ Even a single tool call must go through this array shape — a one-element array, never a bespoke single-call form.
108
108
 
109
- **Log every call.** This applies from the moment you have an `actionId` (after step 3 below).
109
+ Example flush after a few calls:
110
+ - `actions.record_tool(actionId, calls: [{ toolName: 'Bash', argsJson: 'bash health.sh', resultSummary: 'verify codebase health before making changes' }, { toolName: 'tasks.get', argsJson: 'pending', resultSummary: 'find next task to claim' }, { toolName: 'actions.get', argsJson: 'taskId=123', resultSummary: 'read action history to resume in-progress task' }])`
111
+
112
+ **Log every call, batched.** This applies from the moment you have an `actionId` (after step 3 below) — flush at each phase boundary rather than round-tripping once per individual tool use, and never let calls go unrecorded by the time you complete the action.
110
113
 
111
114
  ---
112
115
 
@@ -5,9 +5,6 @@ description: >
5
5
  for the current task. The reviewer reads the full action history, checks the builder's
6
6
  changes against each criterion, runs the health check, and either approves or blocks
7
7
  with specific, actionable feedback. Invoke only after the builder has completed its action.
8
- tools:
9
- - Read
10
- - Bash
11
8
  ---
12
9
 
13
10
  # Reviewer Agent — {{projectName}}
@@ -30,15 +27,19 @@ These calls are **not optional**. The dashboard cannot display what you do not r
30
27
 
31
28
  ### 1. Log every tool call you make
32
29
 
33
- After **each** tool invocation (Read, Bash), call:
30
+ `actions.record_tool` is **batch-only** — it takes an array of calls, never a single bespoke call. Accumulate each tool invocation (Read, Bash) as you go, and flush periodically — every few calls, or at a natural checkpoint — via:
34
31
 
35
32
  ```
36
- actions.record_tool(actionId, '<ToolName>', '<args-summary>', '<why>')
33
+ actions.record_tool(actionId, calls: [
34
+ { toolName: '<ToolName>', argsJson: '<args-summary>', resultSummary: '<why>' },
35
+ ...
36
+ ])
37
37
  ```
38
38
 
39
- Examples:
40
- - `actions.record_tool(actionId, 'Read', 'src/auth/middleware.ts', 'verify refresh token logic matches criterion 2')`
41
- - `actions.record_tool(actionId, 'Bash', 'npm test --testPathPattern=auth', 'confirm all auth tests pass')`
39
+ Even a single tool call must go through this array shape — a one-element array, never a bespoke single-call form.
40
+
41
+ Example flush after a few calls:
42
+ - `actions.record_tool(actionId, calls: [{ toolName: 'Read', argsJson: 'src/auth/middleware.ts', resultSummary: 'verify refresh token logic matches criterion 2' }, { toolName: 'Bash', argsJson: 'npm test --testPathPattern=auth', resultSummary: 'confirm all auth tests pass' }])`
42
43
 
43
44
  ### 2. Mark every acceptance criterion as you verify it
44
45
 
@@ -1,5 +1,4 @@
1
1
  // src/core/db.ts
2
- import { randomUUID } from "crypto";
3
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
4
3
  import { homedir } from "os";
5
4
  import { dirname, join, resolve } from "path";
@@ -10,10 +9,13 @@ var ActionRepository = class {
10
9
  this.driver = driver;
11
10
  }
12
11
  driver;
13
- async create(id, taskId, agent, now) {
14
- await this.driver.exec(
15
- `INSERT INTO actions (id, task_id, agent, status, created_at) VALUES (?, ?, ?, 'in_progress', ?)`,
16
- [id, taskId, agent, now]
12
+ /** Returns the new autoincrement id mirrors TaskRepository.add(). Since
13
+ * task #73, `actions.id` is a driver-generated INTEGER, not an
14
+ * application-generated UUID, so callers no longer pass an id in. */
15
+ async create(taskId, agent, now) {
16
+ return this.driver.insert(
17
+ `INSERT INTO actions (task_id, agent, status, created_at) VALUES (?, ?, 'in_progress', ?)`,
18
+ [taskId, agent, now]
17
19
  );
18
20
  }
19
21
  async complete(actionId, summary, now) {
@@ -359,7 +361,7 @@ var TaskRepository = class {
359
361
  };
360
362
 
361
363
  // src/core/db.ts
362
- var AUTOINCREMENT_TABLES = ["tasks", "task_acceptance", "action_sections", "action_files", "action_tools"];
364
+ var AUTOINCREMENT_TABLES = ["tasks", "task_acceptance", "actions", "action_sections", "action_files", "action_tools"];
363
365
  var TABLE_INSERT_ORDER = ["tasks", "task_acceptance", "actions", "action_sections", "action_files", "action_tools"];
364
366
  var TABLE_DELETE_ORDER = [...TABLE_INSERT_ORDER].reverse();
365
367
  var DEFAULT_SQLITE_PATH = ".harness/harness.db";
@@ -464,9 +466,8 @@ var HarnessDB = class {
464
466
  }
465
467
  // ─── Actions (public facade — delegates to ActionRepository) ──────────────
466
468
  async startAction(taskId, agent) {
467
- const id = randomUUID();
468
469
  const now = (/* @__PURE__ */ new Date()).toISOString();
469
- await this.actions.create(id, taskId, agent, now);
470
+ const id = await this.actions.create(taskId, agent, now);
470
471
  await this.regenerateCurrentMd();
471
472
  return await this.actions.getById(id);
472
473
  }
@@ -494,12 +495,34 @@ var HarnessDB = class {
494
495
  async getActionSections(actionId) {
495
496
  return this.actions.getSections(actionId);
496
497
  }
497
- async recordFile(actionId, filePath, operation, notes) {
498
- return this.actions.addFile(actionId, filePath, operation, notes ?? null);
498
+ /** Batch-only (task #74) records N files in one atomic transaction. There
499
+ * is no single-entry variant; callers pass a one-element array to log a
500
+ * single file. Mirrors the driver.transaction() pattern from claimTask()
501
+ * above: a fresh ActionRepository is bound to the tx driver so every
502
+ * insert in the loop participates in the same transaction and any failure
503
+ * rolls back the whole batch. Returns the number of files recorded. */
504
+ async recordFiles(actionId, files) {
505
+ return this.driver.transaction(async (tx) => {
506
+ const txActions = new ActionRepository(tx);
507
+ for (const f of files) {
508
+ await txActions.addFile(actionId, f.filePath, f.operation, f.notes ?? null);
509
+ }
510
+ return files.length;
511
+ });
499
512
  }
500
- async recordTool(actionId, toolName, argsJson, resultSummary) {
513
+ /** Batch-only (task #74) records N tool calls in one atomic transaction.
514
+ * See recordFiles() above for the pattern; a one-element array is the
515
+ * only way to log a single tool call. Returns the number of calls
516
+ * recorded. */
517
+ async recordTools(actionId, calls) {
501
518
  const now = (/* @__PURE__ */ new Date()).toISOString();
502
- return this.actions.addTool(actionId, toolName, argsJson ?? null, resultSummary ?? null, now);
519
+ return this.driver.transaction(async (tx) => {
520
+ const txActions = new ActionRepository(tx);
521
+ for (const c of calls) {
522
+ await txActions.addTool(actionId, c.toolName, c.argsJson ?? null, c.resultSummary ?? null, now);
523
+ }
524
+ return calls.length;
525
+ });
503
526
  }
504
527
  async getFilesForTask(taskId) {
505
528
  return this.actions.getFilesForTask(taskId);
@@ -696,6 +719,11 @@ async function resetAutoincrementSequences(tx, dbType) {
696
719
  }
697
720
  }
698
721
  async function importFullExport(destDriver, data, destDbType, opts = { truncateFirst: false }) {
722
+ if (data.actions.some((a) => typeof a.id !== "number")) {
723
+ throw new Error(
724
+ "This export was produced by an older version of agent-harness-kit (actions used text/UUID ids, pre-2.0) and cannot be imported into a database using the current integer-id actions schema. Re-exporting from the old build is the only way to fix this \u2014 importing this file as-is is not supported."
725
+ );
726
+ }
699
727
  await destDriver.transaction(async (tx) => {
700
728
  if (opts.truncateFirst) {
701
729
  await truncateAllTables(tx);
@@ -779,13 +807,13 @@ async function openDB(config, cwd, homeDir = homedir()) {
779
807
  const dbConfig = config.database;
780
808
  let driver;
781
809
  if (dbConfig.type === "postgres") {
782
- const { PostgresDriver } = await import("./postgres-IOQE32DM.js");
810
+ const { PostgresDriver } = await import("./postgres-BB4GY4PN.js");
783
811
  driver = new PostgresDriver(dbConfig);
784
812
  } else if (dbConfig.type === "mysql") {
785
- const { MySQLDriver } = await import("./mysql-THKQOXIS.js");
813
+ const { MySQLDriver } = await import("./mysql-AUPKARWA.js");
786
814
  driver = new MySQLDriver(dbConfig);
787
815
  } else {
788
- const { SQLiteDriver } = await import("./sqlite-TR4D324R.js");
816
+ const { SQLiteDriver } = await import("./sqlite-5OWKTUUZ.js");
789
817
  if (dbConfig.type !== "sqlite") {
790
818
  throw new Error("Invalid database type");
791
819
  }
@@ -823,6 +851,7 @@ export {
823
851
  HarnessDB,
824
852
  getRowCounts,
825
853
  isEmptyDatabase,
854
+ resetAutoincrementSequences,
826
855
  importFullExport,
827
856
  resolveSqlitePathForScope,
828
857
  resolveSqlitePath,
@@ -831,4 +860,4 @@ export {
831
860
  readStorageStateFile,
832
861
  openDB
833
862
  };
834
- //# sourceMappingURL=chunk-6PEIJ2D5.js.map
863
+ //# sourceMappingURL=chunk-JTACLEGM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/db.ts","../src/core/repositories/ActionRepository.ts","../src/core/repositories/StatsRepository.ts","../src/core/repositories/TaskRepository.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\n\nimport { ActionRepository } from './repositories/ActionRepository'\nimport { StatsRepository } from './repositories/StatsRepository'\nimport { TaskRepository } from './repositories/TaskRepository'\n\nimport type { DBDriver } from './drivers/types'\nimport type {\n ActionFileRow,\n ActionRow,\n ActionSectionRow,\n ActionToolRow,\n AgentName,\n HarnessConfig,\n StorageState,\n TaskAcceptanceRow,\n TaskRow,\n TaskStatus,\n} from '@/types'\n\n/** Full relational export of every table — used by `ahk migrate storage` and\n * `ahk export --json`. MUST include all 6 tables (tasks, task_acceptance,\n * actions, action_sections, action_files, action_tools); omitting any of\n * them silently drops user data during a migration. */\nexport interface FullExport {\n tasks: TaskRow[]\n taskAcceptance: TaskAcceptanceRow[]\n actions: ActionRow[]\n sections: ActionSectionRow[]\n actionFiles: ActionFileRow[]\n actionTools: ActionToolRow[]\n}\n\n/** Tables with an integer autoincrement/serial primary key, in FK-safe\n * insertion order (parents before children). Since task #73, `actions.id`\n * is a driver-generated autoincrement INTEGER (previously an\n * application-generated UUID/TEXT id, which is why it used to be excluded\n * from this list) — see src/core/drivers/migrate-actions.ts for the\n * one-time migration that upgrades a pre-existing DB in place. */\nconst AUTOINCREMENT_TABLES = ['tasks', 'task_acceptance', 'actions', 'action_sections', 'action_files', 'action_tools'] as const\n\n/** Full insertion order across all 6 tables, respecting FK constraints\n * (parent before child): tasks -> task_acceptance -> actions ->\n * action_sections/action_files/action_tools. */\nconst TABLE_INSERT_ORDER = ['tasks', 'task_acceptance', 'actions', 'action_sections', 'action_files', 'action_tools'] as const\n\n/** Reverse of TABLE_INSERT_ORDER — used to TRUNCATE a non-empty destination\n * safely (children before parents) when `--force` is used. */\nconst TABLE_DELETE_ORDER = [...TABLE_INSERT_ORDER].reverse()\n\n// ─── Global storage path resolution ────────────────────────────────────────\n\n/** Default relative sqlite path used whenever `LocalStorageConfig.sqlitePath`\n * is omitted, and as the fallback filename component for `scope: 'global'`\n * (which never reads a configured path at all — see resolveSqlitePath()).\n * Centralized here (task #56) to stop the literal '.harness/harness.db'\n * from drifting across config.ts/templates.ts/tests. */\nexport const DEFAULT_SQLITE_PATH = '.harness/harness.db'\n\n/** Default relative current.md fallback path, used as the fallback filename\n * component whenever a caller needs \"the local markdown path\" for a scope\n * that ISN'T `config.storage`'s own current scope — `markdownFallback.path`\n * only exists on `LocalStorageConfig`, so there's no field to read it from\n * when `config.storage.scope === 'global'`. See `defaultMarkdownPathForConfig`\n * usage in src/commands/migrate-storage.ts. */\nexport const DEFAULT_MARKDOWN_PATH = '.harness/current.md'\n\n/** Resolves the directory used for 'global' scope storage: ~/.harness/dbs/<projectId>/\n * Uses os.homedir() (not $HOME env var) for portability. Callers are\n * responsible for creating the directory (mkdirSync recursive) before use. */\nexport function resolveGlobalStorageDir(config: HarnessConfig, homeDir: string = homedir()): string {\n return join(homeDir, '.harness', 'dbs', config.storage.projectId)\n}\n\n// ─── DB class ─────────────────────────────────────────────────────────────────\n\nexport class HarnessDB {\n readonly tasks: TaskRepository\n readonly actions: ActionRepository\n readonly stats: StatsRepository\n private driver: DBDriver\n private config: HarnessConfig\n /** Overridable home directory, used to keep 'global' scope tests off the real $HOME. */\n private homeDir: string\n\n constructor(driver: DBDriver, config: HarnessConfig, homeDir: string = homedir()) {\n this.driver = driver\n this.config = config\n this.homeDir = homeDir\n this.tasks = new TaskRepository(driver)\n this.actions = new ActionRepository(driver)\n this.stats = new StatsRepository(driver)\n }\n\n // ─── Tasks (public facade — delegates to TaskRepository) ──────────────────\n\n async addTask(params: {\n slug: string\n title: string\n description?: string\n acceptance?: string[]\n }): Promise<TaskRow> {\n const taskId = await this.tasks.add({\n slug: params.slug,\n title: params.title,\n description: params.description,\n })\n if (params.acceptance?.length) {\n await this.tasks.addAcceptance(taskId, params.acceptance)\n }\n await this.regenerateCurrentMd()\n return (await this.tasks.getById(taskId))!\n }\n\n async getTasks(status?: TaskStatus, includeArchived = false): Promise<TaskRow[]> {\n return this.tasks.getAll(status, includeArchived)\n }\n\n async getTaskById(id: number): Promise<TaskRow | null> {\n return this.tasks.getById(id)\n }\n\n async getTaskBySlug(slug: string): Promise<TaskRow | null> {\n return this.tasks.getBySlug(slug)\n }\n\n async getTaskAcceptance(taskId: number): Promise<TaskAcceptanceRow[]> {\n return this.tasks.getAcceptance(taskId)\n }\n\n async updateTaskStatus(idOrSlug: number | string, status: TaskStatus): Promise<TaskRow> {\n const now = new Date().toISOString()\n const task =\n typeof idOrSlug === 'number'\n ? await this.tasks.getById(idOrSlug)\n : await this.tasks.getBySlug(idOrSlug)\n if (!task) throw new Error(`Task not found: ${idOrSlug}`)\n\n if (status === 'in_progress' && !task.started_at) {\n await this.tasks.setStatus(task.id, status, { started_at: now })\n } else if (status === 'done') {\n await this.tasks.setStatus(task.id, status, { completed_at: now })\n } else {\n await this.tasks.setStatus(task.id, status)\n }\n\n await this.regenerateCurrentMd()\n return (await this.tasks.getById(task.id))!\n }\n\n async claimTask(id: number, agent: string): Promise<TaskRow | null> {\n const now = new Date().toISOString()\n return this.driver.transaction(async (tx) => {\n // need to create a new TaskRepository instance bound to the transaction\n const txTasks = new TaskRepository(tx)\n const changed = await txTasks.claim(id, agent, now)\n if (!changed) return null\n const task = await txTasks.getById(id)\n if (!task || task.status !== 'in_progress' || task.assigned_to !== agent) return null\n await this.regenerateCurrentMd()\n return task\n })\n }\n\n async markAcceptanceMet(criterionId: number): Promise<void> {\n return this.tasks.markAcceptanceMet(criterionId)\n }\n\n async updateTask(id: number, params: { title?: string; description?: string | null; slug?: string }): Promise<TaskRow> {\n await this.tasks.update(id, params)\n await this.regenerateCurrentMd()\n return (await this.tasks.getById(id))!\n }\n\n async updateTaskAcceptance(taskId: number, criteria: string[]): Promise<void> {\n await this.tasks.replaceAcceptance(taskId, criteria)\n await this.regenerateCurrentMd()\n }\n\n async archiveTask(id: number): Promise<TaskRow> {\n await this.tasks.archive(id)\n await this.regenerateCurrentMd()\n return (await this.tasks.getById(id))!\n }\n\n async unarchiveTask(id: number): Promise<TaskRow> {\n await this.tasks.unarchive(id)\n await this.regenerateCurrentMd()\n return (await this.tasks.getById(id))!\n }\n\n async getArchivedTasks(): Promise<TaskRow[]> {\n return this.tasks.getArchived()\n }\n\n async getStatusSummary(): Promise<{ status: string; total: number }[]> {\n return this.tasks.getStatusSummary()\n }\n\n // ─── Actions (public facade — delegates to ActionRepository) ──────────────\n\n async startAction(taskId: number, agent: AgentName): Promise<ActionRow> {\n const now = new Date().toISOString()\n const id = await this.actions.create(taskId, agent, now)\n await this.regenerateCurrentMd()\n return (await this.actions.getById(id))!\n }\n\n async writeSection(actionId: number, sectionType: string, content: string): Promise<void> {\n const now = new Date().toISOString()\n await this.actions.addSection(actionId, sectionType, content, now)\n await this.regenerateCurrentMd()\n }\n\n async completeAction(actionId: number, summary: string): Promise<ActionRow> {\n const now = new Date().toISOString()\n await this.actions.complete(actionId, summary, now)\n await this.regenerateCurrentMd()\n return (await this.actions.getById(actionId))!\n }\n\n async closeOrphanedActions(taskId: number): Promise<number> {\n const now = new Date().toISOString()\n return this.actions.closeOrphaned(taskId, now)\n }\n\n async getAction(actionId: number): Promise<ActionRow | null> {\n return this.actions.getById(actionId)\n }\n\n async getActionsForTask(taskId: number): Promise<ActionRow[]> {\n return this.actions.getForTask(taskId)\n }\n\n async getActionSections(actionId: number): Promise<ActionSectionRow[]> {\n return this.actions.getSections(actionId)\n }\n\n /** Batch-only (task #74) — records N files in one atomic transaction. There\n * is no single-entry variant; callers pass a one-element array to log a\n * single file. Mirrors the driver.transaction() pattern from claimTask()\n * above: a fresh ActionRepository is bound to the tx driver so every\n * insert in the loop participates in the same transaction and any failure\n * rolls back the whole batch. Returns the number of files recorded. */\n async recordFiles(\n actionId: number,\n files: Array<{ filePath: string; operation: ActionFileRow['operation']; notes?: string }>,\n ): Promise<number> {\n return this.driver.transaction(async (tx) => {\n const txActions = new ActionRepository(tx)\n for (const f of files) {\n await txActions.addFile(actionId, f.filePath, f.operation, f.notes ?? null)\n }\n return files.length\n })\n }\n\n /** Batch-only (task #74) — records N tool calls in one atomic transaction.\n * See recordFiles() above for the pattern; a one-element array is the\n * only way to log a single tool call. Returns the number of calls\n * recorded. */\n async recordTools(\n actionId: number,\n calls: Array<{ toolName: string; argsJson?: string; resultSummary?: string }>,\n ): Promise<number> {\n const now = new Date().toISOString()\n return this.driver.transaction(async (tx) => {\n const txActions = new ActionRepository(tx)\n for (const c of calls) {\n await txActions.addTool(actionId, c.toolName, c.argsJson ?? null, c.resultSummary ?? null, now)\n }\n return calls.length\n })\n }\n\n async getFilesForTask(taskId: number): Promise<(ActionFileRow & { agent: AgentName })[]> {\n return this.actions.getFilesForTask(taskId)\n }\n\n async getTopTools(limit = 10): Promise<{ tool_name: string; uses: number }[]> {\n return this.actions.getTopTools(limit)\n }\n\n // ─── current.md fallback ──────────────────────────────────────────────────\n\n async regenerateCurrentMd(): Promise<void> {\n if (!this.config.storage.markdownFallback.enabled) return\n\n const mdPath =\n this.config.storage.scope === 'global'\n ? join(resolveGlobalStorageDir(this.config, this.homeDir), 'current.md')\n : resolve(this.config.storage.markdownFallback.path)\n mkdirSync(dirname(mdPath), { recursive: true })\n\n const inProgress = await this.tasks.getAll('in_progress')\n const now = new Date().toISOString()\n\n let md = `<!-- AUTO-GENERATED by agent-harness-kit — DO NOT EDIT MANUALLY -->\\n`\n md += `<!-- Last updated: ${now} -->\\n\\n`\n md += `# Current Session\\n\\n`\n\n if (inProgress.length === 0) {\n md += `## No tasks in progress\\n\\n`\n const pending = await this.tasks.getAll('pending')\n if (pending.length > 0) {\n md += `### Next pending tasks\\n`\n for (const t of pending.slice(0, 5)) {\n md += `- **#${t.id}** ${t.title} (\\`${t.slug}\\`)\\n`\n }\n }\n } else {\n for (const task of inProgress) {\n md += `## Active Task\\n`\n md += `- **ID:** ${task.id}\\n`\n md += `- **Slug:** ${task.slug}\\n`\n md += `- **Status:** ${task.status}\\n`\n md += `- **Started:** ${task.started_at ?? 'unknown'}\\n\\n`\n\n const taskActions = await this.actions.getForTask(task.id)\n if (taskActions.length > 0) {\n md += `## Actions this session\\n`\n md += `| Agent | Status | Summary | Started |\\n`\n md += `|----------|-------------|----------------------------------|-------------|\\n`\n for (const a of taskActions) {\n const started = a.created_at.slice(11, 16)\n const summary = (a.summary ?? '').slice(0, 34).padEnd(34)\n md += `| ${a.agent.padEnd(8)} | ${a.status.padEnd(11)} | ${summary} | ${started} |\\n`\n }\n md += `\\n`\n }\n\n const acceptance = await this.tasks.getAcceptance(task.id)\n if (acceptance.length > 0) {\n md += `## Acceptance Criteria\\n`\n for (const a of acceptance) {\n md += `- [${a.met ? 'x' : ' '}] ${a.criterion}\\n`\n }\n md += `\\n`\n }\n }\n }\n\n writeFileSync(mdPath, md, 'utf8')\n }\n\n // ─── Raw query escape hatch ───────────────────────────────────────────────\n\n async queryRaw<T = Record<string, unknown>>(sql: string, ...params: unknown[]): Promise<T[]> {\n return this.driver.query<T>(sql, params)\n }\n\n // ─── Export helpers ───────────────────────────────────────────────────────\n\n /** Full relational export of ALL 6 tables (tasks, task_acceptance, actions,\n * action_sections, action_files, action_tools). Extended for task #47 —\n * the previous version (tasks/actions/sections only) silently dropped\n * acceptance criteria and file/tool records on export/migrate. */\n async exportJson(): Promise<FullExport> {\n return {\n tasks: await this.tasks.getAll(undefined, true),\n taskAcceptance: await this.tasks.getAllAcceptance(),\n actions: await this.actions.getAll(),\n sections: await this.actions.getAllSections(),\n actionFiles: await this.actions.getAllFiles(),\n actionTools: await this.actions.getAllTools(),\n }\n }\n\n /** Row counts for all 6 tables against THIS db's driver — used to decide\n * whether a destination is \"empty\" (safe to import into directly) before\n * a migration. Counts are queried directly (COUNT(*)), never inferred\n * from storage-state.json. */\n async getRowCounts(): Promise<Record<(typeof TABLE_INSERT_ORDER)[number], number>> {\n return getRowCounts(this.driver)\n }\n\n /** Imports a full export into THIS db's driver — see standalone\n * `importFullExport()` for the transactional/rollback/sequence-reset\n * guarantees. `dbType` must match `this.config.database.type`. */\n async importFullExport(data: FullExport, dbType: 'sqlite' | 'postgres' | 'mysql', opts?: { truncateFirst: boolean }): Promise<void> {\n return importFullExport(this.driver, data, dbType, opts)\n }\n\n async reconnect(): Promise<void> {\n await this.driver.reconnect()\n }\n\n async close(): Promise<void> {\n await this.driver.close()\n }\n\n // ─── feature_list.json sync ───────────────────────────────────────────────\n\n async syncFromFeatureList(\n seeds: { slug: string; title: string; description?: string; acceptance?: string[] }[],\n ): Promise<{ added: number; skipped: number }> {\n let added = 0\n let skipped = 0\n for (const t of seeds) {\n if (await this.tasks.getBySlug(t.slug)) {\n skipped++\n continue\n }\n await this.addTask(t)\n added++\n }\n return { added, skipped }\n }\n\n async writeFeatureList(cwd: string): Promise<void> {\n const allTasks = await this.tasks.getAll(undefined, true)\n const list = await Promise.all(\n allTasks.map(async (t) => ({\n slug: t.slug,\n title: t.title,\n description: t.description ?? undefined,\n acceptance: (await this.tasks.getAcceptance(t.id)).map((a) => a.criterion),\n status: t.status,\n })),\n )\n const path = join(resolve(cwd), this.config.storage.dir, 'feature_list.json')\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(list, null, 2) + '\\n', 'utf8')\n }\n\n // ─── storage-state.json (real storage state, for `ahk migrate storage`) ──\n\n /** Writes .harness/storage-state.json, ALWAYS project-local regardless of\n * scope. Reflects the REAL current storage state (scope/projectId/dbType\n * actually in use right now), as opposed to agent-harness-kit.config.ts\n * which reflects the DESIRED state. Format is stable — task #47 (ahk\n * migrate storage) depends on it; do not change field names/shape. */\n async writeStorageState(cwd: string): Promise<void> {\n writeStorageStateFile(cwd, this.config.storage.dir, {\n scope: this.config.storage.scope,\n projectId: this.config.storage.projectId,\n dbType: this.config.database.type,\n migratedAt: new Date().toISOString(),\n })\n }\n}\n\n// ─── Full DB migration helpers (task #47 — `ahk migrate storage`) ─────────\n\n/** Row counts for all 6 tables, queried directly (never inferred). Used to\n * decide whether a destination DB is \"empty\" before an sqlite↔remote\n * migration. */\nexport async function getRowCounts(driver: DBDriver): Promise<Record<(typeof TABLE_INSERT_ORDER)[number], number>> {\n const counts = {} as Record<(typeof TABLE_INSERT_ORDER)[number], number>\n for (const table of TABLE_INSERT_ORDER) {\n const row = await driver.queryOne<{ n: number }>(`SELECT COUNT(*) as n FROM ${table}`)\n counts[table] = Number(row?.n ?? 0)\n }\n return counts\n}\n\n/** True if every table is empty (COUNT(*) = 0 for all 6 tables). */\nexport async function isEmptyDatabase(driver: DBDriver): Promise<boolean> {\n const counts = await getRowCounts(driver)\n return Object.values(counts).every((n) => n === 0)\n}\n\n/** Deletes all rows from all 6 tables, children-before-parents, so FK\n * constraints never block the delete. Only ever called immediately before\n * a `--force` import, inside the same transaction as the import itself —\n * never on its own. */\nasync function truncateAllTables(tx: DBDriver): Promise<void> {\n for (const table of TABLE_DELETE_ORDER) {\n await tx.exec(`DELETE FROM ${table}`)\n }\n}\n\n/** Re-synchronizes the destination's internal autoincrement/serial counter\n * with the highest id actually present, AFTER inserting rows with explicit\n * ids. Required because inserting explicit ids does NOT advance\n * Postgres SERIAL sequences or SQLite's `sqlite_sequence` table — without\n * this, the first unrelated `INSERT ... (no id)` after a migration (e.g.\n * `tasksRepository.add()`) would collide with an imported id.\n * MySQL AUTO_INCREMENT advances automatically on explicit-id inserts\n * greater than the current counter — no action needed there. */\nexport async function resetAutoincrementSequences(\n tx: DBDriver,\n dbType: 'sqlite' | 'postgres' | 'mysql',\n): Promise<void> {\n if (dbType === 'mysql') return // AUTO_INCREMENT self-advances on explicit-id insert — verified in tests.\n\n for (const table of AUTOINCREMENT_TABLES) {\n const row = await tx.queryOne<{ max: number | null }>(`SELECT MAX(id) as max FROM ${table}`)\n const max = row?.max\n if (!max) continue // table stayed empty — nothing to advance\n\n if (dbType === 'postgres') {\n await tx.execRaw(`SELECT setval(pg_get_serial_sequence('${table}','id'), ${max}, true)`)\n } else {\n // sqlite: sqlite_sequence only gets a row once a real AUTOINCREMENT\n // insert happens; explicit-id inserts bypass that, so upsert it.\n await tx.execRaw(\n `INSERT INTO sqlite_sequence (name, seq) SELECT '${table}', ${max} WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = '${table}')`,\n )\n await tx.execRaw(`UPDATE sqlite_sequence SET seq = ${max} WHERE name = '${table}'`)\n }\n }\n}\n\n/** Imports a full export (all 6 tables) into `destDriver`, preserving\n * original ids (required to keep foreign keys intact — see task #47\n * consultant advisory). The ENTIRE import (and, when `truncateFirst` is\n * set, the pre-import wipe) runs inside a single `destDriver.transaction()`\n * call: if anything fails partway, the whole operation rolls back and the\n * destination is left exactly as it was found.\n *\n * Callers MUST only mark the migration successful (e.g. call\n * `db.writeStorageState()`) AFTER this promise resolves without throwing —\n * never inside the transaction callback, never in a `finally`. */\nexport async function importFullExport(\n destDriver: DBDriver,\n data: FullExport,\n destDbType: 'sqlite' | 'postgres' | 'mysql',\n opts: { truncateFirst: boolean } = { truncateFirst: false },\n): Promise<void> {\n // Task #73: actions.id moved from a UUID/TEXT id to an autoincrement\n // INTEGER. An export produced by a pre-2.0 build still carries string\n // action ids, which would otherwise fail deep inside the transaction below\n // with a raw, confusing driver error (a datatype mismatch on sqlite's\n // INTEGER PRIMARY KEY rowid alias, or a hard insert error on postgres/\n // mysql). Fail fast with a clear, actionable message instead.\n if (data.actions.some((a) => typeof (a as { id: unknown }).id !== 'number')) {\n throw new Error(\n 'This export was produced by an older version of agent-harness-kit (actions used text/UUID ids, pre-2.0) and ' +\n 'cannot be imported into a database using the current integer-id actions schema. Re-exporting from the old build ' +\n 'is the only way to fix this — importing this file as-is is not supported.',\n )\n }\n\n await destDriver.transaction(async (tx) => {\n if (opts.truncateFirst) {\n await truncateAllTables(tx)\n }\n\n for (const task of data.tasks) {\n await tx.exec(\n `INSERT INTO tasks (id, slug, title, description, status, assigned_to, created_at, started_at, completed_at, archived_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n task.id,\n task.slug,\n task.title,\n task.description,\n task.status,\n task.assigned_to,\n task.created_at,\n task.started_at,\n task.completed_at,\n task.archived_at,\n task.updated_at,\n ],\n )\n }\n\n for (const ta of data.taskAcceptance) {\n await tx.exec(\n `INSERT INTO task_acceptance (id, task_id, criterion, met) VALUES (?, ?, ?, ?)`,\n [ta.id, ta.task_id, ta.criterion, ta.met],\n )\n }\n\n for (const action of data.actions) {\n await tx.exec(\n `INSERT INTO actions (id, task_id, agent, status, created_at, completed_at, summary) VALUES (?, ?, ?, ?, ?, ?, ?)`,\n [action.id, action.task_id, action.agent, action.status, action.created_at, action.completed_at, action.summary],\n )\n }\n\n for (const section of data.sections) {\n await tx.exec(\n `INSERT INTO action_sections (id, action_id, section_type, content, created_at) VALUES (?, ?, ?, ?, ?)`,\n [section.id, section.action_id, section.section_type, section.content, section.created_at],\n )\n }\n\n for (const file of data.actionFiles) {\n await tx.exec(\n `INSERT INTO action_files (id, action_id, file_path, operation, notes) VALUES (?, ?, ?, ?, ?)`,\n [file.id, file.action_id, file.file_path, file.operation, file.notes],\n )\n }\n\n for (const tool of data.actionTools) {\n await tx.exec(\n `INSERT INTO action_tools (id, action_id, tool_name, args_json, result_summary, called_at) VALUES (?, ?, ?, ?, ?, ?)`,\n [tool.id, tool.action_id, tool.tool_name, tool.args_json, tool.result_summary, tool.called_at],\n )\n }\n\n await resetAutoincrementSequences(tx, destDbType)\n })\n}\n\n/** Resolves the physical sqlite file path for a given scope, sharing the\n * exact convention `openDB()` uses — extracted so `ahk migrate storage` can\n * locate the OLD file (by scope) without duplicating path logic. Does not\n * create any directories or files. */\nexport function resolveSqlitePathForScope(\n scope: 'local' | 'global',\n sqlitePath: string,\n cwd: string,\n config: HarnessConfig,\n homeDir: string,\n): string {\n return scope === 'global'\n ? join(resolveGlobalStorageDir(config, homeDir), 'harness.db')\n : resolve(cwd, sqlitePath)\n}\n\n/** Resolves the physical sqlite file path for `config`'s OWN current scope\n * (as opposed to `resolveSqlitePathForScope`, which resolves an arbitrary\n * scope — used by `ahk migrate storage` to probe both candidates). This is\n * the single mandatory entry point every call site should use instead of\n * reading `config.database`/`config.storage.sqlitePath` directly — routing\n * everything through here is what keeps new call sites from re-introducing\n * the \"reads a local-only field while scope=global\" bug class (task #55/#56). */\nexport function resolveSqlitePath(config: HarnessConfig, cwd: string, homeDir: string = homedir()): string {\n const sqlitePath = config.storage.scope === 'local' ? (config.storage.sqlitePath ?? DEFAULT_SQLITE_PATH) : DEFAULT_SQLITE_PATH\n return resolveSqlitePathForScope(config.storage.scope, sqlitePath, cwd, config, homeDir)\n}\n\n/** Resolves the physical current.md fallback path for `config`'s OWN current\n * scope, sharing the exact convention `HarnessDB.regenerateCurrentMd()`\n * uses. Mirrors `resolveSqlitePath()` — call sites (materializers, reset,\n * health) should use this instead of reading `storage.markdownFallback.path`\n * directly, since that field doesn't exist at all under scope='global'. */\nexport function resolveMarkdownFallbackPath(config: HarnessConfig, cwd: string, homeDir: string = homedir()): string {\n return config.storage.scope === 'global'\n ? join(resolveGlobalStorageDir(config, homeDir), 'current.md')\n : resolve(cwd, config.storage.markdownFallback.path)\n}\n\n/** Writes `<storageDir>/storage-state.json` under `cwd`. Standalone (not tied\n * to a live HarnessDB instance) so it can be called during init before a DB\n * connection exists, and reused by future migration tooling. */\nexport function writeStorageStateFile(cwd: string, storageDir: string, state: StorageState): void {\n const path = join(resolve(cwd), storageDir, 'storage-state.json')\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(state, null, 2) + '\\n', 'utf8')\n}\n\n/** Reads `<storageDir>/storage-state.json` under `cwd`. Returns `null` if it\n * doesn't exist or is malformed. Used by future migration tooling (#47) to\n * determine the real current storage state before migrating. */\nexport function readStorageStateFile(cwd: string, storageDir: string): StorageState | null {\n try {\n const path = join(resolve(cwd), storageDir, 'storage-state.json')\n if (!existsSync(path)) return null\n return JSON.parse(readFileSync(path, 'utf8')) as StorageState\n } catch {\n return null\n }\n}\n\n// ─── Factory ─────────────────────────────────────────────────────────────────\n\nexport async function openDB(config: HarnessConfig, cwd: string, homeDir: string = homedir()): Promise<HarnessDB> {\n const dbConfig = config.database\n let driver: DBDriver\n\n if (dbConfig.type === 'postgres') {\n const { PostgresDriver } = await import('./drivers/postgres')\n driver = new PostgresDriver(dbConfig)\n } else if (dbConfig.type === 'mysql') {\n const { MySQLDriver } = await import('./drivers/mysql')\n driver = new MySQLDriver(dbConfig)\n } else {\n const { SQLiteDriver } = await import('./drivers/sqlite')\n if (dbConfig.type !== 'sqlite') {\n throw new Error('Invalid database type')\n }\n\n let dbPath: string\n if (config.storage.scope === 'global') {\n const globalDir = resolveGlobalStorageDir(config, homeDir)\n // Defensive check: a UUID collision is negligible, but if the target\n // dir already exists with a DIFFERENT project's state, don't silently\n // reuse it — surface the conflict instead of assuming it's free.\n const existingStatePath = join(globalDir, 'storage-state.json')\n if (existsSync(existingStatePath)) {\n try {\n const existingState = JSON.parse(readFileSync(existingStatePath, 'utf8')) as StorageState\n if (existingState.projectId !== config.storage.projectId) {\n throw new Error(\n `Global storage dir ${globalDir} already holds a different project (projectId: ${existingState.projectId}). Refusing to reuse it.`,\n )\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('already holds a different project')) throw err\n // Malformed/unreadable state file — ignore and proceed, mkdirSync below is idempotent.\n }\n }\n mkdirSync(globalDir, { recursive: true })\n dbPath = join(globalDir, 'harness.db')\n } else {\n dbPath = resolve(cwd, config.storage.sqlitePath ?? DEFAULT_SQLITE_PATH)\n }\n\n driver = new SQLiteDriver(dbPath)\n }\n\n await driver.ensureSchema()\n return new HarnessDB(driver, config, homeDir)\n}\n","import type { DBDriver } from '../drivers/types'\nimport type { ActionFileRow, ActionRow, ActionSectionRow, ActionToolRow, AgentName } from '@/types'\n\nexport interface ActionWithDetails extends ActionRow {\n sections: ActionSectionRow[]\n files: ActionFileRow[]\n tools: ActionToolRow[]\n}\n\nexport class ActionRepository {\n constructor(private driver: DBDriver) {}\n\n /** Returns the new autoincrement id — mirrors TaskRepository.add(). Since\n * task #73, `actions.id` is a driver-generated INTEGER, not an\n * application-generated UUID, so callers no longer pass an id in. */\n async create(taskId: number, agent: AgentName, now: string): Promise<number> {\n return this.driver.insert(\n `INSERT INTO actions (task_id, agent, status, created_at) VALUES (?, ?, 'in_progress', ?)`,\n [taskId, agent, now],\n )\n }\n\n async complete(actionId: number, summary: string, now: string): Promise<void> {\n await this.driver.exec(\n `UPDATE actions SET status = 'completed', completed_at = ?, summary = ? WHERE id = ?`,\n [now, summary, actionId],\n )\n }\n\n async closeOrphaned(taskId: number, now: string): Promise<number> {\n return this.driver.exec(\n `UPDATE actions SET status = 'completed', completed_at = ?, summary = 'Auto-closed: task marked done' WHERE task_id = ? AND status = 'in_progress'`,\n [now, taskId],\n )\n }\n\n async getById(actionId: number): Promise<ActionRow | null> {\n return this.driver.queryOne<ActionRow>(`SELECT * FROM actions WHERE id = ?`, [actionId])\n }\n\n async getForTask(taskId: number): Promise<ActionRow[]> {\n return this.driver.query<ActionRow>(\n `SELECT * FROM actions WHERE task_id = ? ORDER BY created_at`,\n [taskId],\n )\n }\n\n async getAll(): Promise<ActionRow[]> {\n return this.driver.query<ActionRow>(`SELECT * FROM actions ORDER BY created_at`)\n }\n\n async getWithDetails(taskId: number): Promise<ActionWithDetails[]> {\n const actions = await this.getForTask(taskId)\n return Promise.all(\n actions.map(async (action) => ({\n ...action,\n sections: await this.getSections(action.id),\n files: await this.getFiles(action.id),\n tools: await this.getTools(action.id),\n })),\n )\n }\n\n // ─── Sections ─────────────────────────────────────────────────────────────\n\n async addSection(actionId: number, sectionType: string, content: string, now: string): Promise<void> {\n await this.driver.exec(\n `INSERT INTO action_sections (action_id, section_type, content, created_at) VALUES (?, ?, ?, ?)`,\n [actionId, sectionType, content, now],\n )\n }\n\n async getSections(actionId: number): Promise<ActionSectionRow[]> {\n return this.driver.query<ActionSectionRow>(\n `SELECT * FROM action_sections WHERE action_id = ? ORDER BY created_at`,\n [actionId],\n )\n }\n\n async getAllSections(): Promise<ActionSectionRow[]> {\n return this.driver.query<ActionSectionRow>(`SELECT * FROM action_sections ORDER BY created_at`)\n }\n\n // ─── Files ────────────────────────────────────────────────────────────────\n\n async addFile(\n actionId: number,\n filePath: string,\n operation: ActionFileRow['operation'],\n notes: string | null,\n ): Promise<void> {\n await this.driver.exec(\n `INSERT INTO action_files (action_id, file_path, operation, notes) VALUES (?, ?, ?, ?)`,\n [actionId, filePath, operation, notes],\n )\n }\n\n async getFiles(actionId: number): Promise<ActionFileRow[]> {\n return this.driver.query<ActionFileRow>(\n `SELECT * FROM action_files WHERE action_id = ?`,\n [actionId],\n )\n }\n\n async getFilesForTask(taskId: number): Promise<(ActionFileRow & { agent: AgentName })[]> {\n return this.driver.query<ActionFileRow & { agent: AgentName }>(\n `SELECT af.*, a.agent FROM action_files af JOIN actions a ON af.action_id = a.id WHERE a.task_id = ? ORDER BY a.agent, af.operation`,\n [taskId],\n )\n }\n\n /** Returns ALL action_files rows regardless of action — used by full DB\n * exports (e.g. `ahk migrate storage`) so file-touch records aren't lost. */\n async getAllFiles(): Promise<ActionFileRow[]> {\n return this.driver.query<ActionFileRow>(`SELECT * FROM action_files ORDER BY id`)\n }\n\n // ─── Tools ────────────────────────────────────────────────────────────────\n\n async addTool(\n actionId: number,\n toolName: string,\n argsJson: string | null,\n resultSummary: string | null,\n now: string,\n ): Promise<void> {\n await this.driver.exec(\n `INSERT INTO action_tools (action_id, tool_name, args_json, result_summary, called_at) VALUES (?, ?, ?, ?, ?)`,\n [actionId, toolName, argsJson, resultSummary, now],\n )\n }\n\n async getTools(actionId: number): Promise<ActionToolRow[]> {\n return this.driver.query<ActionToolRow>(\n `SELECT * FROM action_tools WHERE action_id = ? ORDER BY called_at`,\n [actionId],\n )\n }\n\n /** Returns ALL action_tools rows regardless of action — used by full DB\n * exports (e.g. `ahk migrate storage`) so tool-call records aren't lost. */\n async getAllTools(): Promise<ActionToolRow[]> {\n return this.driver.query<ActionToolRow>(`SELECT * FROM action_tools ORDER BY id`)\n }\n\n async getTopTools(limit: number): Promise<{ tool_name: string; uses: number }[]> {\n return this.driver.query<{ tool_name: string; uses: number }>(\n `SELECT tool_name, COUNT(*) as uses FROM action_tools GROUP BY tool_name ORDER BY uses DESC LIMIT ?`,\n [limit],\n )\n }\n}\n","import type { DBDriver } from '../drivers/types'\nimport type {\n AgentStatRow,\n CountRow,\n RecentFileRow,\n RecentToolRow,\n TimelineRow,\n TopFileRow,\n} from '../server-types'\n\nexport interface DBCounts {\n totalActions: number\n totalFiles: number\n uniqueTools: number\n activeAgents: number\n}\n\nexport { AgentStatRow, RecentFileRow, RecentToolRow, TimelineRow, TopFileRow }\n\nconst AGENT_ORDER = ['lead', 'explorer', 'builder', 'reviewer']\n\nexport class StatsRepository {\n constructor(private driver: DBDriver) { }\n\n async getCounts(): Promise<DBCounts> {\n const [{ total: totalActions }] = await this.driver.query<CountRow>(\n `SELECT COUNT(*) as total FROM actions`,\n )\n const [{ total: totalFiles }] = await this.driver.query<CountRow>(\n `SELECT COUNT(*) as total FROM action_files`,\n )\n const [{ total: uniqueTools }] = await this.driver.query<CountRow>(\n `SELECT COUNT(DISTINCT tool_name) as total FROM action_tools`,\n )\n const [{ total: activeAgents }] = await this.driver.query<CountRow>(\n `SELECT COUNT(DISTINCT agent) as total FROM actions WHERE status = 'in_progress'`,\n )\n return { totalActions, totalFiles, uniqueTools, activeAgents }\n }\n\n async getRecentTools(limit: number): Promise<RecentToolRow[]> {\n return this.driver.query<RecentToolRow>(\n `SELECT at.*, t.id as task_id, t.title as task_title, t.slug as task_slug, a.agent\n FROM action_tools at\n JOIN actions a ON at.action_id = a.id\n JOIN tasks t ON a.task_id = t.id\n ORDER BY at.called_at DESC\n LIMIT ?`,\n [limit],\n )\n }\n\n async getTopFiles(limit: number): Promise<TopFileRow[]> {\n return this.driver.query<TopFileRow>(\n `SELECT\n file_path,\n COUNT(*) as total,\n SUM(CASE WHEN operation='read' THEN 1 ELSE 0 END) as read,\n SUM(CASE WHEN operation='created' THEN 1 ELSE 0 END) as created,\n SUM(CASE WHEN operation='modified' THEN 1 ELSE 0 END) as modified,\n SUM(CASE WHEN operation='deleted' THEN 1 ELSE 0 END) as deleted\n FROM action_files\n GROUP BY file_path\n ORDER BY total DESC\n LIMIT ?`,\n [limit],\n )\n }\n\n async getRecentFiles(limit: number): Promise<RecentFileRow[]> {\n return this.driver.query<RecentFileRow>(\n `SELECT af.*, t.id as task_id, t.title as task_title, t.slug as task_slug,\n a.agent, a.created_at as called_at\n FROM action_files af\n JOIN actions a ON af.action_id = a.id\n JOIN tasks t ON a.task_id = t.id\n ORDER BY a.created_at DESC\n LIMIT ?`,\n [limit],\n )\n }\n\n async getAgentStats(): Promise<AgentStatRow[]> {\n const rows = await this.driver.query<AgentStatRow>(\n `SELECT\n a.agent,\n COUNT(*) as actions_total,\n SUM(CASE WHEN a.status='completed' THEN 1 ELSE 0 END) as actions_done,\n SUM(CASE WHEN a.status='blocked' THEN 1 ELSE 0 END) as actions_blocked,\n COUNT(DISTINCT a.task_id) as tasks_worked,\n COUNT(DISTINCT af.file_path) as files_touched\n FROM actions a\n LEFT JOIN action_files af ON af.action_id = a.id\n GROUP BY a.agent\n ORDER BY actions_total DESC`,\n )\n return rows.sort((a, b) => {\n const ai = AGENT_ORDER.indexOf(a.agent)\n const bi = AGENT_ORDER.indexOf(b.agent)\n if (ai === -1 && bi === -1) return 0\n if (ai === -1) return 1\n if (bi === -1) return -1\n return ai - bi\n })\n }\n\n async getTimeline(limit: number): Promise<TimelineRow[]> {\n return this.driver.query<TimelineRow>(\n `SELECT a.*, t.title as task_title, t.slug as task_slug, t.status as task_status\n FROM actions a\n JOIN tasks t ON a.task_id = t.id\n ORDER BY a.created_at DESC\n LIMIT ?`,\n [limit],\n )\n }\n}\n","import type { DBDriver } from '../drivers/types'\nimport type { TaskAcceptanceRow, TaskRow, TaskStatus } from '@/types'\n\nexport interface TaskWithAcceptance extends TaskRow {\n acceptance_total: number\n acceptance_met: number\n}\n\nexport class TaskRepository {\n constructor(private driver: DBDriver) {}\n\n async add(params: {\n slug: string\n title: string\n description?: string | null\n status?: TaskStatus\n }): Promise<number> {\n const now = new Date().toISOString()\n return this.driver.insert(\n `INSERT INTO tasks (slug, title, description, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)`,\n [params.slug, params.title, params.description ?? null, params.status ?? 'pending', now, now],\n )\n }\n\n async addAcceptance(taskId: number, criteria: string[]): Promise<void> {\n for (const criterion of criteria) {\n await this.driver.exec(\n `INSERT INTO task_acceptance (task_id, criterion) VALUES (?, ?)`,\n [taskId, criterion],\n )\n }\n }\n\n async getAll(status?: TaskStatus, includeArchived = false): Promise<TaskRow[]> {\n let sql = `SELECT * FROM tasks`\n const params: unknown[] = []\n const conditions: string[] = []\n\n if (!includeArchived) {\n conditions.push(`archived_at IS NULL`)\n }\n if (status) {\n conditions.push(`status = ?`)\n params.push(status)\n }\n if (conditions.length > 0) {\n sql += ` WHERE ${conditions.join(' AND ')}`\n }\n sql += ` ORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'blocked' THEN 3 WHEN 'done' THEN 4 ELSE 5 END, updated_at DESC`\n\n return this.driver.query<TaskRow>(sql, params)\n }\n\n async getAllWithAcceptanceCounts(includeArchived = false): Promise<TaskWithAcceptance[]> {\n let sql = `\n SELECT t.*,\n COUNT(ta.id) as acceptance_total,\n COALESCE(SUM(ta.met), 0) as acceptance_met\n FROM tasks t\n LEFT JOIN task_acceptance ta ON ta.task_id = t.id\n `\n if (!includeArchived) {\n sql += ` WHERE t.archived_at IS NULL`\n }\n sql += ` GROUP BY t.id ORDER BY CASE t.status WHEN 'pending' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'blocked' THEN 3 WHEN 'done' THEN 4 ELSE 5 END, t.updated_at DESC`\n return this.driver.query<TaskWithAcceptance>(sql)\n }\n\n async getById(id: number): Promise<TaskRow | null> {\n return this.driver.queryOne<TaskRow>(`SELECT * FROM tasks WHERE id = ?`, [id])\n }\n\n async getBySlug(slug: string): Promise<TaskRow | null> {\n return this.driver.queryOne<TaskRow>(`SELECT * FROM tasks WHERE slug = ?`, [slug])\n }\n\n async getAcceptance(taskId: number): Promise<TaskAcceptanceRow[]> {\n return this.driver.query<TaskAcceptanceRow>(\n `SELECT * FROM task_acceptance WHERE task_id = ?`,\n [taskId],\n )\n }\n\n /** Returns ALL task_acceptance rows regardless of task — used by full DB\n * exports (e.g. `ahk migrate storage`) so criteria aren't silently dropped. */\n async getAllAcceptance(): Promise<TaskAcceptanceRow[]> {\n return this.driver.query<TaskAcceptanceRow>(`SELECT * FROM task_acceptance ORDER BY id`)\n }\n\n async setStatus(id: number, status: TaskStatus, extra?: { started_at?: string; completed_at?: string }): Promise<void> {\n const now = new Date().toISOString()\n if (extra?.started_at) {\n await this.driver.exec(\n `UPDATE tasks SET status = ?, started_at = ?, updated_at = ? WHERE id = ?`,\n [status, extra.started_at, now, id],\n )\n } else if (extra?.completed_at) {\n await this.driver.exec(\n `UPDATE tasks SET status = ?, completed_at = ?, updated_at = ? WHERE id = ?`,\n [status, extra.completed_at, now, id],\n )\n } else {\n await this.driver.exec(`UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?`, [status, now, id])\n }\n }\n\n async update(id: number, params: { title?: string; description?: string | null; slug?: string }): Promise<void> {\n const sets: string[] = []\n const vals: unknown[] = []\n const now = new Date().toISOString()\n if (params.title !== undefined) { sets.push('title = ?'); vals.push(params.title) }\n if (params.description !== undefined) { sets.push('description = ?'); vals.push(params.description) }\n if (params.slug !== undefined) { sets.push('slug = ?'); vals.push(params.slug) }\n if (sets.length === 0) return\n sets.push('updated_at = ?')\n vals.push(now)\n vals.push(id)\n await this.driver.exec(`UPDATE tasks SET ${sets.join(', ')} WHERE id = ?`, vals)\n }\n\n async replaceAcceptance(taskId: number, criteria: string[]): Promise<void> {\n await this.driver.exec(`DELETE FROM task_acceptance WHERE task_id = ?`, [taskId])\n for (const criterion of criteria) {\n await this.driver.exec(\n `INSERT INTO task_acceptance (task_id, criterion) VALUES (?, ?)`,\n [taskId, criterion],\n )\n }\n }\n\n async archive(id: number): Promise<void> {\n const now = new Date().toISOString()\n await this.driver.exec(`UPDATE tasks SET archived_at = ?, updated_at = ? WHERE id = ?`, [now, now, id])\n }\n\n async unarchive(id: number): Promise<void> {\n const now = new Date().toISOString()\n await this.driver.exec(`UPDATE tasks SET archived_at = NULL, updated_at = ? WHERE id = ?`, [now, id])\n }\n\n async getArchived(): Promise<TaskRow[]> {\n return this.driver.query<TaskRow>(\n `SELECT * FROM tasks WHERE archived_at IS NOT NULL ORDER BY archived_at DESC`\n )\n }\n\n async claim(id: number, agent: string, now: string): Promise<number> {\n return this.driver.exec(\n `UPDATE tasks SET status = 'in_progress', assigned_to = ?, started_at = ?, updated_at = ? WHERE id = ? AND status = 'pending'`,\n [agent, now, now, id],\n )\n }\n\n async markAcceptanceMet(criterionId: number): Promise<void> {\n await this.driver.exec(`UPDATE task_acceptance SET met = 1 WHERE id = ?`, [criterionId])\n }\n\n async getStatusSummary(): Promise<{ status: string; total: number }[]> {\n return this.driver.query<{ status: string; total: number }>(\n `SELECT status, COUNT(*) as total FROM tasks WHERE archived_at IS NULL GROUP BY status`,\n )\n }\n}\n"],"mappings":";AAAA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,eAAe;;;ACOhC,IAAM,mBAAN,MAAuB;AAAA,EAC5B,YAAoB,QAAkB;AAAlB;AAAA,EAAmB;AAAA,EAAnB;AAAA;AAAA;AAAA;AAAA,EAKpB,MAAM,OAAO,QAAgB,OAAkB,KAA8B;AAC3E,WAAO,KAAK,OAAO;AAAA,MACjB;AAAA,MACA,CAAC,QAAQ,OAAO,GAAG;AAAA,IACrB;AAAA,EACF;AAAA,EAEA,MAAM,SAAS,UAAkB,SAAiB,KAA4B;AAC5E,UAAM,KAAK,OAAO;AAAA,MAChB;AAAA,MACA,CAAC,KAAK,SAAS,QAAQ;AAAA,IACzB;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,QAAgB,KAA8B;AAChE,WAAO,KAAK,OAAO;AAAA,MACjB;AAAA,MACA,CAAC,KAAK,MAAM;AAAA,IACd;AAAA,EACF;AAAA,EAEA,MAAM,QAAQ,UAA6C;AACzD,WAAO,KAAK,OAAO,SAAoB,sCAAsC,CAAC,QAAQ,CAAC;AAAA,EACzF;AAAA,EAEA,MAAM,WAAW,QAAsC;AACrD,WAAO,KAAK,OAAO;AAAA,MACjB;AAAA,MACA,CAAC,MAAM;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAM,SAA+B;AACnC,WAAO,KAAK,OAAO,MAAiB,2CAA2C;AAAA,EACjF;AAAA,EAEA,MAAM,eA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AI,cAAc,cAAc,OAAO,QAAQ,WAAW;AACxD,kBAAM,IAAI;AAAA,cACR,sBAAsB,SAAS,kDAAkD,cAAc,SAAS;AAAA,YAC1G;AAAA,UACF;AAAA,QACF,SAAS,KAAK;AACZ,cAAI,eAAe,SAAS,IAAI,QAAQ,SAAS,mCAAmC,EAAG,OAAM;AAAA,QAE/F;AAAA,MACF;AACA,gBAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AACxC,eAAS,KAAK,WAAW,YAAY;AAAA,IACvC,OAAO;AACL,eAAS,QAAQ,KAAK,OAAO,QAAQ,cAAc,mBAAmB;AAAA,IACxE;AAEA,aAAS,IAAI,aAAa,MAAM;AAAA,EAClC;AAEA,QAAM,OAAO,aAAa;AAC1B,SAAO,IAAI,UAAU,QAAQ,QAAQ,OAAO;AAC9C;","names":[]}
@@ -1,13 +1,14 @@
1
1
  // src/core/config.ts
2
2
  import { randomUUID } from "crypto";
3
- import { existsSync } from "fs";
3
+ import { existsSync, readFileSync } from "fs";
4
4
  import { join } from "path";
5
5
  import { createJiti } from "jiti";
6
6
  var CONFIG_NAMES = [
7
7
  "agent-harness-kit.config.ts",
8
8
  "agent-harness-kit.config",
9
9
  "agent-harness-kit.config.mjs",
10
- "agent-harness-kit.config.cjs"
10
+ "agent-harness-kit.config.cjs",
11
+ "agent-harness-kit.config.json"
11
12
  ];
12
13
  function findConfigFile(cwd) {
13
14
  for (const name of CONFIG_NAMES) {
@@ -21,10 +22,27 @@ async function loadConfig(cwd) {
21
22
  if (!configPath) {
22
23
  throw new Error("No agent-harness-kit.config found. Run: ahk init");
23
24
  }
24
- const jiti = createJiti(import.meta.url);
25
- const mod = await jiti.import(configPath);
26
- const config = mod.default ?? mod;
27
- if (!config || typeof config !== "object") {
25
+ let config;
26
+ if (configPath.endsWith(".json")) {
27
+ let raw;
28
+ try {
29
+ raw = readFileSync(configPath, "utf8");
30
+ } catch (err) {
31
+ throw new Error(`Could not read ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
32
+ }
33
+ try {
34
+ config = JSON.parse(raw);
35
+ } catch (err) {
36
+ throw new Error(
37
+ `${configPath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`
38
+ );
39
+ }
40
+ } else {
41
+ const jiti = createJiti(import.meta.url);
42
+ const mod = await jiti.import(configPath);
43
+ config = mod.default ?? mod;
44
+ }
45
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
28
46
  throw new Error(`agent-harness-kit.config must export a default HarnessConfig object.`);
29
47
  }
30
48
  return applyDefaults(config);
@@ -59,8 +77,20 @@ function normalizeLegacyStorageShape(raw) {
59
77
  );
60
78
  return { ...raw, storage: normalizedStorage, database: normalizedDatabase ?? database };
61
79
  }
80
+ function normalizeLegacyAgentsKey(raw) {
81
+ if (!("agents" in raw)) return raw;
82
+ const agents = raw.agents;
83
+ const roles = agents && typeof agents === "object" && !Array.isArray(agents) ? Object.keys(agents) : [];
84
+ const normalized = Object.fromEntries(Object.entries(raw).filter(([k]) => k !== "agents"));
85
+ console.warn(
86
+ `[agent-harness-kit] The 'agents' key is set in agent-harness-kit.config.ts${roles.length > 0 ? ` (${roles.map((r) => `agents.${r}`).join(", ")})` : ""} but no longer has any effect \u2014 it has been removed and is ignored. Per-agent settings now live in the generated agent file itself, which is yours to edit: set the model on the 'model:' frontmatter line and write role instructions in the body of .claude/agents/<role>.md (Claude Code), .opencode/agents/<role>.md (OpenCode) or .codex/agents/<role>.toml (Codex CLI). 'ahk build' creates those files when missing and never overwrites them; use 'ahk build --force' to regenerate them from the packaged templates. Remove the 'agents' key from your config. See docs/architecture.md#agent-restrictions.`
87
+ );
88
+ return normalized;
89
+ }
62
90
  function applyDefaults(config) {
63
- const normalized = normalizeLegacyStorageShape(config);
91
+ const normalized = normalizeLegacyAgentsKey(
92
+ normalizeLegacyStorageShape(config)
93
+ );
64
94
  const c = normalized;
65
95
  const scope = c.storage?.scope === "global" ? "global" : "local";
66
96
  const projectId = c.storage?.projectId ?? randomUUID();
@@ -97,14 +127,6 @@ function applyDefaults(config) {
97
127
  agentsMd: "./AGENTS.md",
98
128
  ...c.project
99
129
  },
100
- agents: {
101
- lead: { instructionsPath: null },
102
- explorer: { instructionsPath: null },
103
- builder: { instructionsPath: null },
104
- reviewer: { instructionsPath: null },
105
- custom: [],
106
- ...c.agents
107
- },
108
130
  database: c.database ?? { type: "sqlite" },
109
131
  storage,
110
132
  health: {
@@ -125,4 +147,4 @@ export {
125
147
  loadConfig,
126
148
  defineHarness
127
149
  };
128
- //# sourceMappingURL=chunk-D64KK6UU.js.map
150
+ //# sourceMappingURL=chunk-U3O77CGE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/config.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { createJiti } from 'jiti'\n\nimport type { HarnessConfig } from '@/types'\n\n/** Order is precedence: the first file that exists wins. `.json` is appended\n * last so adding it cannot change which config an existing project resolves\n * to — a project that already has a .ts/.mjs/.cjs config keeps loading it. */\nconst CONFIG_NAMES = [\n 'agent-harness-kit.config.ts',\n 'agent-harness-kit.config',\n 'agent-harness-kit.config.mjs',\n 'agent-harness-kit.config.cjs',\n 'agent-harness-kit.config.json',\n]\n\nexport function findConfigFile(cwd: string): string | null {\n for (const name of CONFIG_NAMES) {\n const candidate = join(cwd, name)\n if (existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport async function loadConfig(cwd: string): Promise<HarnessConfig> {\n const configPath = findConfigFile(cwd)\n if (!configPath) {\n throw new Error('No agent-harness-kit.config found. Run: ahk init')\n }\n\n let config: HarnessConfig\n\n if (configPath.endsWith('.json')) {\n // Read and parse directly rather than going through jiti: a JSON config is\n // pure data with no module semantics to interpret, and parsing it here lets\n // a syntax error name the file and the reason instead of surfacing as an\n // opaque module-resolution failure.\n let raw: string\n try {\n raw = readFileSync(configPath, 'utf8')\n } catch (err) {\n throw new Error(`Could not read ${configPath}: ${err instanceof Error ? err.message : String(err)}`)\n }\n try {\n config = JSON.parse(raw) as HarnessConfig\n } catch (err) {\n throw new Error(\n `${configPath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n } else {\n const jiti = createJiti(import.meta.url)\n const mod = await jiti.import(configPath) as { default?: HarnessConfig } | HarnessConfig\n config = (mod as { default?: HarnessConfig }).default ?? (mod as HarnessConfig)\n }\n\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error(`agent-harness-kit.config must export a default HarnessConfig object.`)\n }\n\n // applyDefaults() runs the same normalizers (normalizeLegacyStorageShape,\n // normalizeLegacyAgentsKey) for every format — a JSON config carrying a\n // legacy `agents` key or a contradictory global-scope path is normalized\n // and warned about exactly like its .ts/.mjs/.cjs counterpart.\n return applyDefaults(config as HarnessConfig)\n}\n\nexport function defineHarness(config: HarnessConfig): HarnessConfig {\n return config\n}\n\n/** Detects and normalizes the legacy contradictory config shape: `scope:\n * 'global'` declared alongside now-meaningless local-only path fields\n * (`database.path` / `storage.sqlitePath`, `storage.markdownFallback.path`).\n *\n * This is necessary IN ADDITION to the type-level redesign (not instead of\n * it) because `loadConfig()` loads `agent-harness-kit.config.ts` via\n * `jiti.import()` at runtime, which transpiles TS to JS and strips types\n * entirely before the module is ever evaluated — a hard type error on\n * `GlobalStorageConfig` protects authors who type-check their config file\n * (IDE, `tsc --noEmit`), but gives ZERO protection against an existing\n * config on disk that already has both fields set. Operates on the RAW\n * untyped input (may not conform to the new types at all) and returns a\n * normalized (stripped) plain object — never crashes, only warns. */\nfunction normalizeLegacyStorageShape(raw: Record<string, unknown>): Record<string, unknown> {\n const storage = raw.storage as Record<string, unknown> | undefined\n const database = raw.database as Record<string, unknown> | undefined\n if (!storage || storage.scope !== 'global') return raw\n\n const offenders: string[] = []\n let normalizedStorage = storage\n let normalizedDatabase = database\n\n const omit = (obj: Record<string, unknown>, key: string): Record<string, unknown> =>\n Object.fromEntries(Object.entries(obj).filter(([k]) => k !== key))\n\n if (database && typeof database.path === 'string' && database.path) {\n offenders.push('database.path')\n normalizedDatabase = omit(database, 'path')\n }\n if (typeof storage.sqlitePath === 'string' && storage.sqlitePath) {\n offenders.push('storage.sqlitePath')\n normalizedStorage = omit(normalizedStorage, 'sqlitePath')\n }\n const markdownFallback = normalizedStorage.markdownFallback as Record<string, unknown> | undefined\n if (markdownFallback && typeof markdownFallback.path === 'string' && markdownFallback.path) {\n offenders.push('storage.markdownFallback.path')\n normalizedStorage = { ...normalizedStorage, markdownFallback: omit(markdownFallback, 'path') }\n }\n\n if (offenders.length === 0) return raw\n\n console.warn(\n `[agent-harness-kit] storage.scope is 'global' but ${offenders.join(', ')} ${offenders.length > 1 ? 'are' : 'is'} set in ` +\n `agent-harness-kit.config.ts — ${offenders.length > 1 ? 'these are' : 'this is'} ignored under global scope and will be ` +\n `removed by a future major version. See docs/architecture.md#storage-scope.`,\n )\n\n return { ...raw, storage: normalizedStorage, database: normalizedDatabase ?? database }\n}\n\n/** Detects and strips the removed `agents` config key entirely.\n *\n * Supersedes the narrower normalizer that only stripped `allowedPaths` /\n * `writablePaths` from `agents.*`: with the whole key gone, per-field\n * stripping is subsumed — a config declaring `agents.explorer.allowedPaths`\n * loses it because it loses `agents` altogether.\n *\n * Same rationale as `normalizeLegacyStorageShape` above: deleting the key from\n * `HarnessConfig` protects authors who type-check their config file, but\n * `loadConfig()` imports the config via `jiti.import()`, which strips types\n * before evaluation — so an existing config on disk that still declares\n * `agents` reaches us untouched. It must not crash; the key is simply dropped.\n *\n * Operates on the RAW untyped input and returns a normalized plain object —\n * never crashes, only warns, exactly once, no matter how many roles or fields\n * the old config declared. */\nfunction normalizeLegacyAgentsKey(raw: Record<string, unknown>): Record<string, unknown> {\n if (!('agents' in raw)) return raw\n\n const agents = raw.agents\n const roles =\n agents && typeof agents === 'object' && !Array.isArray(agents)\n ? Object.keys(agents as Record<string, unknown>)\n : []\n\n const normalized = Object.fromEntries(Object.entries(raw).filter(([k]) => k !== 'agents'))\n\n console.warn(\n `[agent-harness-kit] The 'agents' key is set in agent-harness-kit.config.ts` +\n `${roles.length > 0 ? ` (${roles.map((r) => `agents.${r}`).join(', ')})` : ''} ` +\n `but no longer has any effect — it has been removed and is ignored. ` +\n `Per-agent settings now live in the generated agent file itself, which is yours to edit: ` +\n `set the model on the 'model:' frontmatter line and write role instructions in the body of ` +\n `.claude/agents/<role>.md (Claude Code), .opencode/agents/<role>.md (OpenCode) or ` +\n `.codex/agents/<role>.toml (Codex CLI). 'ahk build' creates those files when missing and never ` +\n `overwrites them; use 'ahk build --force' to regenerate them from the packaged templates. ` +\n `Remove the 'agents' key from your config. See docs/architecture.md#agent-restrictions.`,\n )\n\n return normalized\n}\n\nfunction applyDefaults(config: HarnessConfig): HarnessConfig {\n const normalized = normalizeLegacyAgentsKey(\n normalizeLegacyStorageShape(config as unknown as Record<string, unknown>),\n )\n const c = normalized as Partial<HarnessConfig>\n\n const scope: 'local' | 'global' = c.storage?.scope === 'global' ? 'global' : 'local'\n const projectId = c.storage?.projectId ?? randomUUID()\n const baseStorage = {\n dir: '.harness',\n tasks: { adapter: 'local' as const },\n sections: {\n toolsUsed: true,\n filesModified: true,\n result: true,\n blockers: true,\n nextSteps: false,\n },\n }\n\n const storageOverrides = (c.storage ?? {}) as Record<string, unknown>\n\n const storage: HarnessConfig['storage'] =\n scope === 'global'\n ? ({\n ...baseStorage,\n markdownFallback: { enabled: true },\n ...storageOverrides,\n scope: 'global',\n projectId,\n } as HarnessConfig['storage'])\n : ({\n ...baseStorage,\n markdownFallback: { enabled: true, path: '.harness/current.md' },\n ...storageOverrides,\n scope: 'local',\n projectId,\n } as HarnessConfig['storage'])\n\n return {\n ...(normalized as unknown as HarnessConfig),\n provider: c.provider ?? 'claude-code',\n project: {\n docsPath: './docs',\n agentsMd: './AGENTS.md',\n ...c.project,\n } as HarnessConfig['project'],\n database: c.database ?? { type: 'sqlite' as const },\n storage,\n health: {\n scriptPath: './health.sh',\n required: true,\n ...c.health,\n },\n tools: {\n mcp: { enabled: true, port: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