Commit Graph
698 Commits
Author SHA1 Message Date
ZacharyZhang-NY 8dd0376e0f Package release 0.4.168 from the current workspace snapshot
Constraint: Windows and Linux artifacts are built on native GitHub runners from a temporary snapshot branch
Rejected: Build Windows/Linux locally on Apple Silicon | docker/wine packaging is not stable on this host
Confidence: medium
Scope-risk: moderate
Directive: This snapshot branch is transport-only and should be deleted after the release completes
Tested: local verify/build stages before snapshot creation
Not-tested: remote packaging before workflow execution
2026-04-21 16:51:34 -04:00
ZacharyZhang-NY aba2dac3c5 fix(docs): stop leaking backend reason codes to the open-file toast
The previous toast pasted result.error.message straight into the UI,
so a failed open rendered
  "Couldn't open CEO-WEEK2-DAY1-SUMMARY.md: workspace_id=null
  task_id=null run_id=61669170-180b-4cb3-99d2-eb925ca9717c — none led
  to a workspace with a local_path"
to the operator. That text is a developer log line, not user feedback.

Drop the passthrough — the toast now simply reads
  "Couldn't open <filename>"
and the diagnostic details live only in the IPC return payload (which
a devtools or automated caller can still read). The resolver's five
reason codes and their detail strings remain intact in the main
process; they just no longer surface to the UI.
2026-04-21 14:58:39 -04:00
ZacharyZhang-NY 9fba8dd6c3 fix(projector): stop writing null workspace_id on work_products
Two sites in upsertFilesystemArtifact leaked null workspace_ids
into the work_products table and produced the orphan rows the read
path now has to heal:

1. Create path unconditionally forwarded ctx.workspaceId, which was
   null whenever a run was created without a workspace binding
   (historically cognitive runs, or runs that lost their link through
   the observationPath regression fixed in 1f2f977).

2. Update path passed {workspaceId: ctx.workspaceId} as part of the
   patch. updateWorkProduct treats any key present in patch as "write
   this value", so a run touching a previously-well-linked row with
   ctx.workspaceId=null would clobber the existing workspace_id back
   to null — actively destroying data.

Resolve both at the projector layer:

  - Add workspacesMod.findWorkspaceIdByLocalPath(companyId, localPath)
    as a reverse-lookup. workspacePath is the argument the projector
    is already walking; it came from some workspace row's local_path,
    so finding that row by path is deterministic.
  - Compute resolvedWorkspaceId = ctx.workspaceId ?? reverseLookup(...)
    once, and use it for both the identity lookup
    (findWorkProductByExternalId) and the subsequent write.
  - On the update path, only include workspaceId in the patch when
    resolvedWorkspaceId is non-null. Null now means "no info — leave
    the existing column alone" instead of "clobber to null".

Together with the read-path heal in cfb8ba5 this closes the loop:
new files never enter the table with a null workspace_id if we can
possibly resolve it, old files keep their links, and truly unlinkable
rows still fall back to the observation workspace on open.

Typecheck and build:verify clean.
2026-04-21 14:52:38 -04:00
ZacharyZhang-NY cfb8ba5dc1 fix(docs): heal orphan work_products by falling back to observation workspace
Work-product rows written before the artifact projector tracked
workspace_id end-to-end can lose the link through all three joins:
workspace_id is NULL, task_id is NULL, and the row's run exists but
its runs.workspace_id is also NULL. Those orphans were readable in
the DocumentCenter (the listing doesn't need a workspace root) but
could not be opened — resolveWorkProductTarget returned null and the
toast now reports workspace_unresolved.

Add a fourth resolution tier in resolveWorkProductTarget: if the
three-step chain yields nothing, look up the company's observation
workspace (primary first, then oldest) and check whether the
external_id resolves to a real file inside that root. If it does,
return that absolute path and the row opens. If the file isn't
there, the error falls through with an extended detail line naming
the observation root that was tried, so the operator sees exactly
why the heal also failed.

This is deterministic — exactly one fallback workspace — and
side-effect-free on the read path: the row itself is left alone,
no stealth write-back. A follow-up commit will stop the projector
from writing NULL workspace_id in the first place.

Typecheck and build:verify clean.
2026-04-21 14:51:06 -04:00
ZacharyZhang-NY 390f76fa76 fix(docs): split work-product open errors into actionable reasons
The previous handler folded every null target into one error code
("WORK_PRODUCT_NOT_FOUND: Work product not found or its workspace
is unresolved"). When a user couldn't open a file we had no way to
tell whether the row was archived, the provider/external_id was
empty, the workspace had no local_path, or the external_id escaped
the root.

Widen resolveWorkProductTarget's return from (target | null) to
(target | error) where error carries one of five reasons:

  not_found             row missing for id+company
  archived              status == "archived" tombstone
  no_target             provider != filesystem and no url
  workspace_unresolved  all three workspace_id / task_id / run_id
                         lookups returned no local_path
  path_escape           external_id is absolute or steps outside root

Each reason includes the concrete detail (ids checked, paths tried)
so the toast on the renderer side tells the user exactly which slot
is null without having to open the DB.

The IPC handler maps each reason to its own failure code and passes
the detail through, so WorkProductRow's toast now reads e.g.
"workspace_id=null task_id=null run_id=null — none led to a
workspace with a local_path" instead of a generic unresolved.

Typecheck and build:verify clean.
2026-04-21 14:45:59 -04:00
ZacharyZhang-NY 9f43549606 fix(docs): surface work-product open failures with a toast
Clicking a Files & Deliverables row fired openWorkProduct and then
discarded the result with \`void\`. When the main process could not
resolve the target — archived work product, missing workspace root,
path outside the managed root, or \`shell.openPath\` reporting no
associated app for the file type — the renderer stayed silent and
the row looked like a dead button. The user had no way to know why
"clicking" did nothing.

Await the result in WorkProductRow and route non-ok responses through
addToast with tone="danger". The caller sees the underlying failure
(OPEN_PATH_FORBIDDEN / OPEN_PATH_FAILED / WORK_PRODUCT_NOT_FOUND /
the shell's own message) and can act on it. No backend change — the
handler already returned structured errors; this just stops dropping
them.

Typecheck and build:verify clean.
2026-04-21 14:42:00 -04:00
ZacharyZhang-NY 7301b00cb2 fix(design): actually apply org chart color-bar cleanup
The previous commit 86e9c21 only caught the heartbeat icon color —
the main block of edits silently failed to match (comment block
broke the exact-string diff). This commit lands the full cleanup
that commit 86e9c21 claimed:

- Drop the rounded-t [4px bg-primary | 2px bg-border] rank bar.
- Drop the isRunning border-[color:var(--primary)] override and the
  success-tinted box-shadow glow.
- Switch hover from shadow-lg + translate-y to hover:bg-muted/30.
- Switch active/running avatar circle from bg-success-muted /
  text-success to bg-accent / text-primary.
- Move avatar initials from font-bold to font-semibold.
- Drop the isRoot / stale rank-bar comment block.

Error and pending states keep their destructive borders.

Typecheck and build:verify clean.
2026-04-21 14:38:53 -04:00
ZacharyZhang-NY 86e9c215f1 refactor(design): strip color bars from org chart cards
Remove the ink-blue top rank bar, running-state border override, and
green glow shadow from org chart cards. The tree layout already
communicates rank by position, and a dashed ink-blue connection line
plus the bottom-right status dot + ping animation already mark
running agents — duplicating the signal through a card-wide color
band and a cyan/green shadow was pure decoration.

- Drop the rounded-t [4px bg-primary | 2px bg-border] top bar entirely.
- Running state stops overriding border to var(--primary); all running
  cards fall back to the neutral border-border like everyone else.
- Running state stops emitting a success-tinted glow (shadow-[0_0_12px
  color-mix(... var(--success) 15% ...)]) — kami rule 8 bans drop
  shadows, and the tint introduced an unauthorized green.
- Hover switches from shadow-lg + translate-y-0.5 to a subtle
  hover:bg-muted/30 tint.
- Active/running avatar circle switches from bg-success-muted
  text-success to bg-accent text-primary (kami's ink-blue tint),
  removing the last green chrome on the page.
- Heartbeat icon switches from text-success to text-primary.
- Avatar initials move from font-bold (700) to font-semibold (600).

Error / pending_approval keep their destructive border (red), since
kami reserves the warm terra red for genuine error/destructive state
per design.md color system.

Typecheck and build:verify clean.
2026-04-21 14:38:00 -04:00
ZacharyZhang-NY a5caecbfda refactor(design): remove multi-hue color bars, unify to ink blue
The kanban board, performance metric cards, workspace list, and wait
banner all leaked second and third chromatic hues into the UI: red
bars on critical tasks, amber on in-review columns, green on done /
running / selected workspace rows, colored icon tiles and colored
headline values on metric cards. kami rule 2 allows one accent (ink
blue) at no more than 5% of the surface; these surfaces were spending
30-60%.

KanbanBoard.tsx
  - Drop the tone/dotColor fields from KANBAN_COLUMNS; column headers
    are plain eyebrows, no colored status dot.
  - Delete priorityColors map and border-l-[3px] on cards; cards are
    flat bordered rectangles. Priority order still drives the sort,
    but stops painting the chrome.
  - CRITICAL/HIGH small-caps label routes through text-primary (ink
    blue) instead of text-destructive / text-warning.
  - "Running" status dot + text switches from text-success / bg-success
    to text-primary / bg-primary.
  - Hover changes from hover:shadow-sm (banned by kami rule 8) to
    hover:bg-muted/40.

MetricsGrid.tsx + Dashboard.tsx
  - Drop the tone prop and its toneMap / bgMap / borderMap trio. A
    MetricCard renders one way: ivory card, ink-blue-tinted icon tile
    (bg-accent), ink-blue glyph, near-black value. No left border
    color stripe, no hover shadow, no translate-y.
  - Dashboard.tsx stops passing tone on the four performance cards.
    Semantics that used to live in tone (pending approvals warn, all
    agents running success) are intentionally dropped; those
    affordances can come back through typography or a subtle indicator
    when kami allows, not through a second color.

WorkspaceList.tsx / WorkspaceInspector.tsx
  - Replace every border-l / text / group-hover reference to var(--success)
    with var(--primary). Selected + hover states now carry kami's ink
    blue signal; the three "X count" spans that used text-success as
    a decorative pop become text-primary for the same reason.

WaitStateIndicator.tsx
  - The wait banner (wait-for-reply / approval) flips from warning
    amber (border-warning, bg-warning-muted, text-warning, bg-warning
    button) to primary ink blue across border / bg / text / button.
    The banner still reads as an attention signal — the icon shape
    (Hourglass) carries the semantic, color no longer has to shout.

feedback.tsx (Alert) and Toast.tsx retain their tone-based colors:
they are accessibility-critical transient state surfaces where a
single ink-blue lane would collapse success / warn / danger into an
undifferentiated stack. They are out of scope for this pass.

Typecheck and build:verify clean. Grep confirms no remaining
border-l-[color:var(--success|warning|destructive|caution)] in
dashboard or execution modules.
2026-04-21 14:34:36 -04:00
ZacharyZhang-NY 86ca568b90 refactor(inbox): kami literary rewrite — drop tiles, cards, red stripe
The Inbox rendered every row as a heavy card: a 36x36 solid-fill icon
tile in ink-blue / destructive / warm-silver, a rounded border, a 3pt
red left stripe on urgent items, and a hover that fired a drop shadow
plus translate-y. Six loud signals, all fighting for the reader, all
breaking kami rules (no pure-hue tiles, no red accents outside
destructive buttons, no hard drop shadows, no unnecessary chrome).

Per Jony + Jobs consensus the surface collapses to one quiet canvas:

  - 36x36 color tile  -> removed. Icon is an 18px inline glyph, single
    ink-blue stroke for every type. Type meaning lives in the glyph
    shape (ShieldCheck / XCircle / Eye / ChatCircle / ...), not in
    background color.
  - 3pt red severity stripe -> removed. Urgency compresses to one
    signal: a 5px ink-blue dot before the timestamp, visible only for
    critical/high rows. Title also shifts from font-medium to
    font-semibold at the same threshold so the row carries a little
    more weight without shouting.
  - Card chrome (border, rounded, bg-card) -> removed. Rows sit flat
    on parchment, separated by a single border-b at --border/60
    hairline. Reads like a printed contents page instead of a trello
    board of cards.
  - Hover shadow-md + -translate-y-px -> removed (kami rule 8 bans
    hard drop shadows). Hover tints the row with bg-muted/40, which
    is the kami whisper-shadow equivalent for a list item.

AttentionRow gains a variant prop ("card" | "line", default "card")
so Dashboard's three existing call-sites keep their card rendering
untouched. The "line" branch rejects iconTileBg / rowBgClass /
borderAccentClass overrides — the two variants are orthogonal, not a
half-mixed code path.

inbox-helpers.tsx sheds every token that became dead after the
rewrite: typeConfig.color (constant var(--primary) for every type
after Jony's unification), severityColors, severityBorderClass, and
the unused bg field. Inbox routes icon color through tone="info"
instead of passing the redundant iconColor per row.

Note: the page shows 6 duplicate "Escalation from Maya Rodriguez"
rows and 5 duplicate "Escalation from Taylor Park" rows. That is a
backend dedup bug (same entity + same severity pushed multiple
times), not a visual issue. Flag for a dedicated follow-up; do not
paper over it in the renderer.

Reviewed by Karpathy against /karpathy-guidelines:
  - Surgical: pass
  - No overcomplication: pass
  - Variants orthogonal: pass
  - Orphans cleared: pass
  - API stability for Dashboard callers: pass
  - request_changes item (typeConfig.color is a constant dressed as
    data) addressed in this commit by dropping the field and routing
    through tone="info".

Typecheck and build:verify clean.
2026-04-21 14:25:26 -04:00
ZacharyZhang-NY f9b505569c fix(design): default badge tone becomes ink blue, readable in light mode
The previous default tone (bg-muted text-muted-foreground) reads as
beige-on-beige in light mode — the "3" count on Work was barely
legible against the parchment sidebar.

Route default counts through bg-primary + text-primary-foreground so
the pill adopts kami's sole accent color. The three tones now fall
into a clean priority scale:

  default -> ink blue        (you have items)
  warn    -> warm amber      (needs attention)
  danger  -> warm terra red  (critical)

Contrast holds in both modes: ink-on-parchment in light (~9:1),
ink-light-on-dark-parchment in dark (~5:1). Warm amber and terra red
retain their own semantic foregrounds from the prior commit.

Typecheck and build:verify clean.
2026-04-21 14:12:49 -04:00
ZacharyZhang-NY dc6744bf71 fix(design): make sidebar badges readable in dark mode
Badge text color was hard-coded to text-primary-foreground for every
tone, which renders as parchment light. Pairing light text with the
amber warning background (L=0.82) or the warm-silver muted background
(L=0.77) produced light-on-light collisions — the "9" on the active
Messages row and the "4" count on Work were nearly unreadable.

Route each tone through its own semantic foreground token:

  danger  -> bg-destructive text-destructive-foreground
  warn    -> bg-warning     text-warning-foreground    (dark text on amber)
  default -> bg-muted        text-muted-foreground

Also pull .dark --muted and --secondary off the --card lightness
(0.296 -> 0.360) so bg-muted is actually visible against the sidebar
card surface. This fixes not just the count pill but every hover/muted
fill across the app (toggle rest state, subtle button backgrounds, etc)
that previously vanished into the card.

Typecheck and build:verify clean.
2026-04-21 14:09:44 -04:00
ZacharyZhang-NY 72851ebea3 fix(design): unify messages canvas, keep only app nav elevated
On the Messages page three surfaces collided: the channel list column
and the channel header bar both used bg-card (lighter surface), while
the content area above and below used bg-background (deep). That made
the page read as a sandwich of alternating tones.

Route ChannelSidebar and ChannelHeader through bg-background so the
entire Messages canvas — title bar, channel list, header bar, and
conversation pane — shares the deep kami surface. The left app
SidebarView continues to use bg-card as the single elevated island,
preserving the apple-style "one navigation column floats on the
canvas" hierarchy.

Borders (border-r / border-b on those two panels) already provide the
structural separation, so no shadow is needed — consistent with kami's
rule 8 (ring or whisper shadow only).

Typecheck and build:verify clean.
2026-04-21 13:53:30 -04:00
ZacharyZhang-NY 38a6b82d13 fix(design): warm the dark mode so parchment olive actually reads
The previous dark palette set chroma near zero (C=0.003) on hue 95, which
is technically "warm" but visually indistinguishable from neutral black
at low luminance. Screens rendered the surface as pure black, losing the
"暖橄榄底色" kami promises.

Raise chroma to 0.013-0.014 and shift hue from 95 (cool yellow) toward
80 (closer to olive/gold) so the warmth is perceivable. Lift the
background L from 0.156 to 0.172 so it sits one step off true black.
Separate card (0.296) from border (0.340) so elevation reads without
a hard drop shadow.

Specifically:
  --kami-deep-dark/--kami-near-black  0.156 C0.003 H95 -> 0.172 C0.013 H80
  --kami-dark-surface                 0.283 C0.003 H95 -> 0.296 C0.014 H80
  --kami-dark-warm                    0.336 C0.004 H95 -> 0.350 C0.014 H80
  --kami-border-dark                  0.283 C0.003 H95 -> 0.340 C0.014 H80
  --kami-warm-silver                  0.739 C0.010 H95 -> 0.770 C0.015 H85

Dark surface / border / text tokens flow through the same shifts:
  .dark --background / --sidebar       0.172 warm
  .dark --card / --popover / --secondary / --muted / --sidebar-accent  0.296 warm
  .dark --border / --input / --sidebar-border  0.340 warm (visible)
  .dark --muted-foreground / --secondary-foreground / --sidebar-foreground
                                     0.770 warm (readable timestamps/role labels)
  .dark --accent                       0.320 warm ink hint (selection glows ink)

Light mode --foreground / --card-foreground / --popover-foreground /
--warning-foreground inherit the new warmer near-black so body text on
parchment also carries the olive signature.

Typecheck and build:verify clean.
2026-04-21 13:48:33 -04:00
ZacharyZhang-NY 768fd34e98 feat(design): apply kami serif 500 to app headings
Extend the @layer base h1/h2/h3 rule so every application-level heading
inherits the kami serif stack at weight 500, matching design.md rule 4
(serif carries headline authority) and rule 5 (single serif weight is
the design signature). Prose headings inside .paperclip-markdown already
inherit the same stack via the prose rules added in the token rewrite.

Components that override font-family/font-weight on headings will
continue to win via CSS specificity; the base rule sets the kami default
for every heading that does not opt out.

Typecheck and build:verify clean.
2026-04-21 13:39:36 -04:00
ZacharyZhang-NY 95c4b0ae48 refactor(design): migrate hardcoded colors to kami tokens
Purge remaining hardcoded color values from the component layer and main
process so every surface flows through the kami token system.

src/main/desktop-shell-window.ts
  - BrowserWindow.backgroundColor no longer paints pure white before the
    renderer mounts. It now picks kami parchment (#F5F4ED) or deep-dark
    (#141413) based on nativeTheme.shouldUseDarkColors so the startup
    flash respects the user's OS theme preference.

src/shared/constants.ts
  - DEPARTMENT_COLORS collapses 12 unrelated hex brand colors (violet,
    red, green, cyan, pink, ...) into six kami tokens: var(--primary),
    var(--kami-ink), var(--kami-dark-warm), var(--kami-charcoal),
    var(--kami-olive), var(--kami-stone). Departments are distinguished
    by warm-neutral ramp + ink-blue, never by second chromatic hue.

src/renderer/components/communication/{MessageItem,SearchResults}.tsx
  - Replace the string-concat tint pattern `${color}18` with
    color-mix(in oklab, ${color}, transparent 91%). The old pattern
    produced invalid CSS (e.g. `var(--primary)18`) whenever `color`
    was a CSS custom property, silently falling back to no background.
    color-mix works for both hex and var() inputs, eliminating the
    latent bug at the source.

src/renderer/components/ui/ActionButton.tsx
  - Replace hand-rolled rgba(74,93,122,0.35) and rgba(220,53,69,0.3)
    drop shadows with kami ring shadows routed through color-mix over
    var(--primary) and var(--destructive).

src/renderer/views/CommandPaletteView.tsx
  - Replace rgba(15,23,42,0.08) cold-slate shadow with a kami whisper
    shadow driven by color-mix over var(--foreground).

src/renderer/components/skills/SkillAgentToggles.tsx
src/renderer/components/execution/ModelManagementShared.tsx
  - Toggle thumbs switch from bg-white to bg-background so they
    inherit parchment in light mode and deep-dark in dark mode,
    removing the last pure-white surfaces from the renderer.

Third-party brand hex values in src/renderer/components/social/
social-config.ts are retained: they represent external brand identity
(Twitter blue, YouTube red, ...), not kami chrome, and collapsing them
to one hue would destroy recognition.

Typecheck clean. No business-logic signatures changed.
2026-04-21 13:38:06 -04:00
ZacharyZhang-NY 5113abacc7 feat(design): adopt kami warm-parchment + ink-blue token system
Rewrite styles.css token layer to enforce the kami design system across
light and dark modes:

- Replace grayscale oklch(L 0 0) palette with warm-parchment hue 95
  neutrals and ink-blue hue 258/255 brand; zero cold blue-gray remains.
- Introduce --kami-* source-of-truth layer (parchment/ivory/warm-sand,
  deep-dark/dark-surface, ink/ink-light, warm neutrals, borders, rings,
  ink-blue tag tints) so future components reference semantic names.
- Keep shadcn aliases (--background/--primary/--card/...) so consumer
  components require no className changes; kami is a drop-in under the
  token layer.
- Reset radius-lg/xl from 0 to 0.5rem/0.75rem (kami 8pt/12pt); default
  --radius 0 -> 0.5rem.
- Reset font stacks: serif -> Newsreader + Source Han Serif SC + fallbacks
  for headlines/body; sans -> Inter + system + Source Han Sans for UI;
  mono -> JetBrains Mono + Maple Mono + ui-monospace for code. Maple Mono
  no longer occupies the sans-primary slot.
- Collapse chart-1..5 to a single ink-blue hue (258->252) with L ramp
  per Jobs ruling; dark mode inverts the L order for contrast.
- Desaturate success/warning/caution to warm hues (145/75/50);
  destructive retains warm terra red #B53333 (oklch(0.516 0.186 25)).
- Replace MDXEditor Catppuccin palette (#1e1e2e/#cdd6f4/#181825/
  #585b70/#313244/#45475a/#89b4fa) with kami dark-surface + parchment
  + olive + ink-light equivalents.
- Route markdown link colors through var(--primary) via color-mix
  instead of hardcoded #0969da/#58a6ff.
- Enforce serif 500 (not 700) on .paperclip-markdown h1-h4 per kami
  rule 5 (single serif weight is the design signature).

CSP font-src is self/data only, so no CDN fonts are introduced; the
stacks rely on system-installed fonts with documented fallbacks.

Self-checks pass: no remaining oklch(L 0 0) grayscale, no Catppuccin or
GitHub link literals, no font-weight 700 on prose headings, no radius: 0
in @theme, Maple Mono only lives in the mono fallback chain.
2026-04-21 13:32:40 -04:00
ZacharyZhang-NY 16d4de02c6 update 2026-04-21 13:09:45 -04:00
ZacharyZhang-NY 97033dfabd update 2026-04-21 12:44:33 -04:00
ZacharyZhang-NY 740d0812ee fix(build): restore package.json if electron-builder leaves it mutated
electron-builder's `extraMetadata` feature mutates the source
package.json in place during packaging and restores it on clean
exit. When the builder is killed mid-flight (parent task timeout,
Ctrl-C, OOM) the restore never fires and the source tree is left
with a stripped scripts block — every subsequent pnpm command
then fails with "Missing script" until someone notices the drift
and runs `git checkout`. Observed once in this session when a
`build:dir` task was cancelled mid-packaging.

Wrap the builder invocation in a bytes-level snapshot + idempotent
restore, driven by both normal-exit and SIGINT/SIGTERM/SIGHUP
handlers. On a clean run the builder's own restore wrote the
original bytes back, our final compare is byte-equal, and the
restore is a no-op. On an abnormal termination the snapshot
overwrites whatever electron-builder left behind so the working
tree is guaranteed clean regardless of exit path.

The snapshot approach is intentional over a "reject if tree dirty
before build" guard: this is a recovery mechanism, not a
precondition, and the repo's own `package.json` is the truth —
anything else in there at the moment the builder took its snapshot
is the desired state.
2026-04-21 01:29:50 -04:00
ZacharyZhang-NY f60ba5fa29 refactor(release): drop dead boss snapshot members
`scripts/release-boss.mjs` listed five files under
`bossSnapshotIncludes`. Only `build-boss-edition.mjs` is live —
invoked by both `release-boss.mjs:178` (local mac) and
`.github/workflows/remote-boss-platforms.yml:44` (remote Win).

The other four were leftovers from a previous packaging iteration:

  - `build-boss-mac.mjs` — old mac patcher keyed on `CompanyOnboarding`
    capital-case paths that no longer exist after the company-onboarding
    rename.
  - `build-boss.mjs` — earlier "full edition" builder referencing
    ProvidersStepShared.tsx / AgentCreator.tsx, both deleted by the
    pi-mono catalog rewrite.
  - `build-boss.sh` — thin wrapper that only called
    `build-boss-mac.mjs`.
  - `build-boss-desktop.mjs` — shipped to every snapshot branch but
    never invoked anywhere.

Carrying dead code in the snapshot manifest makes each Boss release
rsync ~1 k LOC of patches that can never run and, more subtly,
tempts a future reader to keep them in sync with the live source.
Removing them here and deleting the files themselves (they live in
gitignored `boss-build/`, not in tree) leaves exactly one live
builder and one snapshot member per real purpose.

No functional change to the live release path. Local verified: both
`pnpm build:dir` (normal AgentCompany.app) and
`node boss-build/build-boss-edition.mjs --platform=mac --version=0.4.167`
(Boss arm64 + x64 DMG + zip + blockmap) produce complete artifacts
with a clean source tree afterwards.
2026-04-21 01:07:46 -04:00
ZacharyZhang-NY 3353e46067 Backfill existing workspace files into work_products on first boot after observationPath fix
The 1f2f977 hotfix repairs the projector for new runs, but files that
already exist on disk before the fix lands stay invisible to the
DocumentCenter — a baseline+diff projector reports "changed" only
when a file's mtime advances past the run-start baseline, and a
quiescent file written before the fix never advances.

This commit adds a bootstrap-time one-shot rescan:

- New module `bootstrap/backfill-workspace-artifacts.ts` walks the
  primary/oldest workspace of every company exactly once (gated by
  `artifact_rescan_v1_done` in the settings table), applies the same
  registrability filter as `artifact-projector.ts` (skip .git/,
  node_modules/, .DS_Store, .lock/.log/.map; ignore package-lock.json
  / pnpm-lock.yaml / yarn.lock; cap at 5 000 files per workspace),
  and upserts a `work_products` row via `findWorkProductByExternalId`
  → `createWorkProduct` for any file the projector never registered.
- bootstrap-application.ts wires the call after recoverScheduledPosts
  (DB ready, services running, before the first heartbeat tick), so
  the rescan completes in the same boot tick that the user opens
  the DocumentCenter.

Idempotency: subsequent boots short-circuit on the settings flag.
The post-fix projector handles all future file activity inside
each run, so the backfill never needs to run twice. Per-workspace
file cap prevents a pathological tree from locking the bootstrap
path; overflow files are still picked up by the next run that
touches them. No fallback, no mock — files that fail stat are
silently skipped (same policy as the projector).

typecheck green, 543/543 unit tests, 10/10 eval. The user's 19
existing markdown deliverables under ~/Documents/Github/test/
should appear in the DocumentCenter on the next `pnpm dev`.
2026-04-20 16:25:48 -04:00
ZacharyZhang-NY 1f2f9770a6 Hotfix: separate workspace observation from lock claim — restore artifact projector for cognitive runs
Production regression of T1 (7829acc..15e3863). User reports "明明生成
了很多文件,但只有一个" — the filesystem shows 19 markdown deliverables
in ~/Documents/Github/test/{business-plan,operations,ceo-coordination}/
but the DocumentCenter surfaces only one row.

Root cause is structural, predicted in spirit by Karpathy's Round 1
take ("把'认知'和'执行'两件事一起锁是数据结构错"). The T1 rewrite
collapsed two concerns into one nullable field on the run context:

  workspacePath = workspace?.localPath ?? null
                  ^^^^^^^^^                ^^^^
                  lock target              observation root

For lockMode='none' (every cognitive C-suite agent post-T1) the
resolver returns workspace=null, so workspacePath was null, so
artifact-projector.ts:242 short-circuited every projection with
`{ kind: "skipped", reason: "no_workspace" }`. The agents kept
writing files via bash (cwd falls back to the company default
workspace at worker/runtime/index.ts:142), but nothing observed
them — the DocumentCenter only saw the one file that was projected
back when the agent still held an exclusive workspace.

Fix: split the two concerns. WorkspaceResolution gains a non-lock
`observationPath` field; the resolver populates it from the company
primary workspace (new `getCompanyObservationWorkspace` query —
primary first, oldest second, null only when company has zero
workspace rows) for lockMode='none' runs, and from `workspace.localPath`
itself for lockMode='exclusive' runs. RunDispatchParams threads the
field through; turn-context's `workspacePath` reads it first.
artifact-projector.ts is unchanged — it just sees a non-null path
again and resumes baselining, diffing, and upserting work_products
rows the way it did pre-T1.

Three new unit tests pin the regression: cognitive role with
workspace ⇒ observationPath set; cognitive role with no workspace ⇒
observationPath null; exclusive ⇒ observationPath equals
workspace.localPath. typecheck green, 543/543 unit tests, 10/10
eval. No fallback, no mock, no silent degradation.
2026-04-20 16:22:40 -04:00
ZacharyZhang-NY e15bf67c9f Workspace concurrency review iteration: Jobs's 3 taste asks
Closes the three specific_asks from Jobs's T1 review of the workspace
architecture fix (7829acc..15e3863):

1. docs/architecture/workspace-concurrency.md: decision table
   upgraded from a code block to a real Markdown table so it reads
   consistently with the failure-modes table lower in the file.

2. docs/architecture/workspace-concurrency.md + resolve-workspace.ts:
   added "Sunset coding-role inference" section and a TODO marker on
   CODING_ROLE_PATTERN tying the regex to the v52 transition window
   (target 2026-05-20). Both documents now name the end-state
   explicitly so a future engineer knows why the regex exists and
   when it dies.

3. resolve-workspace.ts: enriched the WorkspaceConfigurationError
   message to include taskId / agentId / projectId alongside the
   existing companyId, so a misconfigured setup points operators at
   the offending row instead of just the company.

No behaviour change, no fallback, no mock. typecheck green, 540 unit
tests green, 10 eval tests green.
2026-04-20 15:40:46 -04:00
ZacharyZhang-NY 15e3863cba saveTask: accept requires_filesystem; opt in for the onboarding kickoff task
- saveTask now takes an optional requiresFilesystem boolean. Omitted
  → column keeps its current value on updates, defaults to 0 on
  inserts. Explicit true/false → written through.
- Onboarding kickoff (the CEO's very first task) sets
  requiresFilesystem=true. The task description already tells the
  agent to list directories and read README/package.json — that is
  filesystem work, so the task must hold the workspace exclusive.
- Other saveTask call sites (automation reassign, routes-tasks patch,
  create_task, meetings) stay implicit — update paths preserve the
  existing column value, new user-created tasks default to 0 (safe
  cognitive default) and can be opted in later by the creator.
2026-04-20 15:36:08 -04:00
ZacharyZhang-NY c3dd08ec65 Document workspace concurrency model and per-task lock policy
New doc (docs/architecture/workspace-concurrency.md) explains:
  - why lockMode='none' is the default (cognitive tasks run in
    parallel with no lock)
  - what tasks.requires_filesystem means and how v52 backfills it
  - the coding-role inference safety net during the v52 transition
  - the per-task decision table the resolver implements
  - why company_fallback was removed and what replaces it
  - the type-enforced invariants on the resolution pair
  - failure modes and how heartbeat/task-runner recover

Also adds /docs/architecture/*.md to the .gitignore allowlist so the
docs directory is tracked the same way /docs/*.md and
/docs/proposals/*.md already are.
2026-04-20 15:34:23 -04:00
ZacharyZhang-NY 2dd62e5338 Adapt heartbeat/task-runner/turn-context to lockMode=none first-class path
- heartbeat.ts and task-runner.ts now share a single ResolveWorkspaceFn
  signature exported from run-dispatch.ts. Callers handle
  WorkspaceConfigurationError explicitly:
    * heartbeat: release the task lease and skip with new
      workspace_unresolved reason (task re-enters pool next heartbeat)
    * task-runner: release the lease and return WORKSPACE_UNRESOLVED
      to the caller
  No silent fallback to a random shared workspace.
- crash-recovery.ts imports WorkspaceConfigurationError for clean
  catch-branch attribution; the outer try already rolls back the
  queued run on any resolve failure.
- run-dispatch.ts exposes ResolveWorkspaceFn so downstream modules
  type their injected resolver against the same shape (single source
  of truth).
- HeartbeatSkipReason gains workspace_unresolved to keep the closed
  enum honest about all heartbeat exit paths.
2026-04-20 15:32:55 -04:00
ZacharyZhang-NY 28cdf7c56f Rewrite resolveWorkspace to per-task lockMode inference; drop company_fallback silent share (B4-adjacent)
Old resolver: task → agent → project → any company workspace, all
marked exclusive. That fourth step folded every runnable agent in a
multi-agent company onto a single workspace row and serialised the
C-suite (four agents, one exclusive lock, three starved).

New resolver: lockMode='exclusive' is now an opt-in decision inferred
per task. Three rules:

  1. task.workspaceId set → exclusive on that workspace (explicit).
  2. filesystem signal (task.requiresFilesystem OR agent in a
     coding role/engineering department) → exclusive on
     agent.workspaceId / project primary; throws if neither exists.
  3. otherwise → none / null. Pure cognitive work runs with no
     workspace lock and fully in parallel.

Removed:
  - company_fallback silent-share path. Filesystem-touching runs
    with no legitimate binding now throw WorkspaceConfigurationError
    at resolve time so the caller decides recovery rather than the
    resolver picking a random shared workspace.
  - workspacesMod.getAnyCompanyWorkspace (now dead code).

Invariants now enforced by types:
  - lockMode='exclusive' ⇒ workspace is a live WorkspaceRecord.
  - lockMode='none'      ⇒ workspace is null.

Tests updated to cover the new decision table and the four-non-
coding-agents parallel case that was the original bug.
2026-04-20 15:32:01 -04:00
ZacharyZhang-NY 7829acc7f0 Add tasks.requires_filesystem column (v52) — per-task filesystem lock policy
Before v52, resolveWorkspaceWithLockMode walked a four-step fallback
chain (task → agent → project → any company workspace) and marked
every resolved row exclusive. In a multi-agent company every heartbeat
collapsed onto the same company workspace row, every run claimed the
same exclusive lock, and only one agent ever executed at a time.

Root cause is a missing column: per-task 'does this task touch the
filesystem?' had no place to live, so the orchestrator defaulted to
yes on everything. v52 gives that question its own column.

Backfill is conservative:
  - in-flight tasks (in_progress + active_run_id) → 1 (preserve
    the lease the dispatcher already holds)
  - todo/backlog tasks whose assignee is an engineering-flavoured
    role (CTO/engineer/developer/devops/sre or department =
    engineering) → 1
  - everything else → 0

TaskRecord now exposes requiresFilesystem on both entityCrud.getTask
and the snapshot read path.
2026-04-20 15:25:36 -04:00
ZacharyZhang-NY 3ff891c6ec C4 follow-up #2: re-record non-ceo-dm-reply post-C4 and close C4-followup proposal
Closes the second and final ask from the C4 cross-review (Karpathy
specific ask #1). The previous non-ceo-dm-reply recording (409bec2)
pre-dated C4 part 3/5 by ~18 minutes, so it could not discriminate
between "non-CEO path correctly does not receive hire_agent /
file_approval" and "the tools simply had not been injected yet."

Re-recorded against anthropic/claude-sonnet-4-5 on the current main.
The VP Product agent (manager — canRequestHire=true by keyword match,
but after F3 canFileCeoStrategy=false because reportsTo is not null
AND role is not CEO) produces:

- mark_read + /api/agent_message/send + m_77 preserved — 3 positive
  assertions intact.
- Zero hire_agent invocation (not asked to hire).
- Zero file_approval invocation — positive evidence the F3 split
  correctly excludes file_approval from non-CEO managers. Without
  F3 this call would have had file_approval in scope and a manager
  under pressure might have reached for it.

Fixture assertions updated to pin the two tool-scope invariants using
the new message_does_not_contain_substring kind from F2.

C4-followup.md marked CLOSED with resolution table mapping each of
the four items to its landing commit, plus the companion cleanup
(43337e5 — RpcMethod single-source-of-truth) that came out of the
same session.

Final: typecheck green, 537 unit tests, 10 eval tests.
2026-04-20 14:58:26 -04:00
ZacharyZhang-NY d2b6f91023 C4 follow-up #3: RFC 8594 Deprecation/Sunset headers + call counter on legacy hire routes 2026-04-20 14:56:34 -04:00
ZacharyZhang-NY 1fad88bad1 C4 follow-up #1: split canFileCeoStrategy from canRequestHire for file_approval tool scope
Old internal-tool-selector attached `file_approval` to any agent with
`reportsTo === null`, and attached both tools through the same
management-keyword predicate chain. That let a VP or director with
org-management authority walk away with `file_approval`, contradicting
the C4 commit narrative that scoped `approve_ceo_strategy` as CEO-only.

Introduce `canFileCeoStrategy(db, companyId, agentId)` as a dedicated
predicate requiring both a CEO-equivalent role/title AND
`reportsTo === null`. Using either half alone is too loose: role alone
lets a demoted CEO with a virtual superior still file strategy,
`reportsTo` alone lets a VP with no manager slip through. The two
conditions together pin the predicate to a genuine top-level CEO.

- `hire_agent` continues to gate on `canRequestHire` (managers hiring
  ICs is a legitimate flow and the original "CEO-only" framing in the
  C4 commit message was narrower than the production reality).
- `file_approval` now gates on `canFileCeoStrategy`, orthogonal to hire
  authority.
- New unit test covers 4 edges: genuine CEO, CEO title with virtual
  superior, VP without manager, and plain IC.
2026-04-20 14:56:11 -04:00
ZacharyZhang-NY 9a5823b242 C4 follow-up #4: add message_does_not_contain_substring assertion kind + pin C4 invariants
Closes the fourth ask from the C4 cross-review (docs/proposals/C4-followup.md
Item 4). The eval harness previously had no way to assert the absence of a
pattern in a trace — only positive `message_contains_substring`. That meant
the C4 "no more node -e / bash+fetch from CEO" invariant was only
demonstrated by the diff between two commits, not by any running assertion
that future regressions would trip.

Three changes:

1. Extend the Assertion union in tests/eval/types.ts with
   `message_does_not_contain_substring` (role + substring). Symmetric to
   the positive kind; fails on first match with a specific reason.

2. Add the case in assertion-judge.ts. Same traversal as the positive
   branch but inverted exit condition.

3. Add two harness self-tests covering pass + fail, so the new kind is
   exercised even when the fixtures directory is empty.

4. Pin two C4-regression assertions onto the recorded ceo-bootstrap-empty
   fixture: the assistant response must NOT contain "node -e" OR
   "/api/companies". Any future regression that reintroduces the
   HTTP-path-in-prompt pattern or the bash+node -e shell fallback will
   now fail pnpm test:eval instead of living in the fixture silently.

typecheck green, test:eval up from 8 → 10 tests (2 new self-tests), all
passing.
2026-04-20 14:53:24 -04:00
ZacharyZhang-NY 43337e535b C5 follow-up: derive RpcMethod from zod enum (single source of truth)
The C4→C5 drift bug (hotfix 12556de) was caused by the same RPC
method list being declared twice — once as a zod enum in
worker/entry/types.ts for runtime validation, and once as a TS
union type in runtime-bridge.ts for compile-time handler wiring.
The two drifted when C4 added `invokeInternalTool`: the TS union
grew, the handler switch added a case, but the zod enum was
forgotten, so the runtime gate rejected envelopes the handler had
already registered.

This commit collapses the two declarations into one:

- Extract `workerRpcMethodSchema = z.enum([...])` in
  worker/entry/types.ts as the canonical list.
- Export `WorkerRpcMethod = z.infer<typeof workerRpcMethodSchema>`.
- Replace the hand-written `RpcMethod` union in runtime-bridge.ts
  with `type RpcMethod = WorkerRpcMethod` plus an explicit import.
- Reuse the schema inside the `rpc-request` variant of
  `workerMessageSchema` so adding a method requires exactly one
  edit instead of three.
- Add an exhaustiveness `default: { const _exhaustive: never = ... }`
  guard to `handleRpc`'s switch. If the zod enum widens without a
  matching case, TypeScript fails the build at the `never`
  assignment — drift becomes a compile-time error, not a runtime
  ZodError fired at the user.

typecheck clean, 529 unit tests green, 8/8 eval green.
2026-04-20 14:52:08 -04:00
ZacharyZhang-NY 12556deb05 Hotfix C4: add invokeInternalTool to worker-message RPC method enum
Production bug — as soon as the CEO agent tries to call the hire_agent
or file_approval internal tool introduced by C4 (e2c839b..03864f3),
the main process spams:

  [error] [worker] invalid message payload ZodError: ...

with all seven discriminant branches failing. Every branch reports
'invalid_value' on 'type' because zod's discriminated-union validator
walks every variant when the discriminant does not match any
literal — which happens because the worker sent
`{ type: "rpc-request", method: "invokeInternalTool", ... }` and the
'rpc-request' branch's `method: z.enum([...])` only listed five
methods: persistMessage / prepareRun / beforeToolCall / afterToolCall
/ transformContext. 'invokeInternalTool' was missing.

Root cause: C4 added the RPC method on both sides of the fence —
worker-side caller (hire-agent-tool.ts:133, file-approval-tool.ts:115)
and main-side handler (runtime-bridge.ts:565, RpcMethod TS union at
line 77) — but forgot to register it in the zod validation schema
at worker/entry/types.ts that sits between them. The TS union type
would have caught it at compile time if the enum were the single
source of truth; right now the enum is duplicated as a zod literal
list + a TS union, and C5's compile-time hook contract only covers
pi's own hooks, not the RPC message envelope.

Fix: add "invokeInternalTool" to the zod enum. One line.

Follow-up proposal C5-followup: unify the two duplicated enum
definitions by either (a) deriving the TS union from the zod
schema via z.infer, or (b) making runtime-bridge.ts import the
enum values from worker/entry/types.ts so adding an RPC method
requires touching exactly one place. This will be documented in
docs/proposals/ once the hotfix lands and the app is known to
work end-to-end again. Scope for that cleanup is small (one file
edit + one type move) but out of scope for this hotfix because the
user is currently unable to run the CEO bootstrap.

typecheck green, 529 unit tests green, 8/8 eval green.
2026-04-20 14:49:33 -04:00
ZacharyZhang-NY b628b49016 Hotfix B2 Phase 1: drop task_leases.run_id FK (v51 migration)
Production bug on launch — user reports UI 'FOREIGN KEY constraint
failed' on 启动公司 and the main-process log loops forever with
'[heartbeat] CEO not ready: checkout_race_lost'. Both trace to the
same root cause introduced by v50 (e2c839b..2656684 B2 Phase 1):

  task_leases.run_id TEXT NOT NULL REFERENCES runs(id)

The orchestration sequence contradicts this FK. In both heartbeat.ts
(line 165) and task-runner.ts (line 91), the caller generates a fresh
runId = randomUUID() and immediately calls db.tasks.checkoutTask
BEFORE the corresponding row is inserted into the runs table. The
legacy tasks.checkout_run_id column has always been 'dangling
allowed' — the run row saves later when task-runner.ts opens the
run record. v50's FK tightened the shadow lease contract without
coordinating with that insertion sequence, so every checkoutTask
attempt now rolls back with a FK violation, takes the whole CAS
transaction with it, returns changes=0, and the heartbeat reports
checkout_race_lost. The task never advances — the exact orphan
symptom B2 was supposed to eliminate.

Fix: migration v51 recreates task_leases WITHOUT the run_id FK.

- task_id FK + ON DELETE CASCADE stays (a lease for a non-existent
  task is still meaningless)
- UNIQUE(task_id, run_id) stays (still a correctness constraint)
- run_id loses the FK — it mirrors the legacy checkout_run_id's
  loose semantics, which is exactly what Phase 1 dual-write is
  supposed to mirror
- Existing data preserved verbatim via INSERT SELECT
- Uses PRAGMA defer_foreign_keys=ON inside the transaction (the
  pragma is valid inside a txn; regular foreign_keys=OFF would not
  be since runMigrations already opened BEGIN IMMEDIATE)

Post-v51 the run_id column is still NOT NULL and the shadow probe
(ab4afba) will still surface missing runs as divergence — the FK
tightening is a Phase 2 concern coordinated with the saveRun
insertion order, not a Phase 1 shadow-write concern.

typecheck green, 529 unit tests green, 8/8 eval green.
2026-04-20 14:44:59 -04:00
ZacharyZhang-NY 17ffec7ea5 C4 follow-up: re-record manager fixture post-C4, strip bash leftover from SOP, document remaining asks as C4-followup proposal
Closes review asks from cross-review of C4:

- Jobs ask #2: team-building.en.md still referenced the bash+fetch
  pattern for goal creation. Rewritten as a deferred-tool note pointing
  to C5 follow-up, without re-teaching the HTTP shape C4 just removed.

- Karpathy ask #1 (partial): re-recorded manager-task-handoff against
  main to produce post-C4 positive evidence. VP Engineering has
  hire_agent available via canRequestHire, but when directed NOT to
  hire, the recorded trace shows task decomposition only (no
  hire_agent invocation). 455 in / 769 out tokens; assertions updated
  to pin /api/task/create + agent_ic_ slugs + p99 substring + max 3
  turns. The `non-ceo-dm-reply` re-record is deferred to the follow-up
  ticket.

- Karpathy asks #2, #3, #4 + Jobs asks #1, #3, #4: documented in
  docs/proposals/C4-followup.md with concrete completion criteria.
  Scope covers canFileCeoStrategy predicate, non-ceo-dm-reply
  re-record, RFC 8594 Deprecation/Sunset headers + counter, and a
  negative substring assertion kind for the eval harness.

Eval still green at 8/8. C4 main batch (e2c839b..8e99e01) stands
unchanged; this commit is pure follow-up groundwork.
2026-04-20 14:36:00 -04:00
ZacharyZhang-NY 8e99e0119f Re-record ceo-bootstrap-empty fixture post-C4 (tool-based, not bash/fetch)
This is the verification artefact for the C4 refactor (e2c839b through
03864f3). The old fixture (recorded at 1d0cfa2, scenario asked the model
to POST hire_agent requests via bash+node+fetch) captured the model
emitting `node -e 'fetch(\`http://...\`)'` — exactly the antipattern
Jobs called out.

Post-C4 scenario was updated to reflect the new world: the CEO now has
explicit hire_agent and file_approval tools. Re-recording against
anthropic/claude-sonnet-4-5 produced 509 in / 731 out tokens and the
assistant response:

  - Contains `hire_agent` (pseudo-XML tool invocations, one per hire)
  - Contains `file_approval` with type=approve_ceo_strategy
  - No `node -e` / bash+fetch / HTTP POST pattern anywhere
  - 3-5 hires as requested, single approval block

Assertions updated to pin the post-C4 tool names as positive signals.
Absence of bash/fetch is demonstrated by diff against 1d0cfa2 (see that
commit's recorded JSONL for the before state).

Eval harness now green at 8/8 (3 self-tests + 5 recorded fixtures) with
this new baseline. Any future regression that reverts CEO bootstrap to
HTTP-path prompts will fail all three hire_agent / approve_ceo_strategy /
file_approval assertions.
2026-04-20 14:31:36 -04:00
ZacharyZhang-NY 03864f3bd8 Align team-building SOP to tool-based flow; deprecate HTTP hire path (C4 part 5/5)
Rewrite `ceo-modes/team-building.en.md` to describe the `hire_agent`
and `file_approval` pi tools introduced in C4 parts 1-3, replacing the
pre-C4 Node.js `fetch` snippets that showed the CEO how to POST to
`/api/companies/:id/agents` and `/api/companies/:id/approvals`.

The SOP now:
- Lists `hire_agent` args as a table (name / role / connectorId /
  model + optionals) instead of a JSON body with hard-coded headers.
- Lists `file_approval` args the same way, pointing at
  `approve_ceo_strategy` as the canonical use case.
- Preserves the `STRATEGY_BEFORE_HIRES` / `STRATEGY_ALREADY_FILED`
  ordering gate, surfaced through the tool-layer error codes
  (`file_approval.strategy.before_hires` / `.already_filed`).
- Keeps the goal-creation fetch snippet because goal creation is not
  yet exposed as an internal tool; flagged with a "use `bash` for now"
  hint so the CEO does not conflate the two patterns.

HTTP deprecation:
- `POST /api/companies/:id/agents` carries `@deprecated since C4`
  JSDoc and emits `log.warn('[deprecated][C4] ...')` on every
  successful call so residual legacy callers (UI forms, automation
  tests, unmigrated scripts) are auditable in logs.
- `POST /api/companies/:id/approvals` with `type=approve_ceo_strategy`
  emits the same warn; other approval types still use the HTTP route
  and are not flagged (they have no tool equivalent yet).

Neither route is removed — existing clients keep working. Removal is
gated on tool-path eval coverage landing in a follow-up.

tests: pnpm typecheck + pnpm test:unit (529) + pnpm test:eval (8/8) green
2026-04-20 14:29:05 -04:00
ZacharyZhang-NY 003490e16b Downgrade initial-user-turn CEO hardcode to semantic cue (C4 part 4/5)
Replace the 4-line `bash + node -e + fetch POST /api/companies/:id/
agents` + `POST /api/companies/:id/approvals` imperative with two
sentences that point at the Team Building Phase SOP and the new
`hire_agent` / `file_approval` tools (registered on the CEO in part
3/5). The cue is now `"This wake: your team is empty." +
"File 3-5 hire_agent requests and 1 approve_ceo_strategy via your
assigned tools. Execute now, do not write a plan document."`

All five pre-C4 couplings removed from this turn:
- Tool name (`bash`) — gone; cue references the tool surface generically
- Implementation detail (`node -e '...'` + `fetch`) — gone
- API paths (`/api/companies/:id/agents` + `/approvals`) — gone
- Business numbers (3-5 hires + 1 strategy) stay, moved into the cue
- Imperative tone (`NOW / Do not`) — dropped in favour of "execute now"

The fail-through path on the CEO lookup used to be `} catch {}`
(silent swallow). Migrated to `logAppError` under a recoverable
classification so a stale agent/company read still logs a structured
line instead of vanishing. The fallback behaviour (generic timer turn)
is unchanged — pi agent construction must not crash on a prompt-
assembly blip.

This commit is the first one to change model-observable behaviour.
The ceo-bootstrap-empty eval fixture (recorded against the old cue)
is expected to drift to 4/5 until re-recorded; IC / manager / non-CEO
fixtures stay green because they do not hit this code path.

tests: pnpm typecheck + pnpm test:unit (529) + pnpm test:eval (8/8) green
2026-04-20 14:27:19 -04:00
ZacharyZhang-NY b839ce4f23 Inject hire_agent and file_approval into CEO agent (C4 part 3/5)
Wire the two internal tools from parts 1-2 end-to-end:

- `invokeInternalTool` RPC method added to RuntimeBridge; worker tool
  `execute` calls route here, handler dispatches by tool name via the
  new `agent-runtime/internal-tools/router.ts`.
- `InternalToolCallbacks` (`onApprovalCreated` / `onApprovalResolved`
  / `onDomainChanged`) are late-bound on the bridge via
  `setInternalToolCallbacks`; `wire-api-server` now cross-wires the
  same callbacks used by the HTTP approval route so thread integration
  / automation fire identically across both entry points.
- `RunJob.internalTools` (new field) carries the per-run tool list
  main decides at dispatch time via `orchestration/internal-tool-
  selector.ts`. Selection rule: `hire_agent` → any agent with
  `canRequestHire` authority; `file_approval` → CEOs only (scoped to
  the `approve_ceo_strategy` use case).
- Worker `createPiAgent` call site now assembles `codingTools +
  internalTools` before handing to pi. Exhaustiveness guard on the
  switch catches new tool names at compile time.

No prompt-level wiring yet — the `initial-user-turn` and
`team-building.en.md` updates ship in parts 4 and 5 so this commit
only adds the tool surface without changing the CEO's observable
behaviour (the existing HTTP path is still the one the prompt tells
the CEO to call).

tests: pnpm typecheck + pnpm test:unit (529) + pnpm test:eval (8/8) green
2026-04-20 14:25:44 -04:00
ZacharyZhang-NY d65f156732 Add internal file_approval tool (C4 part 2/5)
Introduce a first-class `file_approval` pi tool definition + main-side
handler, paired to `hire_agent` from part 1/5. Replaces the
`bash + node -e + fetch POST /api/companies/:id/approvals` chain with
a single pi tool-call the CEO uses to file `approve_ceo_strategy`
after the initial hires. Handler reuses `db.approvalsMod.requestApproval`,
the `approve_ceo_strategy` ordering gate (STRATEGY_BEFORE_HIRES /
STRATEGY_ALREADY_FILED), and the auto-approval policy so the tool path
produces identical approval rows to the HTTP route.

No runtime wiring yet — the injection + RPC router land in part 3/5.

Error taxonomy:
- file_approval.input.invalid / strategy.before_hires /
  strategy.already_filed → UserInputError
- file_approval.create.failed / activity.failed → UpstreamError

tests: pnpm typecheck + pnpm test:unit (529) + pnpm test:eval (8/8) green
2026-04-20 14:18:37 -04:00
ZacharyZhang-NY e2c839be49 Add internal hire_agent tool (C4 part 1/5)
Introduce a first-class `hire_agent` pi tool definition + main-side
handler so the CEO no longer has to route hires through `bash + node -e
+ fetch` against the internal HTTP API. The tool's `execute` method
proxies to main via a new `invokeInternalTool` RPC method (wiring lands
in part 3/5); the handler reuses the existing `createHireRequest` DB
primitive and auto-approval policy so the tool path and the legacy
HTTP path produce identical approval rows.

No runtime wiring yet — the tool is not injected into any agent's tool
set in this commit. That keeps the behavioural surface unchanged for
this step while giving part 3/5 a concrete handler to bind.

Error taxonomy:
- hire_agent.permission.denied / input.invalid / name.invalid /
  routing.* / connector.* / duplicate.* → UserInputError
- hire_agent.create.failed / activity.failed → UpstreamError

tests: pnpm typecheck + pnpm test:unit (529) + pnpm test:eval (8/8) green
2026-04-20 14:17:03 -04:00
ZacharyZhang-NY 409bec2b25 Record 3 new B5 fixtures: IC task exec, manager handoff, non-CEO DM
These are the role×trigger tripwires Karpathy required before C4 can
ship: covering IC / manager / non-CEO paths, not just the two CEO
fixtures from 1d0cfa2. Together they act as the cross-role regression
net — any C4 change that breaks hire_agent tool registration or
prompt shape across role tiers will now surface as an assertion
failure, not a silent production drift.

Fixtures recorded against anthropic/claude-sonnet-4-5 via the user's
Claude Max OAuth token (read from macOS keychain, not committed):

- ic-task-execute (364 in / 1425 out): IC receives task t_1138,
  expects task id + filename in the response and a mark_complete
  intent within 3 turns.
- manager-task-handoff (457 in / 1022 out): VP Engineering decomposes
  CEO p99 directive into IC-sized tasks; expects /api/task/create
  calls, references to agent_ic_* slugs, and the "p99" term.
- non-ceo-dm-reply (357 in / 545 out): VP Product handles a peer DM
  with blocking ETA ask; expects mark_read + /api/agent_message/send
  + message id preserved.

Total spend ~3.7k tokens; pnpm test:eval --run now green at 8/8
(3 harness self-tests + 5 recorded fixtures).

With these tripwires in place, C4 (hire_agent / file_approval tool
uplift + initial-user-turn rewrite) can proceed without the previous
"only CEO path has a baseline" blind spot.
2026-04-20 14:08:35 -04:00
ZacharyZhang-NY 1d0cfa29d2 Record first two real B5 eval fixtures (ceo-bootstrap-empty + ceo-board-message-reply)
Unblocks the march-of-nines third nine. Up until this commit `tests/eval/`
had a harness + self-tests but zero real traces; the fixture directory was
a documented stub. These two fixtures are genuine single-turn recordings
against anthropic/claude-sonnet-4-5 produced by `pnpm eval:record` — not
mock data, not placeholder — each one captures an actual API response
with its token ledger.

Coverage:
- ceo-bootstrap-empty: empty company, CEO bootstrap trigger. Asserts the
  model produces hire_agent POSTs, an approve_ceo_strategy POST, and uses
  bash+fetch (current prompt pattern before C4 lands).
- ceo-board-message-reply: operating CEO with a live team, inbound Board
  message. Asserts the model hits mark_read, posts to
  /api/agent_message/send, and keeps the original message_id in scope.

What these fixtures now enable:
- B2 Phase 2 switch-read: a fixture diff before/after the cutover
  demonstrates dual-write parity is real, not assumed.
- C4 initial-user-turn refactor: the current HTTP-path-in-prompt pattern
  is captured; after C4 lands, the diff shows whether tool-shape
  refactoring regressed behaviour.
- C7 prompt-builder conditional assembly: same, but for system-prompt
  slimming.
- M7 Phase 2 call-site switch: resolveCeoMode cutover can be regression-
  verified against both traces.

Scenarios live at tests/eval/scenarios/<id>/{system.txt,user.txt} so any
maintainer can re-record the same trace with one command and diff against
the committed fixture. Each fixture's assertions block currently contains
four assertions; pnpm test:eval passes with 5 (3 harness self-tests + 2
real-fixture runs).
2026-04-20 14:01:22 -04:00
ZacharyZhang-NY 720387b6ed B2 proposal: record Phase 2 entry criteria and trigger vs explicit dual-write trade-off
Append a "Phase 2 considerations" section capturing the two
unresolved architecture debates Linus and Jobs surfaced in T1
review:

- Linus: drop the status->phase TRIGGER in favour of explicit
  dual-write at every call site. Deferred to Phase 2 with explicit
  rationale (existing two-layer guard + 5-commit blast radius).
- Jobs: flip reads from legacy columns to phase / task_leases.
  Deferred until B5 eval harness can baseline agent behaviour.

Also records the four entry criteria for Phase 2 and the four gates
for Phase 3 drop-old-columns, so the next iteration has a concrete
checklist rather than a re-argument.
2026-04-20 13:52:51 -04:00
ZacharyZhang-NY 54a97f67ac B2 Phase 1 follow-up: plug lease orphan gap in advanceTaskStatus + scope interruptStaleRuns cleanup
Linus review T1 surfaced three real bugs in the B2 Phase 1 shadow
dual-write surface. Fix them in one pass.

1. advanceTaskStatus left task_leases behind on terminal (done /
   cancelled / blocked) and "return to queue" (todo / backlog)
   transitions. The status->phase trigger advanced tasks.phase but the
   lease row lingered as an orphan. dev-mode verifyPhaseConsistency
   could see the divergence; production silently drifted. Wrap the
   status UPDATE and an explicit DELETE FROM task_leases in a single
   transaction so no caller observes the intermediate state.

2. The no-restricted-syntax guard in eslint.config.mjs only matched
   literals shaped "UPDATE tasks SET status" -- advanceTaskStatus's
   dynamic `UPDATE tasks SET ${timestampSets.join(", ")}` slipped past,
   and so did saveTask / recoverStaleLocks (status not first column).
   Tighten the selectors to (a) match any status-write within UPDATE
   tasks regardless of column order, and (b) flag template literals
   whose head ends with `SET ` so dynamic helpers must carry an
   explicit eslint-disable with rationale. Five grandfathered sites
   now carry matching disables.

3. interruptStaleRuns scoped its task+lease cleanup with
   `WHERE finished_at = ?` against the freshly stamped timestamp --
   safe in isolation, vulnerable to ISO-millisecond ties with other
   already-interrupted runs. Capture the stale run ids before
   mutating anything and drive every downstream statement from that
   explicit id list. Original semantics preserved; scoping is exact.

Unit tests added in tests/unit/tasks-phase.test.ts cover the
advanceTaskStatus lease cleanup across done / cancelled / blocked /
todo, and pin the in_review case as "lease stays".
2026-04-20 13:51:53 -04:00
ZacharyZhang-NY ded707d960 Document C1 codemod recipe + C6 wave boundaries + N-scan TODO deadlines (T2 iteration)
Address T2 review asks from Karpathy (request_changes) + Jobs
(approve with minor asks) without touching published commits:

- scripts/codemod/README.md (new): records remove-appdatabase-passthrough.mjs
  usage, the completeness proof for METHOD_TO_MODULE (typecheck-clean +
  524 tests green at 118e3d8 = no orphaned call sites), and the sequential
  revert recipe for C1 (3 -> 2 -> 1, not independent because 118e3d8
  bundled vault simplification).

- CONTRIBUTING.md (new): pass-through ban + codemod usage + sequential
  revert recipe + file-size ceiling + C6 wave cap. Whitelisted in
  .gitignore alongside the existing doc exceptions.

- docs/proposals/C6.2-error-taxonomy-phase2.md: wave 2 scope boundary
  names renderer-adjacent / api-server / browser / automation / skills
  explicitly and excludes src/main/database/** + src/main/worker/runtime/**
  (B2 / M10 high-churn zones). Wave 2 and wave 3 each capped at 30
  catch sites so C6 cannot expand without bound.

- src/main/agent-runtime/artifact-projector.ts, runtime-bridge.ts:
  N-scan TODOs now carry a death date ("TODO(M-followup by 2026-05-20)").
  If the date passes without decomposition, a follow-up session MUST
  revisit or justify the exception.

Karpathy T2 asks #1 and #2 (split part 3 / "independent revert" language)
are addressed in CONTRIBUTING + codemod README as documentation, not
history rewrites, because 118e3d8 is already published.

Typecheck clean. No structural code changes; pure docs + comment edits.
2026-04-20 13:48:25 -04:00
ZacharyZhang-NY 69d03312e6 Cleanup residual dead code and stale annotations (N-scan residual)
- Drop the "pass-through remains for back-compat" note on
  AppDatabaseBase's domain modules; the pass-through layer is gone, so
  the comment was out of date. Replace with a pointer to the ESLint
  guard that blocks regression.

- Flag the two remaining >500-line files (`agent-runtime/runtime-bridge.ts`
  648 LOC, `agent-runtime/artifact-projector.ts` 637 LOC) with an
  inline `TODO: decompose — M-followup` note. No structural change;
  the decomposition is tracked for a later milestone to keep this pass
  scope-safe.
2026-04-20 13:39:56 -04:00
ZacharyZhang-NY 827f06f358 Migrate 26 high-value catch sites to AppError taxonomy (C6 wave 1)
Classify scheduler, orchestration, IPC read, and automation catch
blocks via logAppError + classifyUnknownError so each failure surfaces
a stable `module.subdomain.condition` code plus a kind. No behaviour
change — returns, throws, and fall-through are preserved; only log
prefixes and the taxonomy metadata are new.

Wave 1 coverage (26 sites, all non-database):

  - orchestration/scheduler-lock-recovery (3)
  - orchestration/scheduler-housekeeping (5)
  - orchestration/scheduler-idle-automation (2)
  - orchestration/scheduler-heartbeat (4)
  - orchestration/turn-context (2)
  - ipc-core-read-handlers (6)
  - automation/automation-handlers (4)

Relax the Logger interface so `error` is optional, letting callers
whose deps expose only `{info, warn}` (scheduler contexts) pass in
directly without wrapping. The helper falls back to warn when error
is absent.
2026-04-20 13:37:40 -04:00