Skip to content

refactor: agents instructions & couple other - #85

Merged
fum4 merged 3 commits into
masterfrom
refactor/task-context-cli-command
Mar 19, 2026
Merged

fum4 merged 3 commits into
masterfrom
refactor/task-context-cli-command

Conversation

@fum4

@fum4 fum4 commented Mar 18, 2026 •

Copy link
Copy Markdown
Owner
  • replace TASK.md with on-demand openkit task context CLI c…ommand
  • remove TASK.md file generation system entirely (went stale between writes, required git exclude hacks, duplicated data from .openkit/issues/)
  • add openkit task context [<issue-id>] [--json] CLI command that reads issue data + notes + effective hooks on demand and outputs merged context
  • rename local task.json to issue.json for consistency with jira/linear (lazy migration: reads issue.json first, falls back to task.json)
  • move task-context types and formatters to libs/agents (agent-facing code belongs with agent instructions, not in shared utils)
  • remove server-side TASK.md plumbing: pendingWorktreeContext, taskHooksProvider, regenerateTaskMd, writeTaskMd, ensureGitExclude
  • fix hooks-run.json placement from worktree root to .openkit/ directory (was showing as untracked file in worktrees)
  • add md-raw-loader vite plugin for vitest configs (allows barrel imports from @openkit/agents without bundler-only .md loaders)
  • lock @openkit/agents exports to barrel only (index.ts)
  • update agent skills, launch prompts, and docs to use CLI command

Summary by CodeRabbit

  • New Features

    • Added openkit task context CLI (markdown + --json output) and instance info in the app UI (branch/worktree).
    • UI prompts updated to instruct running the context command before implementing tasks.
  • Documentation

    • CLI, architecture, configuration, and hooks docs updated to reflect on-demand task context and local file migration.
  • Chores

    • Removed server-side TASK.md generation; local task file renamed with backward compatibility.
    • UI label/icon updates ("Create task" → "Create issue" and icon refresh).

…ommand

- remove TASK.md file generation system entirely
  (went stale between writes, required git exclude hacks, duplicated data from .openkit/issues/)
- add `openkit task context [<issue-id>] [--json]` CLI command that reads
  issue data + notes + effective hooks on demand and outputs merged context
- rename local task.json to issue.json for consistency with jira/linear
  (lazy migration: reads issue.json first, falls back to task.json)
- move task-context types and formatters to libs/agents
  (agent-facing code belongs with agent instructions, not in shared utils)
- remove server-side TASK.md plumbing: pendingWorktreeContext, taskHooksProvider,
  regenerateTaskMd, writeTaskMd, ensureGitExclude
- fix hooks-run.json placement from worktree root to .openkit/ directory
  (was showing as untracked file in worktrees)
- add md-raw-loader vite plugin for vitest configs
  (allows barrel imports from @openkit/agents without bundler-only .md loaders)
- lock @openkit/agents exports to barrel only (index.ts)
- update agent skills, launch prompts, and docs to use CLI command
@fum4 fum4 self-assigned this Mar 18, 2026
@vercel

vercel Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
openkit Ready Ready Preview, Comment Mar 18, 2026 11:35pm

@github-actions

github-actions Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude Review

🟠 Medium

  1. apps/server/src/routes/config.ts:548-558 — The /api/instance endpoint uses execFileSync and readFileSync synchronously in a request handler, blocking the event loop. For a rarely-called endpoint this is low-risk, but inconsistent with async patterns elsewhere. The readFileSync of .git when it's a directory will throw — handled by catch, but a statSync check would be cleaner.

  2. apps/server/src/routes/tasks.ts:453 — resolveActiveLinkedWorktreeId is still called (const linkedWorktreeId = resolveActiveLinkedWorktreeId(task.id);) but the result is never used after the TASK.md regeneration code was removed. Dead code.

  3. apps/cli/src/task.ts — detectWorktreeId redundant loop — The function walks up parent directories but dir.indexOf(marker) will match on the same substring regardless of which parent we're checking since the marker only appears once in the path. The upward walk is unnecessary — a single indexOf on process.cwd() suffices. Not a bug, just dead logic.

  4. apps/web-app/src/components/TabBar.tsx:163 — Tailwind dynamic class interpolation using template literals like text-[${palette.text2}] won't work with Tailwind's JIT compiler — these classes won't be included in the CSS output because Tailwind can't statically analyze them. Use full class names or inline styles instead.

🟡 Minor

  1. apps/cli/src/__test__/task-context.test.ts — Heavy mock surface: many mocks for modules not directly tested (Jira, Linear, server manager, etc.) needed because task.ts imports them at the module level. Consider lazy imports in task.ts to reduce test coupling.

  2. libs/agents/package.json — The "./*": "./src/*.ts" export was removed, restricting all imports to the barrel. Correct per import policy, but verify no external consumers relied on subpath imports like @openkit/agents/task-context.

  3. docs/superpowers/plans/2026-03-18-task-context-cli.md — This 679-line plan file is included in the PR but the implementation is already done. Consider marking it as completed.

  4. Removal of per-package check:format/check:lint/fix:format/fix:lint scripts — These were removed from all packages in favor of root-level oxfmt/oxlint commands. This is a reasonable consolidation, but the root check:all now runs oxfmt --check . and oxlint . sequentially with && rather than in parallel, which is slower than the previous Nx-parallel approach.

🟢 Resolved

  1. docs/CLI.md — Broken table formatting — The command inventory table no longer has the extra | --- | column or trailing | |. The openkit task context row is properly formatted.

  2. apps/web-app/src/components/TabBar.tsx:163 — instanceInfo.port empty string concern — The port is now derived in useInstanceInfo with explicit null checks (returns null when port is empty), and the template uses {instanceInfo.port && ...} which correctly handles both null and empty string since both are falsy.

  3. apps/web-app/src/hooks/useWorktrees.ts:197 — useInstanceInfo unhandled promise — A .catch() has been added to the apiFetchInstanceInfo call.

  4. AGENTS.md / CLAUDE.md — Removed MCP guardrail guidance — The "MCP Status (Removed)" section was deleted. The "Git Commits" section ("Never commit unless the user explicitly asks") was also removed. These were noted as potentially useful guardrails. The files are now synced with each other and the Mirror File Requirement section is present in both.

@coderabbitai

coderabbitai Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Replaces server-side TASK.md generation with an on-demand openkit task context CLI command, moves local task files to issue.json (with task.json fallback), introduces task-context formatters, removes pending-context/hooks-provider plumbing, updates server routes, tests, web UI prompts, docs, and agent workflows.

Changes

Cohort / File(s) Summary
CLI Task Context
apps/cli/src/task.ts, apps/cli/src/index.ts, apps/cli/src/__test__/task-context.test.ts
Adds openkit task context command, helpers to detect worktree ID, load issue/notes, resolve hooks, and output markdown/JSON; includes comprehensive tests.
CLI Config & Tests
apps/cli/package.json, apps/cli/tsconfig.json, apps/cli/vitest.config.ts
Adds Vitest config, test scripts, and vitest typing; configures module alias and md plugin.
Server TASK.md Removal & Manager
apps/server/src/task-context.ts (deleted), apps/server/src/manager.ts, apps/server/src/index.ts
Removes TASK.md generation module, pendingWorktreeContext and taskHooksProvider; adds startupCwd tracking and simplifies route registration/startup.
Server Routes & API
apps/server/src/routes/tasks.ts, apps/server/src/routes/notes.ts, apps/server/src/routes/linear.ts, apps/server/src/routes/config.ts
Stops TASK.md regeneration, prefers issue.json over task.json, removes hooksManager deps, and adds /api/instance endpoint.
Server Tests & Hooks Storage
apps/server/src/__test__/task-context.test.ts, apps/server/src/__test__/verification-manager.test.ts, apps/server/src/verification-manager.ts, apps/server/standalone.ts, apps/server/vitest.config.ts
Updates tests to new formatters and to .openkit/hooks-run.json path; integrates md plugin and startupCwd propagation.
Task Context Formatters (agents lib)
libs/agents/src/task-context.ts, libs/agents/src/index.ts, libs/agents/src/instructions.ts
Adds formatTaskContext/formatTaskContextJson and TaskContextJson type, restructures instruction exports (CLAUDE_SKILL, CURSOR_RULE, VSCODE_PROMPT).
Shared Tooling & Plugins
libs/shared/src/vite-md-plugin.ts, libs/shared/src/logger.ts, libs/shared/src/detect-config.ts
Adds mdRawPlugin (import .md as raw), minor logger/comment updates.
Agents Skill Docs & Workflows
.claude/skills/work-on-task/SKILL.md, libs/agents/src/work-skill/base.md, libs/agents/src/sample-skills/how-to-test/SKILL.md, CLAUDE.md, AGENTS.md
Consolidates steps to run openkit task context, reorders checkpoints, and adds doc/governance updates (JSDoc header rule, CLAUDE/AGENTS mirroring).
Web App UI & Prompts
apps/web-app/src/App.tsx, apps/web-app/src/components/ProjectSetupScreen.tsx, apps/web-app/src/components/*.{tsx,ts}, apps/web-app/src/components/__test__/CreateForm.test.tsx
Replaces TASK.md messaging with openkit task context, adds setup-flow tracking, renames labels/icons (Create issue, FileText), updates tests.
Instance Info & Hooks in UI
apps/web-app/src/components/TabBar.tsx, apps/web-app/src/components/detail/*, apps/web-app/src/hooks/api.ts, apps/web-app/src/hooks/useWorktrees.ts
Adds InstanceInfo/fetchInstanceInfo and useInstanceInfo hook; shows branch/port in UI; updates agent launch prompts.
Docs, Website & Plans
docs/*, apps/website/src/scripts/download-bootstrap.ts, docs/superpowers/*
Documents new CLI command, removes TASK.md-first references, updates config schema (issue.json), and adds design/plan docs for task-context migration.
Package Scripts & NX
multiple package.json and nx.json files across repo
Removes many format/lint fix/check scripts in subpackages; adjusts root scripts to use ox tooling and updates NX target defaults.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI (openkit)
  participant FS as Filesystem
  participant Config as Config / Hooks
  participant Formatter as Agents.formatTaskContext

  CLI->>FS: detect worktree (search .openkit/worktrees/<id>)
  CLI->>FS: load issue data (`issue.json` or fallback `task.json`)
  CLI->>FS: load notes (`notes.json`)
  CLI->>Config: resolve effective hooks (global + per-issue overrides)
  CLI->>Formatter: formatTaskContext / formatTaskContextJson(issue, notes, hooks)
  Formatter-->>CLI: formatted markdown or JSON
  CLI-->>User: output to stdout (or exit with error if not found)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I sniff the worktree, hop and find the clue,
No more TASK.md piles — the context comes when due.
Run the command, fetch the facts, and then begin to code,
A rabbit's tiny rhythm, clearing the old road. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is vague and generic, using non-specific terms like 'couple other' that don't convey meaningful information about the substantial changeset. Revise the title to be more specific and descriptive. Consider something like: 'refactor: replace TASK.md generation with on-demand task context CLI' to clearly communicate the main changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/task-context-cli-command
📝 Coding Plan
  • Generate coding plan for human review comments

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
apps/server/src/manager.ts (1)

714-720: ⚠️ Potential issue | 🟠 Major

Log parse failures in the migrated local-issue read path.

Line 718 silently swallows JSON parse errors; this makes corrupt issue.json / task.json files hard to diagnose in production.

🛠️ Proposed fix
           if (existsSync(taskFile)) {
             try {
               const taskData = JSON.parse(readFileSync(taskFile, "utf-8"));
               if (taskData.id) info.localIssueId = taskData.id;
               if (taskData.status) info.localIssueStatus = taskData.status;
-            } catch {
-              /* ignore */
+            } catch (error) {
+              log.warn("Failed to parse local issue metadata", {
+                domain: "worktree",
+                worktreeId: entry.name,
+                issueDir,
+                taskFile,
+                error,
+              });
             }
           }
As per coding guidelines, "Silent `catch {}` blocks are never acceptable" and errors should include actionable metadata.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/manager.ts` around lines 714 - 720, The JSON.parse failure
for the migrated local-issue read is currently swallowed by an empty catch,
making corrupt issue.json/task.json hard to diagnose; update the try/catch
around JSON.parse(readFileSync(taskFile, "utf-8")) to catch the error and log it
(using the existing logger or processLogger) with actionable metadata such as
the taskFile path and the error message/stack, then preserve current behavior of
not crashing (i.e., continue without setting info.localIssueId/status) so
callers using info.localIssueId and info.localIssueStatus remain unchanged.
apps/server/src/verification-manager.ts (1)

197-206: ⚠️ Potential issue | 🟡 Minor

Documentation inconsistency: path doesn't match docs.

The new path .openkit/worktrees/{worktreeId}/.openkit/hooks-run.json differs from what's documented in docs/HOOKS.md (line 194), which still shows:

worktrees/
  <worktreeId>/
    hooks.json                              # Combined step run + skill results

The docs should be updated to reflect the new nested .openkit/ directory and the renamed file hooks-run.json.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/verification-manager.ts` around lines 197 - 206, The
documentation is out of sync with the code: update docs/HOOKS.md to reflect that
hooks are now stored under a nested .openkit directory and the file was renamed
to hooks-run.json; specifically, change references that show
worktrees/<worktreeId>/hooks.json to
.openkit/worktrees/{worktreeId}/.openkit/hooks-run.json (matching the
hooksFilePath method which composes the path via this.manager.getConfigDir(),
CONFIG_DIR_NAME and the hook filename hooks-run.json) and ensure the doc comment
explains the difference between combined hooks.json and the new hooks-run.json
naming/placement.
docs/HOOKS.md (1)

188-195: ⚠️ Potential issue | 🟡 Minor

Data Storage section needs updating.

The path shown here is outdated. Based on the code changes in verification-manager.ts, the actual path is now:

.openkit/
  .openkit/
    hooks.json                                  # Global hooks configuration
    worktrees/
      <worktreeId>/
        .openkit/
          hooks-run.json                        # Combined step run + skill results

As per coding guidelines: "Keep ALL docs in sync at ALL TIMES."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/HOOKS.md` around lines 188 - 195, The Data Storage section in HOOKS.md
is outdated: update the tree to match the path used by verification-manager.ts
so the per-worktree combined run file is now nested under a .openkit directory
and named hooks-run.json; replace the current example block that shows
worktrees/<worktreeId>/hooks.json with
worktrees/<worktreeId>/.openkit/hooks-run.json and ensure the global hooks.json
entry remains unchanged to reflect the new hooks-run.json location used by
verification-manager.ts.
docs/CONFIGURATION.md (1)

882-889: ⚠️ Potential issue | 🟠 Major

Update per-worktree hook run path docs to hooks-run.json.

Line 889 still documents hooks.json, but this PR moves run persistence to .openkit/hooks-run.json. This section is now stale and misleading.

🛠️ Proposed doc fix
 .openkit/worktrees/<worktreeId>/
-  hooks.json            # Combined step run results + skill results
+  .openkit/
+    hooks-run.json      # Combined step run results + skill results

As per coding guidelines, “Keep ALL docs in sync at ALL TIMES. After every change, check if any docs in /docs/ or README.md need updating and update them immediately.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/CONFIGURATION.md` around lines 882 - 889, The docs still reference
per-worktree hook results as `hooks.json` under
`.openkit/worktrees/<worktreeId>/` which is stale; update the text and the
example listing to reference the new filename `hooks-run.json` (and any
descriptive text that says "hooks.json") so it reflects that run persistence is
now stored as `.openkit/hooks-run.json`; keep the mention of `openkit task
context` intact and ensure the example block shows
`.openkit/worktrees/<worktreeId>/ hooks-run.json` instead of `hooks.json`.
docs/CLI.md (1)

15-30: ⚠️ Potential issue | 🟡 Minor

Fix malformed Command Inventory table columns.

The separator row at Line 15 defines 3 columns while the header has 2, and Line 30 adds an empty trailing column. This breaks table rendering.

🛠️ Proposed doc fix
-| ---------------------------------------------------------- | ------------------------------------------------------------------------ | --- |
+| ---------------------------------------------------------- | ------------------------------------------------------------------------ |
@@
-| `openkit task context [<issue-id>] [--json]`               | Output merged task context (issue data, notes, hooks). Default markdown. |     |
+| `openkit task context [<issue-id>] [--json]`               | Output merged task context (issue data, notes, hooks). Default markdown. |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/CLI.md` around lines 15 - 30, The table's separator row currently
defines three columns while the header and entries have two, and the last row
contains an extra empty third column; fix by changing the separator to define
exactly two columns (e.g., use "| --- | --- |") and remove the trailing empty
column from the last row so every row (headers and all command rows like
`openkit ...`, `ok ...`, `openkit init`, etc.) has exactly two pipe-separated
columns.
🧹 Nitpick comments (12)
apps/server/src/routes/linear.ts (3)

29-29: Pre-existing: Parent-relative import should use alias.

The import ../logger uses a parent-relative path. Per coding guidelines for apps/**/*.{ts,tsx}, only same-folder relative imports are allowed; anything outside the current folder should use configured aliases.

♻️ Suggested change

If an alias like @server/logger is configured:

-import { log } from "../logger";
+import { log } from "@server/logger";

As per coding guidelines: "Do not use parent-relative imports (for example ../ or ../../) in app source files."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/linear.ts` at line 29, Replace the parent-relative
import of the logger by updating the import that currently reads from
"../logger" to use the configured project alias (e.g. import { log } from
"@server/logger"); locate the import of the symbol "log" in linear.ts and change
the module specifier to the alias so that no parent-relative paths (../ or
../../) remain in this app source file.

197-203: Pre-existing: Silent catch block should log a warning.

Per coding guidelines, empty catch blocks are never acceptable. If JSON parsing fails for a cached issue file, it would help debugging to log a warning with the issue identifier and error.

♻️ Suggested improvement
                   try {
                     const cached = JSON.parse(readFileSync(issueFile, "utf-8"));
                     status = cached.status;
                   } catch {
-                    /* ignore */
+                    log.warn(`Failed to parse cached issue file`, { domain: "Linear", issueId, issueFile });
                   }

As per coding guidelines: "Silent catch {} blocks are never acceptable... If you genuinely cannot handle an error, re-throw it or log it at warn/error level with context."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/linear.ts` around lines 197 - 203, The empty catch
around JSON.parse(readFileSync(issueFile, "utf-8")) must be replaced with a
catch that accepts an error and logs a warning including the issue identifier
(issueFile or any local issue ID), the fact that parsing the cached issue
failed, and the error details; locate the try/catch that reads into cached and
sets status and change catch { /* ignore */ } to catch (err) {
logger.warn(`Failed to parse cached issue ${issueFile}`, err); } (or use the
module's existing logger variable name) so failures are recorded for debugging.

210-214: Pre-existing: Silent catch block should log a warning.

Same concern as above—scan errors are silently swallowed. A debug or warn log would aid in diagnosing issues when directory scanning fails unexpectedly.

♻️ Suggested improvement
           } catch {
-            /* ignore scan errors */
+            log.debug(`Failed to scan cached issues directory`, { domain: "Linear", linearIssuesDir });
           }

As per coding guidelines: "Silent catch {} blocks are never acceptable."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/linear.ts` around lines 210 - 214, The empty catch
block in apps/server/src/routes/linear.ts silently swallows scan errors; change
it to catch the error (e.g., catch (err)) and log a warning with the error and
any relevant context (directory/path variable or function name) using the
module's logger (e.g., logger.warn or console.warn) so scan failures are visible
for debugging.
libs/shared/src/vite-md-plugin.ts (1)

7-15: LGTM!

Clean implementation of a Vite plugin for raw markdown imports. The transform logic correctly handles .md files by exporting their content as a default string export.

Consider adding an explicit return type for better type safety:

♻️ Optional: Add explicit Plugin type
+import type { Plugin } from "vite";
+
-export function mdRawPlugin() {
+export function mdRawPlugin(): Plugin {
   return {
     name: "md-raw-loader",
     transform(code: string, id: string) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/vite-md-plugin.ts` around lines 7 - 15, Add an explicit Vite
Plugin return type to the mdRawPlugin function for stronger type safety: import
the Plugin type from 'vite' and change the signature to export function
mdRawPlugin(): Plugin { ... }, keeping the existing transform method and
behavior (name "md-raw-loader" and the .md handling) unchanged so the function
is fully typed while preserving current logic.
apps/cli/package.json (1)

14-14: Consider adding vitest to this package's devDependencies for isolated testing.

The vitest run script references vitest which is hoisted from the workspace root (vitest is declared in the root package.json and vitest.config.ts is configured for this package). This works correctly in the monorepo context. However, adding vitest explicitly to this package's devDependencies would allow the package to be tested in isolation if needed and clarify its test runtime dependency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/package.json` at line 14, The package's "test" script in
package.json references vitest but vitest is only declared at the workspace
root; add vitest to this package's devDependencies (matching the workspace/root
version) so the "test": "vitest run" script can run in isolation and the runtime
dependency is explicit; update package.json's devDependencies to include
"vitest": "<version>" and run an install to verify local execution.
libs/agents/src/task-context.ts (1)

35-35: Tighten JSON output typing for source.

TaskContextJsonOutput.source is currently string; using IssueSource would prevent invalid source values at compile time.

♻️ Proposed type-tightening diff
 export interface TaskContextJsonOutput {
-  source: string;
+  source: IssueSource;
   issueId: string;
   identifier: string;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/agents/src/task-context.ts` at line 35, The TaskContextJsonOutput type
currently declares source as a plain string which allows invalid values; change
the source property's type from string to the IssueSource enum/type so
TypeScript enforces valid sources — locate TaskContextJsonOutput (and the source
field declaration) in task-context.ts and replace its type with IssueSource,
updating any imports or exported types as needed to compile.
apps/cli/src/__test__/task-context.test.ts (1)

1-405: Comprehensive test coverage for helper functions — consider adding tests for runTaskContext.

The test file thoroughly covers the helper functions (detectWorktreeId, loadIssueDataForContext, loadNotesFile, resolveEffectiveHooks) with good edge case coverage including malformed JSON, missing files, and fallback behavior. The structure follows Arrange-Act-Assert and places one behavior per it().

However, the main exported function runTaskContext (which orchestrates these helpers and handles CLI output) is not tested. Consider adding integration-style tests for it to verify the full flow including error exits and JSON/markdown output paths.

Would you like me to help draft test cases for runTaskContext covering:

  • Explicit issue ID with markdown output
  • Explicit issue ID with --json flag
  • Auto-detect from worktree context
  • Error when not in worktree and no ID provided
  • Error when issue not found
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/__test__/task-context.test.ts` around lines 1 - 405, Add
integration-style tests for the main exported function runTaskContext in the
existing task-context.test.ts suite: import runTaskContext from "../task", mock
filesystem (existsSync/readFileSync), child_process execFileSync, logger and
formatters, and the integrations (jira/linear) to control behavior; then add
tests for (1) explicit issue id with markdown output asserting logger.plain or
formatTaskContext was called with expected data, (2) explicit id with --json
flag asserting formatTaskContextJson output and no markdown calls, (3)
auto-detect from worktree context by stubbing process.cwd to a
.openkit/worktrees/<id> path and ensuring runTaskContext uses that id, (4) error
when not in worktree and no id provided by asserting process.exit(1) /
logger.error called, and (5) error when issue not found by having
loadIssueDataForContext return null and asserting proper error handling; reuse
existing helper mocks (mockedExistsSync/mockedReadFileSync) and reset mocks
between tests to keep isolation.
apps/cli/src/task.ts (5)

483-494: Silent catch block should log the error.

The catch block silently ignores malformed JSON files. Per coding guidelines, every catch block must do something meaningful to aid debugging.

♻️ Proposed fix
     try {
       const task = JSON.parse(readFileSync(taskFile, "utf-8")) as { id?: string; title?: string };
       const id = (task.id ?? entry.name).toUpperCase();
       const title = task.title?.trim() || "(no title)";
       results.push({ id, title });
-    } catch {
-      // ignore malformed local task file
+    } catch (err) {
+      log.debug(`Skipping malformed issue file: ${taskFile}`, {
+        domain: "task",
+        error: err instanceof Error ? err.message : String(err),
+      });
     }

As per coding guidelines: "Silent catch {} blocks are never acceptable."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/task.ts` around lines 483 - 494, The catch block that ignores
malformed task JSON in the task loading loop must log the error and context;
update the try/catch around JSON.parse (the block handling issueFile,
legacyFile, taskFile and pushing into results) to catch the exception and call a
logger (or console.warn/error) with a clear message including the taskFile (or
entry.name) and the error details so malformed files are visible during
debugging while still continuing processing.

889-894: Add debug logging for malformed notes.

♻️ Proposed fix
   try {
     return JSON.parse(readFileSync(notesPath, "utf-8"));
-  } catch {
-    return {};
+  } catch (err) {
+    log.debug(`Failed to parse notes file: ${notesPath}`, {
+      domain: "task-context",
+      error: err instanceof Error ? err.message : String(err),
+    });
+    return {};
   }

As per coding guidelines: "Never swallow errors silently."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/task.ts` around lines 889 - 894, The catch block that currently
swallows parsing errors around JSON.parse(readFileSync(notesPath, "utf-8")) must
log the malformed notes and the parsing error before returning {}. Update the
catch to read the raw file (using readFileSync and notesPath), log a clear
debug/error message including notesPath, the parsing error, and the raw contents
(via your logger or console.error), then return the empty object as before;
ensure references to JSON.parse, readFileSync, and notesPath are used so the log
pinpoints the failing input.

901-907: Add debug logging for hooks config parse failures.

If hooks.json is malformed, returning null is appropriate, but the silent catch makes it indistinguishable from a missing file.

♻️ Proposed fix
   let config: { steps?: HookStep[]; skills?: HookSkillRef[] };
   try {
     config = JSON.parse(readFileSync(hooksPath, "utf-8"));
-  } catch {
-    return null;
+  } catch (err) {
+    log.debug(`Failed to parse hooks config: ${hooksPath}`, {
+      domain: "task-context",
+      error: err instanceof Error ? err.message : String(err),
+    });
+    return null;
   }

As per coding guidelines: "If you genuinely cannot handle an error, re-throw it or log it at warn/error level with context."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/task.ts` around lines 901 - 907, The catch around
JSON.parse(readFileSync(hooksPath, "utf-8")) silently swallows parse errors;
update the catch to log the parse failure (including hooksPath and the caught
error) at warn/error level before returning null so malformed hooks.json is
distinguishable from a missing file (e.g., catch (err) { logger?.warn(...) ||
console.warn(...); return null; }), keeping the existing behavior of returning
null on failure.

866-883: Add debug logging for parse failures.

Returning null on parse error is a valid fallback, but silent failures make debugging difficult when issue data unexpectedly fails to load.

♻️ Proposed fix
   try {
     const raw = JSON.parse(readFileSync(filePath, "utf-8"));
     return {
       source,
       issueId,
       identifier: raw.identifier ?? raw.id ?? raw.key ?? issueId,
       title: raw.title ?? raw.summary ?? "",
       description: raw.description ?? "",
       status: raw.status ?? "",
       url: raw.url ?? "",
       comments: raw.comments,
       attachments: raw.attachments,
       linkedResources: raw.linkedResources,
     };
-  } catch {
-    return null;
+  } catch (err) {
+    log.debug(`Failed to parse issue file: ${filePath}`, {
+      domain: "task-context",
+      issueId,
+      source,
+      error: err instanceof Error ? err.message : String(err),
+    });
+    return null;
   }

As per coding guidelines: "Include actionable metadata in error logs: what operation failed, what inputs caused it."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/task.ts` around lines 866 - 883, The JSON.parse read block
currently swallows errors and returns null; update the catch to log an
actionable error including what failed and relevant inputs (filePath, source,
issueId) plus the error message/stack. In the catch for the try that
reads/parses using readFileSync, call the project's logger (e.g.,
processLogger.error) or console.error if no logger exists and include a clear
message like "Failed to parse issue file" along with filePath, source, issueId
and the caught error, then continue to return null. Ensure the log uses the same
scope variables (filePath, source, issueId) so debugging can tie the failure to
the input that caused it.

842-850: Silent catch block reduces diagnosability.

When notes.json parsing fails, the error is silently swallowed. If an issue becomes undetectable due to a corrupt notes file, there's no log trail to diagnose it.

♻️ Proposed fix
       try {
         const notes = JSON.parse(readFileSync(notesPath, "utf-8"));
         if (notes.linkedWorktreeId === worktreeId) {
           return { source, issueId: entry.name };
         }
-      } catch {
-        // skip malformed
+      } catch (err) {
+        log.debug(`Skipping malformed notes file: ${notesPath}`, {
+          domain: "task-context",
+          error: err instanceof Error ? err.message : String(err),
+        });
       }

As per coding guidelines: "If this fails in production, will I be able to diagnose it from the logs alone?"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/cli/src/task.ts` around lines 842 - 850, The catch block swallowing
JSON.parse errors for notes.json should log the failure with context instead of
being silent; update the catch in the loop that reads notesPath (where you parse
notes and check notes.linkedWorktreeId against worktreeId and return { source,
issueId: entry.name }) to emit an error/warning including notesPath and the
caught error/stack (use the project logger if available, e.g.
processLogger.error, or console.error) and then continue to skip the malformed
file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/cli/src/__test__/task-context.test.ts`:
- Around line 34-37: The test mock is using the wrong module path so it doesn't
intercept the real imports; update the vi.mock call in task-context.test.ts to
mock the same module the code imports by replacing the module string with
"@openkit/agents" and keep mocking the same functions (formatTaskContext and
formatTaskContextJson) so the test correctly stubs those exports used by the
production code (task.ts).

In `@apps/server/src/routes/config.ts`:
- Around line 541-561: The two empty catch blocks around the git branch/worktree
detection (the try that calls execFileSync to set branch and the try that reads
".git" to set isWorktree/worktreeName) should not silently swallow errors;
instead, catch the error as e and emit a structured log that includes domain
(e.g., domain: "api.instance.git-detection"), the error message/stack, and
relevant metadata such as startupCwd and the operation ("rev-parse" or "read
.git"), then allow normal flow (keep existing fallback behavior). Update the
catch for execFileSync and the catch for readFileSync to use the project’s
logger (processLogger or the module logger) to log these fields so failures are
observable while preserving current behavior of branch/isWorktree/worktreeName
when git is unavailable.

In `@apps/server/src/routes/tasks.ts`:
- Around line 91-98: The loadTask function currently parses JSON without error
handling, so malformed files throw a SyntaxError whereas missing files return
null; update loadTask to mirror loadIssueDataForContext by wrapping the read +
JSON.parse in a try-catch, returning null on parse/read errors (and optionally
logging the error) so callers get a consistent null-on-failure behavior; locate
the loadTask function and modify the JSON parsing block to catch exceptions and
return null instead of letting them propagate.

In `@apps/web-app/src/hooks/api.ts`:
- Around line 1777-1784: The catch block in fetchInstanceInfo currently swallows
errors; update it to catch the error as a variable (e.g., catch (err)) and log
the full error and context before returning the fallback InstanceInfo so
failures are observable (for example use console.error or the app logger with a
message like "fetchInstanceInfo failed" and include err). Ensure you modify the
catch in the fetchInstanceInfo function to log the error details (and any
relevant serverUrl) while preserving the existing fallback return shape.

In `@apps/web-app/src/hooks/useWorktrees.ts`:
- Around line 194-197: The call to apiFetchInstanceInfo inside the useEffect in
useWorktrees.ts lacks error handling; update the effect to append a .catch(...)
that calls reportPersistentErrorToast with the error (and optionally context)
and ensure failures don't leave unhandled rejections, keeping the existing
promise chain that calls setInstanceInfo on success; reference the useEffect
block, apiFetchInstanceInfo, setInstanceInfo, and reportPersistentErrorToast
when making this change.

In `@docs/superpowers/specs/2026-03-18-task-context-cli-design.md`:
- Around line 21-24: The fenced code block containing the CLI examples for
"openkit task context [<issue-id>]" needs a language identifier for markdown
linting and readability; update the triple-backtick fence to include "bash" so
the block reads as a bash code block and retains the two example lines ("openkit
task context [<issue-id>]" and "openkit task context [<issue-id>] --json")
unchanged.
- Line 85: The example attachment uses an absolute, machine-specific path
(`/path/to/local/file`); update the spec example to use a portable repo-relative
path (e.g., `./attachments/screenshot.png` or `docs/assets/screenshot.png`) so
the line with `screenshot.png` references a repository-relative attachment path
instead of an absolute filesystem path.

---

Outside diff comments:
In `@apps/server/src/manager.ts`:
- Around line 714-720: The JSON.parse failure for the migrated local-issue read
is currently swallowed by an empty catch, making corrupt issue.json/task.json
hard to diagnose; update the try/catch around JSON.parse(readFileSync(taskFile,
"utf-8")) to catch the error and log it (using the existing logger or
processLogger) with actionable metadata such as the taskFile path and the error
message/stack, then preserve current behavior of not crashing (i.e., continue
without setting info.localIssueId/status) so callers using info.localIssueId and
info.localIssueStatus remain unchanged.

In `@apps/server/src/verification-manager.ts`:
- Around line 197-206: The documentation is out of sync with the code: update
docs/HOOKS.md to reflect that hooks are now stored under a nested .openkit
directory and the file was renamed to hooks-run.json; specifically, change
references that show worktrees/<worktreeId>/hooks.json to
.openkit/worktrees/{worktreeId}/.openkit/hooks-run.json (matching the
hooksFilePath method which composes the path via this.manager.getConfigDir(),
CONFIG_DIR_NAME and the hook filename hooks-run.json) and ensure the doc comment
explains the difference between combined hooks.json and the new hooks-run.json
naming/placement.

In `@docs/CLI.md`:
- Around line 15-30: The table's separator row currently defines three columns
while the header and entries have two, and the last row contains an extra empty
third column; fix by changing the separator to define exactly two columns (e.g.,
use "| --- | --- |") and remove the trailing empty column from the last row so
every row (headers and all command rows like `openkit ...`, `ok ...`, `openkit
init`, etc.) has exactly two pipe-separated columns.

In `@docs/CONFIGURATION.md`:
- Around line 882-889: The docs still reference per-worktree hook results as
`hooks.json` under `.openkit/worktrees/<worktreeId>/` which is stale; update the
text and the example listing to reference the new filename `hooks-run.json` (and
any descriptive text that says "hooks.json") so it reflects that run persistence
is now stored as `.openkit/hooks-run.json`; keep the mention of `openkit task
context` intact and ensure the example block shows
`.openkit/worktrees/<worktreeId>/ hooks-run.json` instead of `hooks.json`.

In `@docs/HOOKS.md`:
- Around line 188-195: The Data Storage section in HOOKS.md is outdated: update
the tree to match the path used by verification-manager.ts so the per-worktree
combined run file is now nested under a .openkit directory and named
hooks-run.json; replace the current example block that shows
worktrees/<worktreeId>/hooks.json with
worktrees/<worktreeId>/.openkit/hooks-run.json and ensure the global hooks.json
entry remains unchanged to reflect the new hooks-run.json location used by
verification-manager.ts.

---

Nitpick comments:
In `@apps/cli/package.json`:
- Line 14: The package's "test" script in package.json references vitest but
vitest is only declared at the workspace root; add vitest to this package's
devDependencies (matching the workspace/root version) so the "test": "vitest
run" script can run in isolation and the runtime dependency is explicit; update
package.json's devDependencies to include "vitest": "<version>" and run an
install to verify local execution.

In `@apps/cli/src/__test__/task-context.test.ts`:
- Around line 1-405: Add integration-style tests for the main exported function
runTaskContext in the existing task-context.test.ts suite: import runTaskContext
from "../task", mock filesystem (existsSync/readFileSync), child_process
execFileSync, logger and formatters, and the integrations (jira/linear) to
control behavior; then add tests for (1) explicit issue id with markdown output
asserting logger.plain or formatTaskContext was called with expected data, (2)
explicit id with --json flag asserting formatTaskContextJson output and no
markdown calls, (3) auto-detect from worktree context by stubbing process.cwd to
a .openkit/worktrees/<id> path and ensuring runTaskContext uses that id, (4)
error when not in worktree and no id provided by asserting process.exit(1) /
logger.error called, and (5) error when issue not found by having
loadIssueDataForContext return null and asserting proper error handling; reuse
existing helper mocks (mockedExistsSync/mockedReadFileSync) and reset mocks
between tests to keep isolation.

In `@apps/cli/src/task.ts`:
- Around line 483-494: The catch block that ignores malformed task JSON in the
task loading loop must log the error and context; update the try/catch around
JSON.parse (the block handling issueFile, legacyFile, taskFile and pushing into
results) to catch the exception and call a logger (or console.warn/error) with a
clear message including the taskFile (or entry.name) and the error details so
malformed files are visible during debugging while still continuing processing.
- Around line 889-894: The catch block that currently swallows parsing errors
around JSON.parse(readFileSync(notesPath, "utf-8")) must log the malformed notes
and the parsing error before returning {}. Update the catch to read the raw file
(using readFileSync and notesPath), log a clear debug/error message including
notesPath, the parsing error, and the raw contents (via your logger or
console.error), then return the empty object as before; ensure references to
JSON.parse, readFileSync, and notesPath are used so the log pinpoints the
failing input.
- Around line 901-907: The catch around JSON.parse(readFileSync(hooksPath,
"utf-8")) silently swallows parse errors; update the catch to log the parse
failure (including hooksPath and the caught error) at warn/error level before
returning null so malformed hooks.json is distinguishable from a missing file
(e.g., catch (err) { logger?.warn(...) || console.warn(...); return null; }),
keeping the existing behavior of returning null on failure.
- Around line 866-883: The JSON.parse read block currently swallows errors and
returns null; update the catch to log an actionable error including what failed
and relevant inputs (filePath, source, issueId) plus the error message/stack. In
the catch for the try that reads/parses using readFileSync, call the project's
logger (e.g., processLogger.error) or console.error if no logger exists and
include a clear message like "Failed to parse issue file" along with filePath,
source, issueId and the caught error, then continue to return null. Ensure the
log uses the same scope variables (filePath, source, issueId) so debugging can
tie the failure to the input that caused it.
- Around line 842-850: The catch block swallowing JSON.parse errors for
notes.json should log the failure with context instead of being silent; update
the catch in the loop that reads notesPath (where you parse notes and check
notes.linkedWorktreeId against worktreeId and return { source, issueId:
entry.name }) to emit an error/warning including notesPath and the caught
error/stack (use the project logger if available, e.g. processLogger.error, or
console.error) and then continue to skip the malformed file.

In `@apps/server/src/routes/linear.ts`:
- Line 29: Replace the parent-relative import of the logger by updating the
import that currently reads from "../logger" to use the configured project alias
(e.g. import { log } from "@server/logger"); locate the import of the symbol
"log" in linear.ts and change the module specifier to the alias so that no
parent-relative paths (../ or ../../) remain in this app source file.
- Around line 197-203: The empty catch around JSON.parse(readFileSync(issueFile,
"utf-8")) must be replaced with a catch that accepts an error and logs a warning
including the issue identifier (issueFile or any local issue ID), the fact that
parsing the cached issue failed, and the error details; locate the try/catch
that reads into cached and sets status and change catch { /* ignore */ } to
catch (err) { logger.warn(`Failed to parse cached issue ${issueFile}`, err); }
(or use the module's existing logger variable name) so failures are recorded for
debugging.
- Around line 210-214: The empty catch block in apps/server/src/routes/linear.ts
silently swallows scan errors; change it to catch the error (e.g., catch (err))
and log a warning with the error and any relevant context (directory/path
variable or function name) using the module's logger (e.g., logger.warn or
console.warn) so scan failures are visible for debugging.

In `@libs/agents/src/task-context.ts`:
- Line 35: The TaskContextJsonOutput type currently declares source as a plain
string which allows invalid values; change the source property's type from
string to the IssueSource enum/type so TypeScript enforces valid sources —
locate TaskContextJsonOutput (and the source field declaration) in
task-context.ts and replace its type with IssueSource, updating any imports or
exported types as needed to compile.

In `@libs/shared/src/vite-md-plugin.ts`:
- Around line 7-15: Add an explicit Vite Plugin return type to the mdRawPlugin
function for stronger type safety: import the Plugin type from 'vite' and change
the signature to export function mdRawPlugin(): Plugin { ... }, keeping the
existing transform method and behavior (name "md-raw-loader" and the .md
handling) unchanged so the function is fully typed while preserving current
logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 47a023d9-9cd9-4892-aeb3-11379f9919d8

📥 Commits

Reviewing files that changed from the base of the PR and between e39dad3 and e11a51c.

📒 Files selected for processing (57)
  • .claude/skills/work-on-task/SKILL.md
  • AGENTS.md
  • CLAUDE.md
  • apps/cli/package.json
  • apps/cli/src/__test__/task-context.test.ts
  • apps/cli/src/index.ts
  • apps/cli/src/task.ts
  • apps/cli/tsconfig.json
  • apps/cli/vitest.config.ts
  • apps/server/src/__test__/task-context.test.ts
  • apps/server/src/__test__/verification-manager.test.ts
  • apps/server/src/index.ts
  • apps/server/src/manager.ts
  • apps/server/src/routes/config.ts
  • apps/server/src/routes/linear.ts
  • apps/server/src/routes/notes.ts
  • apps/server/src/routes/tasks.test.ts
  • apps/server/src/routes/tasks.ts
  • apps/server/src/standalone.ts
  • apps/server/src/task-context.ts
  • apps/server/src/verification-manager.ts
  • apps/server/vitest.config.ts
  • apps/web-app/src/App.tsx
  • apps/web-app/src/components/ConfigurationPanel.tsx
  • apps/web-app/src/components/CreateCustomTaskModal.tsx
  • apps/web-app/src/components/CreateForm.tsx
  • apps/web-app/src/components/LinkIssueModal.tsx
  • apps/web-app/src/components/ProjectSetupScreen.tsx
  • apps/web-app/src/components/TabBar.tsx
  • apps/web-app/src/components/WorktreeItem.tsx
  • apps/web-app/src/components/__test__/CreateForm.test.tsx
  • apps/web-app/src/components/detail/CustomTaskDetailPanel.tsx
  • apps/web-app/src/components/detail/DetailPanel.tsx
  • apps/web-app/src/components/detail/JiraDetailPanel.tsx
  • apps/web-app/src/components/detail/LinearDetailPanel.tsx
  • apps/web-app/src/components/detail/TerminalView.tsx
  • apps/web-app/src/hooks/api.ts
  • apps/web-app/src/hooks/useWorktrees.ts
  • apps/website/src/scripts/download-bootstrap.ts
  • docs/API.md
  • docs/ARCHITECTURE.md
  • docs/CLI.md
  • docs/CONFIGURATION.md
  • docs/HOOKS.md
  • docs/INTEGRATIONS.md
  • docs/superpowers/plans/2026-03-18-task-context-cli.md
  • docs/superpowers/specs/2026-03-18-task-context-cli-design.md
  • libs/agents/README.md
  • libs/agents/package.json
  • libs/agents/src/index.ts
  • libs/agents/src/instructions.ts
  • libs/agents/src/sample-skills/how-to-test/SKILL.md
  • libs/agents/src/task-context.ts
  • libs/agents/src/work-skill/base.md
  • libs/shared/src/detect-config.ts
  • libs/shared/src/logger.ts
  • libs/shared/src/vite-md-plugin.ts
💤 Files with no reviewable changes (2)
  • libs/shared/src/detect-config.ts
  • apps/server/src/task-context.ts

Comment on lines +541 to +561
try {
branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: startupCwd,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim();
} catch {
// Not a git repo or git not available
}

let isWorktree = false;
let worktreeName: string | null = null;
try {
const gitContent = readFileSync(path.join(startupCwd, ".git"), "utf-8").trim();
isWorktree = gitContent.startsWith("gitdir: ");
if (isWorktree) {
worktreeName = path.basename(startupCwd);
}
} catch {
// .git is a directory (main working tree) or doesn't exist
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Do not silently swallow errors in /api/instance.

Line 547 and Line 559 use silent catch {} branches, which removes observability for branch/worktree detection failures. Please log these failures with domain + actionable metadata.

🛠️ Proposed fix
 import { execFileSync } from "child_process";
 import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
 import path from "path";
 import type { Hono } from "hono";
+import { log } from "../logger";
@@
     let branch: string | null = null;
     try {
       branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
         cwd: startupCwd,
         encoding: "utf-8",
         stdio: ["pipe", "pipe", "pipe"],
       }).trim();
-    } catch {
-      // Not a git repo or git not available
+    } catch (error) {
+      log.warn("Failed to resolve instance branch", {
+        domain: "config-routes",
+        startupCwd,
+        error: error instanceof Error ? error.message : String(error),
+      });
     }
@@
     try {
       const gitContent = readFileSync(path.join(startupCwd, ".git"), "utf-8").trim();
       isWorktree = gitContent.startsWith("gitdir: ");
       if (isWorktree) {
         worktreeName = path.basename(startupCwd);
       }
-    } catch {
-      // .git is a directory (main working tree) or doesn't exist
+    } catch (error) {
+      log.debug("Failed to inspect .git pointer for worktree detection", {
+        domain: "config-routes",
+        startupCwd,
+        error: error instanceof Error ? error.message : String(error),
+      });
     }

As per coding guidelines, “Every catch block… must do something meaningful… Silent catch {} blocks are never acceptable,” and logs must include a domain field.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/config.ts` around lines 541 - 561, The two empty catch
blocks around the git branch/worktree detection (the try that calls execFileSync
to set branch and the try that reads ".git" to set isWorktree/worktreeName)
should not silently swallow errors; instead, catch the error as e and emit a
structured log that includes domain (e.g., domain:
"api.instance.git-detection"), the error message/stack, and relevant metadata
such as startupCwd and the operation ("rev-parse" or "read .git"), then allow
normal flow (keep existing fallback behavior). Update the catch for execFileSync
and the catch for readFileSync to use the project’s logger (processLogger or the
module logger) to log these fields so failures are observable while preserving
current behavior of branch/isWorktree/worktreeName when git is unavailable.

Comment on lines 91 to 98
function loadTask(configDir: string, id: string): CustomTask | null {
const filePath = path.join(getTasksDir(configDir), id, "task.json");
const dir = path.join(getTasksDir(configDir), id);
const issuePath = path.join(dir, "issue.json");
const legacyPath = path.join(dir, "task.json");
const filePath = existsSync(issuePath) ? issuePath : legacyPath;
if (!existsSync(filePath)) return null;
return JSON.parse(readFileSync(filePath, "utf-8")) as CustomTask;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

loadTask throws on malformed JSON despite returning null for missing files.

The function returns null when files don't exist but will throw a SyntaxError if JSON.parse fails on malformed JSON. This inconsistency could cause unhandled exceptions in callers that only check for null.

Consider wrapping the parse in a try-catch for consistency with the "return null on failure" pattern, similar to how loadIssueDataForContext handles this in the CLI:

🛡️ Proposed fix for consistent error handling
 function loadTask(configDir: string, id: string): CustomTask | null {
   const dir = path.join(getTasksDir(configDir), id);
   const issuePath = path.join(dir, "issue.json");
   const legacyPath = path.join(dir, "task.json");
   const filePath = existsSync(issuePath) ? issuePath : legacyPath;
   if (!existsSync(filePath)) return null;
-  return JSON.parse(readFileSync(filePath, "utf-8")) as CustomTask;
+  try {
+    return JSON.parse(readFileSync(filePath, "utf-8")) as CustomTask;
+  } catch {
+    return null;
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function loadTask(configDir: string, id: string): CustomTask | null {
const filePath = path.join(getTasksDir(configDir), id, "task.json");
const dir = path.join(getTasksDir(configDir), id);
const issuePath = path.join(dir, "issue.json");
const legacyPath = path.join(dir, "task.json");
const filePath = existsSync(issuePath) ? issuePath : legacyPath;
if (!existsSync(filePath)) return null;
return JSON.parse(readFileSync(filePath, "utf-8")) as CustomTask;
}
function loadTask(configDir: string, id: string): CustomTask | null {
const dir = path.join(getTasksDir(configDir), id);
const issuePath = path.join(dir, "issue.json");
const legacyPath = path.join(dir, "task.json");
const filePath = existsSync(issuePath) ? issuePath : legacyPath;
if (!existsSync(filePath)) return null;
try {
return JSON.parse(readFileSync(filePath, "utf-8")) as CustomTask;
} catch (err) {
log.warn("Failed to parse task file", {
domain: "tasks",
configDir,
id,
filePath,
error: String(err),
});
return null;
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/routes/tasks.ts` around lines 91 - 98, The loadTask function
currently parses JSON without error handling, so malformed files throw a
SyntaxError whereas missing files return null; update loadTask to mirror
loadIssueDataForContext by wrapping the read + JSON.parse in a try-catch,
returning null on parse/read errors (and optionally logging the error) so
callers get a consistent null-on-failure behavior; locate the loadTask function
and modify the JSON parsing block to catch exceptions and return null instead of
letting them propagate.

Comment on lines +1777 to +1784
export async function fetchInstanceInfo(serverUrl: string | null = null): Promise<InstanceInfo> {
try {
const res = await fetch(`${getBaseUrl(serverUrl)}/api/instance`);
if (!res.ok) throw new Error("Failed to fetch instance info");
return await res.json();
} catch {
return { branch: null, isWorktree: false, worktreeName: null };
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don’t silently swallow /api/instance failures.

Line 1782 currently suppresses the failure reason entirely. Returning only fallback values makes production diagnosis and user feedback impossible.

💡 Suggested fix
 export interface InstanceInfo {
   branch: string | null;
   isWorktree: boolean;
   worktreeName: string | null;
+  error?: string;
 }

 export async function fetchInstanceInfo(serverUrl: string | null = null): Promise<InstanceInfo> {
   try {
     const res = await fetch(`${getBaseUrl(serverUrl)}/api/instance`);
     if (!res.ok) throw new Error("Failed to fetch instance info");
     return await res.json();
-  } catch {
-    return { branch: null, isWorktree: false, worktreeName: null };
+  } catch (err) {
+    return {
+      branch: null,
+      isWorktree: false,
+      worktreeName: null,
+      error: err instanceof Error ? err.message : "Failed to fetch instance info",
+    };
   }
 }

As per coding guidelines: “Every catch block … must do something meaningful … Silent catch {} blocks are never acceptable.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/hooks/api.ts` around lines 1777 - 1784, The catch block in
fetchInstanceInfo currently swallows errors; update it to catch the error as a
variable (e.g., catch (err)) and log the full error and context before returning
the fallback InstanceInfo so failures are observable (for example use
console.error or the app logger with a message like "fetchInstanceInfo failed"
and include err). Ensure you modify the catch in the fetchInstanceInfo function
to log the error details (and any relevant serverUrl) while preserving the
existing fallback return shape.

Comment on lines +194 to +197
useEffect(() => {
// Pass serverUrl as-is — when null, the API call uses relative URLs (browser mode)
apiFetchInstanceInfo(serverUrl).then(setInstanceInfo);
}, [serverUrl]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing error handling for API call.

The apiFetchInstanceInfo call lacks a .catch() handler. If the API request fails, the promise rejection will be unhandled. Other hooks in this file (e.g., useProjectName, useJiraStatus) consistently use .catch() with reportPersistentErrorToast.

🛡️ Proposed fix to add error handling
   useEffect(() => {
     // Pass serverUrl as-is — when null, the API call uses relative URLs (browser mode)
-    apiFetchInstanceInfo(serverUrl).then(setInstanceInfo);
+    apiFetchInstanceInfo(serverUrl)
+      .then(setInstanceInfo)
+      .catch((error) => {
+        reportPersistentErrorToast(error, "Failed to fetch instance info", {
+          scope: "instance-info:fetch",
+        });
+      });
   }, [serverUrl]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/hooks/useWorktrees.ts` around lines 194 - 197, The call to
apiFetchInstanceInfo inside the useEffect in useWorktrees.ts lacks error
handling; update the effect to append a .catch(...) that calls
reportPersistentErrorToast with the error (and optionally context) and ensure
failures don't leave unhandled rejections, keeping the existing promise chain
that calls setInstanceInfo on success; reference the useEffect block,
apiFetchInstanceInfo, setInstanceInfo, and reportPersistentErrorToast when
making this change.

Comment on lines +21 to +24
```
openkit task context [<issue-id>] # markdown (agent-facing)
openkit task context [<issue-id>] --json # structured JSON
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add a language to the fenced command block.

This block should be typed (e.g., bash) to satisfy markdown linting and improve readability.

📝 Suggested fix
-```
+```bash
 openkit task context [<issue-id>]          # markdown (agent-facing)
 openkit task context [<issue-id>] --json   # structured JSON
</details>

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.21.0)</summary>

[warning] 21-21: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/superpowers/specs/2026-03-18-task-context-cli-design.md around lines 21

  • 24, The fenced code block containing the CLI examples for "openkit task
    context []" needs a language identifier for markdown linting and
    readability; update the triple-backtick fence to include "bash" so the block
    reads as a bash code block and retains the two example lines ("openkit task
    context []" and "openkit task context [] --json") unchanged.

</details>

<!-- fingerprinting:phantom:poseidon:hawk -->

<!-- This is an auto-generated comment by CodeRabbit -->


## Attachments

- `screenshot.png` (image/png) — `/path/to/local/file`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use a portable repo-relative attachment path in the spec example.

/path/to/local/file is absolute and machine-specific.

📝 Suggested fix
-- `screenshot.png` (image/png) — `/path/to/local/file`
+- `screenshot.png` (image/png) — `.openkit/issues/local/LOCAL-1/attachments/screenshot.png`

As per coding guidelines: “Design spec files should capture the what/why of features. Never use absolute or user-specific paths in specs.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- `screenshot.png` (image/png) — `/path/to/local/file`
- `screenshot.png` (image/png) — `.openkit/issues/local/LOCAL-1/attachments/screenshot.png`
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/superpowers/specs/2026-03-18-task-context-cli-design.md` at line 85, The
example attachment uses an absolute, machine-specific path
(`/path/to/local/file`); update the spec example to use a portable repo-relative
path (e.g., `./attachments/screenshot.png` or `docs/assets/screenshot.png`) so
the line with `screenshot.png` references a repository-relative attachment path
instead of an absolute filesystem path.

@fum4

fum4 commented Mar 18, 2026

Copy link
Copy Markdown
Owner Author

/package

@github-actions

github-actions Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

📦 Packaging completed

Triggered by @fum4 with /package

View workflow logs

Target Status Artifact
macOS (Apple Silicon) 📦 Success Download
macOS (Intel) 📦 Success Download
Linux 📦 Success Download

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web-app/src/components/TabBar.tsx (1)

94-94: ⚠️ Potential issue | 🟠 Major

Move palette colors to inline styles; dynamic Tailwind classes won't render

Lines 156, 158, 161, 167 use runtime-interpolated arbitrary values (text-[${palette.text2}], etc.) that Tailwind's static content scanner cannot detect, so these colors will fail to render. Line 94 uses a hardcoded color instead of a theme token. Per the coding guidelines, use the standard palette from theme.ts directly in style attributes.

Proposed fix
-    <div
-      className={`flex-shrink-0 flex items-center z-40 pl-5 pr-4 pb-5 pt-4 gap-1 ${overlaps ? "bg-[`#0c0e12`]/60 backdrop-blur-md" : ""}`}
-    >
+    <div
+      className={`flex-shrink-0 flex items-center z-40 pl-5 pr-4 pb-5 pt-4 gap-1 ${overlaps ? "backdrop-blur-md" : ""}`}
+      style={overlaps ? { backgroundColor: "rgba(12,14,18,0.6)" } : undefined}
+    >
@@
-      {(instanceInfo.branch || instanceInfo.port) && (
-        <div
-          className={`mr-4 h-7 inline-flex items-center gap-1.5 text-[10px] text-[${palette.text2}] font-mono select-text`}
-        >
-          <span className={`text-[${palette.text1}]`}>{instanceInfo.worktreeName ?? "root"}</span>
+      {(instanceInfo.branch || instanceInfo.port) && (
+        <div
+          className="mr-4 h-7 inline-flex items-center gap-1.5 text-[10px] font-mono select-text"
+          style={{ color: palette.text2 }}
+        >
+          <span style={{ color: palette.text1 }}>{instanceInfo.worktreeName ?? "root"}</span>
           {instanceInfo.branch && (
             <>
-              <span className={`text-[${palette.text3}]`}>·</span>
+              <span style={{ color: palette.text3 }}>·</span>
               <GitBranch className="w-3 h-3 flex-shrink-0" />
               <span>{instanceInfo.branch}</span>
             </>
           )}
           {instanceInfo.port && (
-            <span className={`text-[${palette.text3}] ml-0.5`}>:{instanceInfo.port}</span>
+            <span className="ml-0.5" style={{ color: palette.text3 }}>
+              :{instanceInfo.port}
+            </span>
           )}
         </div>
       )}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/TabBar.tsx` at line 94, Several
runtime-interpolated Tailwind classes in TabBar.tsx (e.g.,
`text-[${palette.text2}]`, `text-[${palette.text3}]`,
`ring-[${palette.border}]`, `bg-[${palette.bg}]`) and the hardcoded
`bg-[`#0c0e12`]/60` will not be picked up by Tailwind; replace those dynamic class
names with inline style attributes using the theme tokens from theme.ts (import
the palette token if not already imported) — e.g., on the elements currently
using `text-[${palette.text2}]`/`text-[${palette.text3}]` add style={{ color:
palette.text2 }} or palette.text3, for ring/border use style={{ boxShadow: `0 0
0 1px ${palette.border}` }} or appropriate borderColor, and replace
`bg-[`#0c0e12`]/60` with style={{ backgroundColor: <rgba/hex of theme token with
opacity> }} (or compute rgba from the theme color); ensure you remove the
dynamic arbitrary Tailwind classes and keep static Tailwind utility classes
only.
🧹 Nitpick comments (1)
package.json (1)

42-42: Prefer non-mutating checks in smoke script.

Using fix-mode commands in smoke can mask failures and produce dirty state during validation runs. Consider making smoke check-only and leaving mutation to fix:*.

Suggested change
-    "smoke": "oxfmt . && oxlint --fix . && pnpm nx run-many -t check:types,build,test --parallel",
+    "smoke": "oxfmt --check . && oxlint . && pnpm nx run-many -t check:types,build,test --parallel",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` at line 42, Update the "smoke" npm script to be check-only
instead of mutating: remove the --fix usage and invoke the format/lint tools in
their check mode (e.g. use oxfmt --check . and run oxlint without --fix or with
its --check flag if available) while keeping the pnpm nx run-many ... portion
unchanged; edit the "smoke" script string in package.json (the "smoke" property)
to reflect these non-mutating flags.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web-app/src/components/TabBar.tsx`:
- Around line 6-7: The TabBar component currently imports useInstanceInfo and
palette/surface with parent-relative paths; replace those parent-relative
imports for useInstanceInfo, palette, and surface with the project's configured
alias imports (the aliases defined in your TS/webpack config) so they no longer
use "../" (e.g., import useInstanceInfo from the hooks alias and palette/surface
from the theme alias).

---

Outside diff comments:
In `@apps/web-app/src/components/TabBar.tsx`:
- Line 94: Several runtime-interpolated Tailwind classes in TabBar.tsx (e.g.,
`text-[${palette.text2}]`, `text-[${palette.text3}]`,
`ring-[${palette.border}]`, `bg-[${palette.bg}]`) and the hardcoded
`bg-[`#0c0e12`]/60` will not be picked up by Tailwind; replace those dynamic class
names with inline style attributes using the theme tokens from theme.ts (import
the palette token if not already imported) — e.g., on the elements currently
using `text-[${palette.text2}]`/`text-[${palette.text3}]` add style={{ color:
palette.text2 }} or palette.text3, for ring/border use style={{ boxShadow: `0 0
0 1px ${palette.border}` }} or appropriate borderColor, and replace
`bg-[`#0c0e12`]/60` with style={{ backgroundColor: <rgba/hex of theme token with
opacity> }} (or compute rgba from the theme color); ensure you remove the
dynamic arbitrary Tailwind classes and keep static Tailwind utility classes
only.

---

Nitpick comments:
In `@package.json`:
- Line 42: Update the "smoke" npm script to be check-only instead of mutating:
remove the --fix usage and invoke the format/lint tools in their check mode
(e.g. use oxfmt --check . and run oxlint without --fix or with its --check flag
if available) while keeping the pnpm nx run-many ... portion unchanged; edit the
"smoke" script string in package.json (the "smoke" property) to reflect these
non-mutating flags.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 66c990ed-e838-492a-aa9f-0c68427f4d00

📥 Commits

Reviewing files that changed from the base of the PR and between e11a51c and c327fa1.

📒 Files selected for processing (17)
  • apps/cli/package.json
  • apps/cli/src/__test__/task-context.test.ts
  • apps/desktop-app/package.json
  • apps/mobile-app/package.json
  • apps/server/package.json
  • apps/web-app/package.json
  • apps/web-app/src/components/TabBar.tsx
  • apps/web-app/src/hooks/useWorktrees.ts
  • apps/website/package.json
  • docs/CLI.md
  • libs/agents/package.json
  • libs/integrations/package.json
  • libs/logger/package.json
  • libs/port-offset/package.json
  • libs/shared/package.json
  • nx.json
  • package.json
💤 Files with no reviewable changes (1)
  • nx.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/CLI.md
  • apps/web-app/src/hooks/useWorktrees.ts

Comment on lines +6 to +7
import { useInstanceInfo } from "../hooks/useWorktrees";
import { palette, surface } from "../theme";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Use configured alias imports instead of parent-relative paths

Line 6 and Line 7 introduce ../ imports in app source. This violates the repo import-boundary rule and should be switched to the configured alias form.

As per coding guidelines: “Do not use parent-relative imports (e.g., ../ or ../../) in app/lib source files… For anything outside the current folder, use configured aliases.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/TabBar.tsx` around lines 6 - 7, The TabBar
component currently imports useInstanceInfo and palette/surface with
parent-relative paths; replace those parent-relative imports for
useInstanceInfo, palette, and surface with the project's configured alias
imports (the aliases defined in your TS/webpack config) so they no longer use
"../" (e.g., import useInstanceInfo from the hooks alias and palette/surface
from the theme alias).

@fum4
fum4 merged commit ede1634 into master Mar 19, 2026
19 checks passed
@fum4
fum4 deleted the refactor/task-context-cli-command branch March 19, 2026 01:16

This branch was successfully deployed

1 active deployment
Preview — c327fa1f Deployed Mar 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant