diff --git a/CHANGELOG.md b/CHANGELOG.md index 64facd459..e50cfca69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ All notable changes to this project are documented here. The format is based on Don't Be Michael keeps its own version line, starting at 0.0.1. +## [0.4.3] (2026-11-20) + +### Added +- **Run two separate businesses on one computer.** Each business keeps its own settings, saved passwords and keys, files, history and, if you choose, its own Claude account. The business name in the top bar switches between them, and Settings, General lists every business with Open, Find it for a folder that moved, and Remove for a setup never finished. A switch closes the open office properly first. Everyone finishes or hands off their step, then the other business opens. +- **Add a business while the open one keeps working.** Setup opens over the office, and the new business's folder is named after it. Back to the office keeps what you typed, and you go on from that step later. +- **Back up everything and restore it on a new computer.** One file holds every business: the team, memory, tasks, history, knowledge, settings and the team's folders. Saved passwords and keys are locked with a backup password. Restore from Settings, General, or from the first setup screen on a new computer. +- **Always allowed, for the privacy check.** In Settings, Research and privacy, list your business's own public names and links, and the check keeps them in questions to Research. When the check keeps words back, an Ask me card offers to always allow each one and ask again. +- Address suggestions as you type the street; business hours set day by day; languages served and currency picked from a list; one field per social link, with the site named. +- Ask me cards show three questions at a time. +- Add a mailbox starts on the email you gave in setup. + +### Changed +- Team setup shows the members side by side, four across, and asks for one office folder instead of one per member. +- New office folders are named with no spaces or special characters. + +### Fixed +- A question to Pete waits while he starts, instead of saying he is turned off. +- Closing time tells Michael once everyone has confirmed and reminds him, and Michael files only the messages he read, so closing no longer hangs. +- A member link opens the tab it names. +- Business hours you never set show as not set, never as an unsaved 9 to 5. +- A business you just added opens after setup, instead of saying the office can't be found. +- Ask me can be read while the office opens or closes. +- A list's save button says all for now, not the whole list, and a retired foundations question is never asked again. + ## [0.4.2] (2026-11-17) ### Added diff --git a/README.md b/README.md index 5fc7f7fd7..3d9353874 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,8 @@ runs on your computer. > brings you only the calls that need you. > [!TIP] -> **New in 0.4.2: team members attach files from their folder to an email.** On Send on approval -> the card lists each file, to open or take off before you approve. +> **New in 0.4.3: run two separate businesses on one computer.** Each keeps its own settings, +> passwords and files, and the business name in the top bar switches between them. ## Contents @@ -272,6 +272,8 @@ and signs you in where you can see it, or takes an Anthropic API key instead. **Also** - **Updates.** A new version downloads in the background and arrives as a card from Michael on Needs you, with Later and Restart to update (or Download, for an install that can't update itself). Nothing restarts until you click. - **Claude Code updates.** When Claude Code updates itself, team members already running stay on the old version until they restart. A "team upgrade ready" chip and note offer to close the office the safe way (everyone saves first) and reopen on the new version. Nothing restarts until you click. +- **Two separate businesses.** Each business keeps its own settings, saved passwords and keys, files, history and, if you choose, its own Claude account. The business name in the top bar switches between them, closing the open office properly first, and Add a business sets up another while the open one keeps working. The business you are not in waits until you open it. +- **Backup and restore.** One file holds everything on this computer: every business, its team, memory, tasks, history, knowledge, settings and the team's folders, with saved passwords and keys locked by a backup password. Restore it on a new computer from Settings, General, or from the first setup screen.
(↑ back to top)
@@ -321,7 +323,9 @@ follow. trust layer that keeps out the kinds of data you mark private in Settings, Research & privacy, and their answers are cleaned of instructions before your team reads them. They see none of your files, and they are off until you turn them on. On Windows, they can still reach your office files. - The one exception: when you start your case study, the app reads your logo from your own website. + Two exceptions: when you start your case study, the app reads your logo from your own website, and as + you type a street address, the app asks OpenStreetMap (Photon) for matching addresses, sending only + what you typed in that field. - **A case study, only if you send it.** Pulse can build a case study page of your office for our website. It goes out only when you press Send, from your own mailbox, after you agree we may publish it and take it down if you ask. See [`TELEMETRY.md`](./TELEMETRY.md#case-studies-you-send-us). @@ -391,5 +395,5 @@ The **source code** is licensed under the **MIT License**. See [`LICENSE`](./LIC ## Acknowledgements -- [Munder Difflin](https://github.com/chaitanyagiri/munder-difflin) by Chaitanya Giri, for the inspiration. Don't Be Michael is a complete rewrite, built from the ground up so AI agents can run the everyday work of a small business. +- Munder Difflin by Chaitanya G, for the inspiration. Don't Be Michael is a complete rewrite, built from the ground up so AI agents can run the everyday work of a small business. - [xterm.js](https://xtermjs.org/) · [node-pty](https://github.com/microsoft/node-pty) · [electron-vite](https://electron-vite.org/) · [CodeMirror](https://codemirror.net/) for the libraries this is built on. diff --git a/RELEASE.md b/RELEASE.md index 0e7aef46d..368b4013e 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,12 +1,14 @@ -# Don't Be Michael v0.4.2 +# Don't Be Michael v0.4.3 **An AI office for your small business.** Pick your kind of business, pick your team, and Michael, your office manager, runs the floor while you run the business. -## What's new in 0.4.2 +## What's new in 0.4.3 -- **Team members attach files from their folder.** Ask a team member to email a client the statements in its folder, and the files go with the email. On Send on approval the card lists each file: open it, or take it off before you approve. A file a teammate keeps is handed over first. -- **Slow shares no longer stall a turn,** and a network path is never shown as missing. -- **Quoted text in the terminal links the file inside it,** when the quote is a sentence rather than a path. +- **Run two separate businesses on one computer.** Each business keeps its own settings, saved passwords and keys, files, history and, if you choose, its own Claude account. The business name in the top bar switches between them, and switching closes the open office properly first. +- **Add a business while the open one keeps working.** Setup opens over the office, and the new business's folder is named after it. +- **Back up everything and restore it on a new computer.** One file holds every business, with saved passwords and keys locked by a backup password. +- **Always allowed, for the privacy check.** List your business's own public names and links, and an Ask me card offers to allow what the check kept back. +- **Setup is easier.** Address suggestions, business hours by day, languages and currency from a list, and Ask me cards three questions at a time. Every feature, release by release: [docs/FEATURES.md](https://github.com/agentvivekkumar/dontbemichael/blob/main/docs/FEATURES.md) @@ -14,15 +16,15 @@ Every feature, release by release: [docs/FEATURES.md](https://github.com/agentvi | Platform | Download | |---|---| -| Mac (Apple Silicon and Intel) | [`Dont-Be-Michael-0.4.2-mac-universal.dmg`](https://github.com/agentvivekkumar/dontbemichael/releases/latest/download/Dont-Be-Michael-0.4.2-mac-universal.dmg) | +| Mac (Apple Silicon and Intel) | [`Dont-Be-Michael-0.4.3-mac-universal.dmg`](https://github.com/agentvivekkumar/dontbemichael/releases/latest/download/Dont-Be-Michael-0.4.3-mac-universal.dmg) | -**Windows 11 (x64):** [`Dont-Be-Michael-0.4.2-win-x64-setup.exe`](https://github.com/agentvivekkumar/dontbemichael/releases/download/v0.4.2/Dont-Be-Michael-0.4.2-win-x64-setup.exe). ARM PCs aren't supported. This build is not yet signed with a Microsoft certificate: when Windows says **Windows protected your PC**, click **More info**, then **Run anyway**. +**Windows 11 (x64):** [`Dont-Be-Michael-0.4.3-win-x64-setup.exe`](https://github.com/agentvivekkumar/dontbemichael/releases/download/v0.4.3/Dont-Be-Michael-0.4.3-win-x64-setup.exe). ARM PCs aren't supported. This build is not yet signed with a Microsoft certificate: when Windows says **Windows protected your PC**, click **More info**, then **Run anyway**. Linux will follow. -[Source code (zip)](https://github.com/agentvivekkumar/dontbemichael/archive/refs/tags/v0.4.2.zip) · [Source code (tar.gz)](https://github.com/agentvivekkumar/dontbemichael/archive/refs/tags/v0.4.2.tar.gz) +[Source code (zip)](https://github.com/agentvivekkumar/dontbemichael/archive/refs/tags/v0.4.3.zip) · [Source code (tar.gz)](https://github.com/agentvivekkumar/dontbemichael/archive/refs/tags/v0.4.3.tar.gz) ## Installing on your Mac diff --git a/TELEMETRY.md b/TELEMETRY.md index 9d77e8381..60354ae4b 100644 --- a/TELEMETRY.md +++ b/TELEMETRY.md @@ -79,8 +79,12 @@ memory. - **Your logo is read from your own website.** When you press Get featured, the app reads the home page of the website in your company profile and the logo image it names, once, over HTTPS, from public addresses only, and keeps the logo in your office's private folder. That website sees an ordinary - web request from your computer. It is the one time the app itself reads a web page; everything - else on the internet goes through your Research team member. The page always shows your business - name, logo and website. + web request from your computer. It is one of two times the app itself reaches the web (address + suggestions, below, are the other); everything else on the internet goes through your Research + team member. The page always shows your business name, logo and website. +- **Address suggestions come from OpenStreetMap.** As you type the street in setup or in your + company profile, the app sends only the text of that field to OpenStreetMap's Photon service + (photon.komoot.io), at most every 300 ms, with no name, email or other detail. A failure just + means no suggestions, and you type the address yourself. - A case study is a submission you choose to make, not usage data: the app does not tell us that you opened the screen, and nothing is sent in the background. diff --git a/TODOS.md b/TODOS.md index 92105f0cd..42d4bda85 100644 --- a/TODOS.md +++ b/TODOS.md @@ -1,5 +1,91 @@ # TODOS +## Two unrelated businesses (deferred from the CEO review of docs/designs/separate-businesses.md, 2026-11-18) + +### Write a line to the office log when a business moves, switches or is set up + +**What:** Settings migration, a switch and the first open of a new business each write one line to the hive log (log.jsonl) with the office id and the app version. + +**Why:** Today the move logs only to the console, so a support case cannot see when an office moved or switched, or on which version (Sections 3 and 8 of the plan). + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Tag failure reports with the office id + +**What:** failures.jsonl rows and the reports sent from them carry the open office's id. + +**Why:** With two businesses on one install, a failure report cannot say which business it came from (T3 and Section 8). + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Check at launch that the business name matches the office record + +**What:** At launch, compare the open office's settings business name with its office.json and report a mismatch. + +**Why:** A mismatch is the first sign of one business's settings reaching the other's office (Section 8). + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Refuse two businesses sharing one business folder + +**What:** Add a business, and Settings when the business folder changes, refuse a business folder another business already uses. + +**Why:** Two businesses on one folder would mix their documents (Section 4 edge case). addBusiness refuses only the open office's folder and a finished office folder. + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Refuse a mailbox another business already has + +**What:** Adding a mailbox checks every business's mailboxes and says the address belongs to that business. + +**Why:** Mailboxes are per business now, so the old one install check only looks at the open business (mail.ts, Section 4 edge case). + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Name the business on a hire or deep link screen + +**What:** A link that hires or joins says which business it will join before anything happens. + +**Why:** With two businesses, a link opened while the wrong one is open would add to it (Section 3 threat table). + +**Context:** Deferred from plan: docs/designs/separate-businesses.md. Planned in the CEO review, not built in step one; the owner chose to ship and defer it (2026-11-20). + +**Effort:** S (human) / S (CC) +**Priority:** P1 +**Depends on:** None + +### Both businesses running at once in one app + +**What:** Step two of docs/designs/separate-businesses.md: each business runs as its own office process at the same time, with one window, a business switcher and a Needs you list marked by business. + +**Why:** In step one the business the owner is not looking at pauses: its mail, schedules and agents wait. An owner running a bakery and a real estate agency needs both working all day. + +**Context:** Owner chose this direction in the CEO review (D1, option C) and deferred it until step one ships (D3). Step one moves every business field out of the shared `config.json` into the office, so this work starts from per office settings. Today the app holds one office per process (`requestSingleInstanceLock`, src/main/index.ts:2832) and one window; the earlier New Floor window shared one hive and was removed on 2026-10-03 (docs/FEATURES.md:879). Two Michaels at once doubles Claude usage. If the Mac user per business interim (OV-1) works, it is the stopgap until this ships. + +**Effort:** XL (human) / L (CC) +**Priority:** P2 +**Depends on:** step one of docs/designs/separate-businesses.md + ## Source links on cards (from the CEO review of docs/designs/ask-me-source-links.md, 2026-11-08) ### Links to connector records that come with only an id @@ -282,18 +368,6 @@ Go with it: keep only the owner's own words (the answer, the edit, the note) in **Priority:** P3 **Depends on:** None -### Key Pulse by a stable office id, not its folder path - -**What:** Store an office id in the office and key telemetry rows by it, or re-key rows when Settings moves the office; resolve the path with realpath meanwhile. - -**Why:** Moving the office, or reaching it by another spelling (a symlink, a different case), splits Pulse history and runs the backfill again under the new key. - -**Context:** From the /ship red team review, 2026-10-16. `pulseOffice()` in `index.ts` returns `expandTilde(harnessHome)`. - -**Effort:** M (human) / S (CC) -**Priority:** P2 -**Depends on:** None - ### Hand the hook secret over where another process cannot read it **What:** On engines and platforms where a sibling process can read another's environment (Linux /proc, Windows), pass the hook secret through a 0600 file or descriptor only that agent's sandbox can read, or check the peer on the socket. @@ -955,6 +1029,20 @@ A live end-to-end run is required before adding an engine: Gemini has never been ## Completed +### Key Pulse by a stable office id, not its folder path + +**What:** Store an office id in the office and key telemetry rows by it, or re-key rows when Settings moves the office; resolve the path with realpath meanwhile. + +**Why:** Moving the office, or reaching it by another spelling (a symlink, a different case), splits Pulse history and runs the backfill again under the new key. + +**Context:** From the /ship red team review, 2026-10-16. `pulseOffice()` in `index.ts` returns `expandTilde(harnessHome)`. + +**Effort:** M (human) / S (CC) +**Priority:** P2 +**Depends on:** None +**Completed:** unreleased, mit/promote-retry-5xx (2026-11-20). `pulseOffice()` returns the office's lasting id once settings are per office, and `persist.relabelOffice` moves existing rows from the folder to the id (E5 in docs/designs/separate-businesses.md). + + ### Sign and notarize the Mac build with an Apple Developer ID **What:** Add the Developer ID Application cert and notarization credentials as repo secrets (`APPLE_CERTIFICATE_P12`, `APPLE_CERTIFICATE_PASSWORD`, `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_TEAM_ID`). `release.yml` and `build/notarize.cjs` already use them when present. diff --git a/branding/DESIGN.md b/branding/DESIGN.md index 29a9441bd..6548bef2a 100644 --- a/branding/DESIGN.md +++ b/branding/DESIGN.md @@ -516,7 +516,9 @@ Names in parentheses are today's components that the v2 component replaces or re ### 7.1 Top bar -Left to right: lockup (§1.5, 26 px mark); view tabs (§7.2); then, pushed right: clock +Left to right: lockup (§1.5, 26 px mark); the business menu (BusinessMenu: the open +business's name as a quiet menu button, capped at 220 px, listing every business with its +state and Add a business; docs/designs/separate-businesses.md DT1); view tabs (§7.2); then, pushed right: clock pill (§7.3), version chip (§7.4), Report a problem (a solid `lemon` pill, `on-accent` text, 28 px high, 12/600 with a flag icon; its hover text is a native title and `aria-description`, and it reads "Couldn't open" for 2 s if the report page fails; docs/designs/report-problem-top-bar.md), icon buttons (theme, Settings; focus mode hidden in this build, `SHOW_FOCUS_MODE`; 32 × 32, `r-md`, `ink-2` icons, hover fills `card` with a `line` border), and the Needs you button (§7.5). The bar is a drag region; interactive children are `no-drag`. Coral stays Needs @@ -1266,8 +1268,8 @@ Full window, no app chrome. Team, Manager, Permissions, Ready; five when Michael's engine is not Claude) in a `card` pill container, each a 22 px circle (done: `green` with a check; current: `ink` with the number; next: `line-2` ring with the number) joined by 1 px `line-2` rules; "Step 4 of 8" right, `t-meta`. -- Body: a 560 px card with the step's fields. While the studio isn't showing (Business, - Details, Resume, or no team yet) the card is centered under the step indicator; once it +- Body: a 560 px card with the step's fields (the Team step's is wider, below). While the + studio isn't showing (Business, Details, Team, Resume, or no team yet) the card is centered under the step indicator; once it shows, the card sits at the start edge and the studio (§8) fills the rest, reacting to the step. The card glides there over `--cth-dur-slow` (320 ms) as the studio fades in, and back on Back; reduced motion jumps. The soft glow behind the page follows: behind @@ -1276,14 +1278,20 @@ Full window, no app chrome. as quiet rows in one `line` card, a 26 px neutral icon and a label each, the explanation behind an info icon (review, 2026-10-01: it was a grid of tinted tiles, one coral). - **Team step**: heading "Your team" with an info icon, one line "Suggested for Pro - Services. You can hire more later." Rows: checkbox, 36 px avatar, name 600, role `ink-3`, - tags ("in every pack" green soft; "always on" indigo soft for Michael, who has a lock and - no checkbox), connection chips ("needs: Email" with an indigo dot on `card-2`, "optional: - Calendar" with a dashed `line-2` border, "nothing to connect" `ink-3`), and a mono - "Works in Harbor & Pine/Finance" line with a "change" link. Unchecked rows at 55%. + Services. You can hire more later." The card is wide (up to 1400 px) with no studio beside + it (owner, 2026-11-19). One folder line under the heading: a folder icon, "Each person works + in their own folder inside ~/Documents/Harbor & Pine.", an info icon with the rest, and a + "change" link for the office folder ("use suggested" once changed); each member's folder + goes inside it, and is moved after setup if needed. The members are cards in a grid, four + across in a usual window (280 px minimum, 10 px gap), each 12 px padding and `r-lg`: + checkbox, 36 px avatar, name 600, role `ink-3`, summary, tags ("in every pack" green soft; + "always on" indigo soft for Michael, first, who has a lock and no checkbox), connection + chips ("needs: Email" with an indigo dot on `card-2`, "optional: Calendar" with a dashed + `line-2` border, "nothing to connect" `ink-3`). A picked card has a 2 px `ink` ring on + `card`; an unpicked one a 1 px `line` ring on `card-2`, its contents at 60%. Footer: "N picked, M to connect" and Back (secondary), Next (primary). The footer sticks - to the window's bottom edge, so Next stays in reach on a long step. Last in the list, one - unchecked row for Research (issue #230): Pete's own character, its current name, "Looks things up on the + to the window's bottom edge, so Next stays in reach on a long step. Last in the grid, one + unchecked card for Research (issue #230): Pete's own character, its current name, "Looks things up on the internet for the team, and sees no office data.", a "uses the internet" chip in the "always on" style; picked, it starts with the team. - **Ready step** (Get Michael ready, docs/designs/get-michael-ready.md): heading with an @@ -1700,12 +1708,15 @@ review 2026-11-03). Same card as §7.27a, with these changes: clamped to two lines, `dir="auto"`; under it the app's own line in `amber-text` 11 px: the member, the file it was seen in, the day. Add is a 26 px secondary button; Not ours and Decide later are quiet links with 24 px targets, each named for its item. - - Add puts the name on a new line in the box; the row becomes a `green-soft` line "Added to the - list. Save to keep it." with Undo. + - Add is saved at once (owner, 2026-11-18): the name goes on the saved list, known so far, and + on a new line in the box; the row becomes a `green-soft` line "Card ending 1005 is on the + list." with Undo, under the undecided rows. A full list refuses it with a `coral-text` line. - Not ours is saved at once; the row becomes an `indigo-soft` line "Card ending 1005 is marked not ours." with Undo until the card leaves the board; a failure is a `coral-text` line. - Decide later is saved at once; the row becomes a `neutral-soft` line "Back next week." with Undo. Focus moves to the next undecided Add, else to Save; each change is spoken politely. + - Each settled line ends in a quiet × ("Close the line about Card ending 1005") that hides the + line on this card and keeps the choice. - **Primary button**: "Save as the whole list"; "Save the list so far" while an item is put off; "Still all of them" on a card past its shelf life whose box matches the saved list. Held until every seen item is added, not ours or put off. It never truncates. diff --git a/build/release-notes.md b/build/release-notes.md index 2ca83915c..91bc74880 100644 --- a/build/release-notes.md +++ b/build/release-notes.md @@ -1,4 +1,4 @@ -- **Team members attach files from their folder to an email.** -- The approval card lists each file to open or take off. -- A teammate hands over a file it keeps. -- Slow shares no longer stall a turn. +- **Run two separate businesses on one computer.** +- Add a business while the open one keeps working. +- Back up everything and restore it on a new computer. +- Always allowed: your business's own public names pass the privacy check. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9667247b8..58687a48c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -58,7 +58,15 @@ src/ config.ts harness config persistence + home setup; Claude Code's ~/.claude.json (folder trust, the first-run welcome, an approved API key), written to a copy and swapped in; folder trust is keyed as Claude Code looks it up (forward slashes on Windows, claudeProjectKey); - a config.json it cannot read is copied beside it before the next save (damagedConfigCopy) + a config.json it cannot read is copied beside it before the next save (damagedConfigCopy); + readConfig and writeConfig route business fields to the open business's own entry + (docs/designs/separate-businesses.md), and officeDataPath gives each business's place + in the app's data folder (offices//) + officeSettings.ts / officeKeys.ts each business's own settings: config.json `offices[]` beside the + install's own keys, one home per field (BUSINESS_KEYS, INSTALL_KEYS), the one time move + at launch (migrateToOfficeSettings, config.before-offices.json kept for a downgrade), + adoptOpenOffice, and the business list, Add a business and Find it behind the top bar's + business menu and Settings, Your businesses (listBusinesses, addBusiness, relocateBusiness) engineSetup.ts Get Michael ready: finds Claude without a shell, Claude's standalone install script, sign in state (`claude auth status`), the Anthropic API key check (docs/designs/get-michael-ready.md; status types in shared/engineSetup.ts) @@ -90,6 +98,9 @@ src/ harness.db (the pure parts are in shared/runCompare.ts) teamMemory.ts the dates and sources of each member's memory notes, for Pulse's Learning tiles claudeAccount.ts which Claude plan the owner's account is on (plan fields of Claude Code's account record only) + claudeHome.ts where Claude Code keeps its settings and `.claude.json` for this run, following + CLAUDE_CONFIG_DIR, which the app sets for a business with its own Claude login + (`userData/offices//claude`); every Claude file the app reads or writes goes through it github.ts GitHub issue + CI run ingestion via the gh CLI shellEnv.ts resolve PATH and shell env for child processes mail.ts IMAP/SMTP client for connected mailboxes; the broker calls it for md-mail tool calls, and @@ -125,7 +136,8 @@ src/ standingCheck.ts the separate quick check (hidden Claude, no tools) that an email fits a standing approval; anything it can't read counts as no, so the email goes to the owner integrations.ts the secret store: every saved password and key in one safeStorage-encrypted file - (integration-secrets.json in userData, 0600); refuses to save over a file it can't read + (integration-secrets.json in userData, 0600); refuses to save over a file it can't read; + each business's entries are keyed by its office id (`@/`) atomicFile.ts crash-safe file write (temp file, fsync, rename); the secret store's writer officeBreak.ts the office break when Claude can't work: the plan's usage limit (hooks.ts reports the StopFailure `rate_limit` and the status line's reset time), no credit left, or a sign in or @@ -144,7 +156,13 @@ src/ researchNotes.ts Pete's files read only as plain files inside his own folder factoryReset.ts what Settings, Reset & start over erases (app:resetAll in index.ts): everything the app made for the office, in the office folder and the app's data folder; team folders, - roster backups, the owner's own files and the Claude sign in stay + roster backups, the owner's own files and the Claude sign in stay; with several businesses + it erases only the open one's (its place, secrets, rows and settings entry) + backup.ts / backupArchive.ts / backupSecrets.ts Settings, General, Backup (docs/designs/backup-restore.md): + everything on this computer in one `.dbmbackup` gzip stream (the app's data folder by an + allow list, a database snapshot, each office, business and team folder, the team's Claude + conversations), saved passwords and keys sealed with a backup password (scrypt, + AES-256-GCM), and restore with paths moved to the new home folder closingTime.ts Closing Time shutdown protocol (the office reopens on next launch, shared/officeOpen.ts) The closing time bar (ClosingTimeBar) lists who is still working (hook `detail` from hooks.ts toolDetail), with Remind and Close without them (never pty:kill: that archives the agent). @@ -204,7 +222,11 @@ src/ restart.ts restarts the app after a reset or a home change, and knows when a dev build cannot relaunch roster.ts the roster on disk: agents, notes, worktree paths, archived entries and parked message queues, one JSON file beside the hive (hive identity stays in registry.json) - officeFile.ts /office.json, the office's own record (shared/officeRecord.ts) + officeFile.ts /office.json, the office's own record (shared/officeRecord.ts), with its lasting + id (ensureOfficeId); officeSwitchGuard refuses another business's office while settings + are not yet per business + inheritedEnv.ts drops the settings a Claude Code session hands down when the app was started inside one + (a dev run), so the team and the checks never run on the host session's own skills.ts skills: the ones installed for each CLI on this machine, and a catalog of what could be; Settings, Skills is hidden in this build (SHOW_SKILLS), and skills keep working slack.ts / slack-trigger.cjs Slack messages into Michael's queue over a bare http server that verifies every request @@ -240,6 +262,11 @@ src/ off by default, then per agent; books roles like Oscar default to Read only) officeOpen.ts the Office open message each agent gets after closing time + officeHome.ts where an added business's office folder goes (~/HarnessAgents_) + businessHours.ts / currencies.ts / languages.ts / socialSite.ts / photon.ts the company profile's pickers: + hours by day, written as one line agents read; the currency and language lists; a social + link's site; address suggestions from Photon (OpenStreetMap), called from main + inboxSweep.ts refuses a command that moves inbox messages picked by a wildcard, so none is filed unread cliUpdate.ts whether live Claude agents run an older Claude Code than the one installed (cliUpdate:status push, cliUpdate:current pull) folderAccess.ts who may open and change which folder: sandbox, permission rules, hook checks; @@ -290,6 +317,9 @@ src/ heldByBreak (Claude agents only) research.ts the Research team member: its id, default name (Pete; the owner may rename it, and researchText shows the current one), house rule 9, refusal reasons and the reply label + publicTerms.ts / researchKept.ts Always allowed, the owner's list of the business's own public names and + links the privacy check keeps as written (passwords and keys never pass), and what the + check kept back from a question, offered on Ask me (ResearchKeptCards) dataClasses.ts the kinds of data the owner keeps private (Settings, Research & privacy) and the fixed patterns the trust layer marks them with webAccess.ts who may use web pages and search (the Research agent alone, in every office), and the empty @@ -370,6 +400,10 @@ src/ MemoryNotes, an agent's Memory tab as grouped notes; "Show the file" keeps the raw text OwnerViaMichaelBar, replaces a team member's message box outside 1:1 (Message Michael / Talk 1:1) OfficeFolderMissing, launch screen shown only when the office folder is missing + YourBusinesses, Settings, General, Your businesses: the same rows as the top bar's business menu + (shell/BusinessMenu.tsx, shell/businessMenuRows.ts), with Open, Find it and Remove + BackupRestore, Settings, General, Backup: back up with a backup password, or restore (also on the first + setup screen of a new computer) CliUpdateNotice, "team upgrade ready" title-bar chip and corner note; its click runs closing time with relaunch, "later" waits for a newer version (localStorage cth.cliUpdateLaterFor) TasksKanban, dependency-aware kanban board (the Tasks view); the owner closes a card as Done, diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 0c0cbe4d5..11942d1a5 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -1,6 +1,6 @@ # Don't Be Michael: features and changes -Everything the app does today, and every release that got it here (0.0.1 to 0.4.2). Part 1 is +Everything the app does today, and every release that got it here (0.0.1 to 0.4.3). Part 1 is written to be lifted onto the GitHub page and the website as it is; Part 2 is the full list, release by release. @@ -228,6 +228,10 @@ moving, and brings you only the decisions that need you. pages or searches, in every office. A trust layer checks every message to Pete against the kinds of data you keep private and cleans Pete's answers. Pete is off until you turn them on, and sees none of your files. On a Mac nobody else's commands reach the internet. +- Always allowed: in Settings, Research and privacy, list your business's own public names and + links, and the privacy check keeps them as written in questions to Research. When the check + keeps words back, an Ask me card offers to always allow each one and ask again. Passwords and + keys never go through, whatever the list says. ### 7. An office you can watch - A pod for each department around Michael's glass office, each with a plate in front of the @@ -279,8 +283,25 @@ moving, and brings you only the decisions that need you. ### 8. Built for small business owners - Setup by kind of business: restaurant and food, retail, professional services, home services, SaaS and consulting, or anything else. Each comes with a suggested team. +- Setup and the company profile save typing: address suggestions from OpenStreetMap as you type + the street, business hours set day by day, languages served and currency picked from a list, + and one field per social link with the site named. Team setup shows the members side by side + and asks for one office folder. - Runs on your computer with the Claude plan you already have. Plain words, no developer settings. A Windows 11 (x64) build ships with every release. +- Run two separate businesses on one computer, such as a bakery and a real estate agency. Each + keeps its own settings, saved passwords and keys, files, history and, if you choose, its own + Claude account. The business name in the top bar switches between them: the open office closes + properly first, everyone finishing or handing off their step, then the other opens. The business + you are not in waits: its mail and schedules run again when you open it. +- Add a business from the top bar or Settings while the open one keeps working. Setup opens over + the office, the new business's folder is named after it, and Back to the office keeps what you + typed for later. Settings, General lists every business with Open, Find it for a folder that + moved, and Remove for a setup never finished. +- Back up everything on this computer to one file and restore it on a new one: every business with + its team, memory, tasks, history, knowledge, settings and the team's folders. Saved passwords and + keys are locked with a backup password you choose. Restore from Settings, General, or from the + first setup screen of a new computer, then sign in to Claude again. - When your Claude plan reaches its usage limit, the office takes a break. Ask me, the top bar and the floor say when work starts again. Nothing is typed into a Claude terminal meanwhile, and scheduled jobs still go out on time and wait in the inbox. At the reset the team carries on by @@ -310,6 +331,21 @@ moving, and brings you only the decisions that need you. ## Part 2: Every change, release by release +### 0.4.3 (2026-11-20) +- Two separate businesses on one computer: each keeps its own settings, saved passwords and keys, + files, history, spend caps and, optionally, its own Claude account. The business name in the top + bar switches; Settings, General lists every business with Open, Find it and Remove. A switch + closes the open office first. Existing installs move their settings on the first launch. +- Add a business over the open office; Back to the office keeps what was typed. +- Back up everything to one file and restore it on a new computer, from Settings or the first setup + screen. Saved passwords and keys are locked with a backup password; a restore writes only into + the business's own folders and says when it stops partway. +- Always allowed for the privacy check, and Ask me cards that offer to allow what it kept back. +- Address suggestions from OpenStreetMap, business hours by day, languages and currency from a list, + one field per social link, Team setup four across with one office folder. +- Ask me shows three questions at a time. Pete waits while he starts. Closing time tells and reminds + Michael once everyone confirmed, and Michael files only the messages he read. + ### 0.4.2 (2026-11-17) - A team member attaches files from its own folder, or a folder you named for its job, to an email. On Send on approval the card lists each file to open or take off. A file a teammate keeps is diff --git a/docs/designs/backup-restore.md b/docs/designs/backup-restore.md new file mode 100644 index 000000000..88dddc6b1 --- /dev/null +++ b/docs/designs/backup-restore.md @@ -0,0 +1,49 @@ +# Back up everything, restore it on a new computer + +Owner request, 2026-11-19: "build an ability to take a full back up so that a business owner can restore the setup and content as it is to a brand new computer". + +## Decisions (owner, 2026-11-19) + +| Question | Answer | +|---|---| +| Saved passwords and keys (locked to this Mac's Keychain) | In the backup, sealed with a backup password the owner sets; re-locked to the new Mac on restore. | +| Which businesses | Everything on this Mac in one backup: every business and the app's own settings. | +| The team's working folders (the business's documents) | Included. | + +## What a backup holds + +One `.dbmbackup` file (src/main/backupArchive.ts): a gzip stream with a manifest line and each file as a header line plus its bytes, written and read as a stream, so a large documents folder never sits in memory. Node's own zlib, no archive library, the same on every platform. + +| Root | What | Restored to | +|---|---|---| +| The app's data folder | config.json, every business's place (`offices/`), knowledge, journals, approvals, dock keys, pasted images, the window's saved state, the old config copy. The list follows factoryReset.ts's own lists (`USER_DATA_ITEMS`), so a new app file is never forgotten. Not: the secrets file, caches, scratch check folders, opened attachments, logs. | The new computer's data folder | +| The database | A consistent snapshot (better-sqlite3 `backup`) taken while the app runs. | harness.db | +| Each office folder | The hive (team, tasks, log, memory), the palace, roster, office.json, Research's desk. Not sockets, links or `.DS_Store`. | The same place under the new home folder | +| Each business and team folder | The documents the team works in; a folder inside another is carried once. Only folders a restore puts back (`restorableFolder`): never the home folder itself, a dot folder, Library or Windows AppData. Not `node_modules`. | The same place under the new home folder; a file already there is kept | +| The team's Claude conversations | ~/.claude/projects for each agent's folder, so their sessions resume. | Under the folder's new name | +| Saved passwords and keys | Decrypted on this Mac, sealed with the backup password (scrypt, AES-256-GCM: src/main/backupSecrets.ts). | Re-locked to the new Mac (safeStorage) | + +No root carries a Claude sign in file (`.credentials.json`) or an earlier backup (`.dbmbackup`), wherever they sit (`SKIP_NAMES` and `isBackupFile`, src/main/backup.ts). + +## Restore + +- From the first setup screen of a new computer ("Moving from another computer?"), or Settings, General, Backup. +- The owner picks the file and sees when it was made and its businesses, then gives the backup password. The password is checked before anything stops: a wrong one changes nothing. +- A backup with no saved passwords or keys needs no backup password. +- An office already there has its files replaced, read only ones included; a business or team folder already there keeps its files. A link already on the disk is never followed out of its folder. +- The office stops (as a reset does), every file goes back, and when the username differs every path under the old home folder moves to the new one: in the app's own JSON files (config, office.json, the registry, the roster) and in the database's office column (`movePathPrefix`). Then the app reopens on the restored office. +- A restore that stops partway, such as on a file it cannot write, stops with that error and says so; the owner reopens the app. + +## What cannot move + +The Claude sign in (the Keychain) and its connectors (the claude.ai account). After a restore the owner signs in to Claude again, and Gmail, QuickBooks and the rest come back with the account. + +## Not covered + +- A restore onto a computer of another kind (a Mac backup onto Windows): paths are moved only under the home folder. +- Merging a backup into a computer that already has businesses: restoring replaces what is there (the screen says so). +- Files that change while a backup runs are stored as they were when read. + +## Tests + +test/backup-restore.test.cjs (17 cases: the format round trip with times; a crafted or cut file; the sealed passwords, wrong password and changed file; the file name with no spaces or special characters; moving paths; what the app data part carries; a whole computer backed up and restored under another username; the wiring and copy; two businesses in one backup; no secrets, no password; a crafted backup that names its own folders; restoring over an office already there; no Claude sign in file or earlier backup; a restore that stops partway; a link already in a restored folder (not on Windows); a file that cannot be written; only folders a restore puts back). test/pulse-office-id.test.cjs moves the database's folder keyed rows under Electron's Node. diff --git a/docs/designs/separate-businesses-mockup.html b/docs/designs/separate-businesses-mockup.html new file mode 100644 index 000000000..6c50b2947 --- /dev/null +++ b/docs/designs/separate-businesses-mockup.html @@ -0,0 +1,180 @@ + + + + + +Two businesses mockup + + + + + + +
+
+

Two businesses on one Mac

+

Step one of docs/designs/separate-businesses.md. Example businesses: Harbor & Pine Bakery and Northgate Realty.

+
+ +
+
1 · The open business, and switching (top bar)
+
+ + +
OfficeTasksPulse
+
+ 9:41 +
+ +
+
Harbor & Pine Bakery
+

The business name sits right of the mark as a quiet button (DESIGN.md §7.1 icon button hover). With one business it is plain text and the menu holds only Add a business. Row states: Open, Closed since, Folder not found (never starts closing time), Setup not finished (reopens the wizard). Name capped at 220 px with an ellipsis.

+
+ +
+
2 · Switching: closing time first (D10)
+
+
Closing Harbor & Pine Bakery to open Northgate Realty5 / 8 workers confirmed
+
+
3 still working ▴ +
+
+

The §7.23 closing bar with its subject changed. Cancel switch keeps the bakery open. Switch now asks once, like Force quit now, because unsaved work is lost.

+
+ +
+
3 · Before step one ships: the guard (T2, D8)
+
+

That office belongs to another business i

+

Open it from its own Mac user for now.

+
+
+

One title, one line, one button. The second line only says "its own Mac user" if T1 shows two Mac users run side by side; otherwise it reads "It can't be opened from here yet."

+
+ +
+
4 · Add a business: the setup wizard, Ready step
+
+
✓✓✓✓✓6New business · Step 6 of 6
+
Claude account for Northgate Realty i
+
Same as Harbor & Pine Bakeryowner@example.com
+
A different Claude accountSign in on the next screen
+
+
+

The same wizard as first setup (§7.25), headed New business, opened over the app while Harbor & Pine Bakery keeps working. Open the office at the end starts closing time for the bakery. The account choice is the only new field.

+
+ +
+
5 · An office that no longer shares mailboxes (D11)
+
+
Mailboxes
+
No mailboxes yetHarbor & Pine Bakery's mailboxes stay with it.
+
+

Settings, Mailboxes, empty state. Schedules show the same pattern. The floor shows nothing extra; Michael raises it only if a job needs a mailbox.

+
+
+ + diff --git a/docs/designs/separate-businesses.md b/docs/designs/separate-businesses.md new file mode 100644 index 000000000..cdab3ec63 --- /dev/null +++ b/docs/designs/separate-businesses.md @@ -0,0 +1,1049 @@ +# One owner, two unrelated businesses + +Status: step one built and complete (2026-11-20, see "Step one complete" below); step two deferred to TODOS.md. Reviews: CEO (2026-11-18, strategy-only depth: which way to support it, not the implementation design), eng and design (2026-11-18). + +Ask (owner, 2026-11-18): some owners run two businesses that share nothing, such as a bakery and a real estate agency. Explore the best way to support this. + +## What the app does today (receipts) + +- An office is a folder (`harnessHome`, default `~/HarnessAgents`), marked by `hive/registry.json` (src/main/homeFolder.ts:23,31). It holds the hive, memory palace, agent settings, `office.json` and `private/` (foundations, owner chat, broker tokens). +- Nearly everything about the business lives in ONE app-wide `config.json` (src/main/config.ts:229-248, 303-326, 387-393): business name, city, type, company profile, business folder, team, mailboxes, agent grants, Claude connector switches, QuickBooks, schedules, custom integrations, notifications. The code says it: "Several offices share one config" (src/main/officeFile.ts:79). +- Secrets for every office sit in one `integration-secrets.json`; the company knowledge store is app-wide by default (src/main/knowledge.ts:68-73). +- One app process (src/main/index.ts:2828-2834) and one window; the second floor window went 2026-10-03 (docs/FEATURES.md:879). +- Switching office (Settings, General, "Other offices on this computer" or "Change office folder") writes only `{ harnessHome }` and relaunches (src/main/index.ts:4203). `office.json` is never read back on a switch (src/main/index.ts:4110-4114). +- Claude login, Claude connectors (Gmail, Calendar, QuickBooks, Drive, HubSpot) and transcripts belong to the Mac user's `~/.claude` (src/main/claudeAccount.ts:16-18, src/main/transcript.ts:47-52). A Claude connector holds one account per service (docs/designs/claude-connectors.md:4-6, docs/designs/multi-mailbox.md:7). +- The app's own mailboxes (IMAP/SMTP) can hold many addresses, but in one app-wide list; one address can be connected once per install (src/main/mail.ts:2161-2164). + +**Consequence:** today a second business on the same Mac user is not isolated. "Start a new, empty office here" keeps the first business's name, city, type, profile, mailboxes, grants and schedules (inferred from index.ts:4203 writing only harnessHome; not yet reproduced live). The bakery's Michael would introduce himself as the real estate agency, its standup would fire into the other office, and its foundations would be seeded from the other company's profile (src/main/foundations.ts:275-303). Only one business runs at a time, so the other one's mail, schedules and agents stop while it is closed. + +## Step 0A. Premise + +- **Real problem:** an owner with two businesses needs two offices that never mix (identity, customers, mail, money, memory) and that both keep working. +- **Proxy to avoid:** "a switcher in Settings". A switcher on top of a shared config makes mixing easier, not harder. +- **Cost of doing nothing:** the switch path that exists already crosses data between businesses. An owner who tries it today gets one business's agents speaking for the other. That is the worst outcome for a business owner (wrong company name in a customer email, the wrong QuickBooks company). + +## Step 0B. Existing code to reuse + +| Sub-problem | Reuse | Gap | +|---|---|---| +| Office data on disk | the office folder, `office.json` record (src/main/officeFile.ts, src/shared/officeRecord.ts) | config keeps the live copy; office.json is a mirror | +| Listing offices | `recentHives` (src/main/fs.ts:292-307), Settings "Other offices" (SettingsModal.tsx:716-730) | capped at 8, no business names | +| Switching | `config:changeHome` stop, relaunch (index.ts:4145-4207) | carries the whole config across | +| Office keyed stats | Pulse tables already carry an `office` column (src/main/db.ts:214) | keyed by folder path (TODOS.md:284-293) | +| Separate Claude account per office | Claude Code honours `CLAUDE_CONFIG_DIR`; the app passes it through to terminals (src/main/ptyEnv.ts:40) and some readers use it (claudeAccount.ts:17, transcript.ts:47) | the app never sets it per office; sign in storage follows the undocumented `CLAUDE_SECURESTORAGE_CONFIG_DIR` (hiddenClaude.ts:180-188); several readers hardcode `~/.claude` (hive.ts:2070-2072, config.ts:724-726, the sign in terminal and connector listing in index.ts) | +| New business setup | onboarding wizard with pack choice | not reachable for a second office once `onboardingComplete` is true | + +## Step 0C. Dream state + +``` + CURRENT STATE THIS PLAN 12-MONTH IDEAL + one shared config, one office -> each business owns its settings, -> both businesses run at once, + at a time, switching leaks accounts and secrets; a new one window with a business + identity, mail and schedules business gets its own setup switcher and one Needs you + list that says which business +``` + +## Landscape (search, 2026-11-18) + +- Layer 1: small business accounting tools keep each company as its own file, with one login and a company switcher (QuickBooks Online, Xero HQ, FreshBooks, Patriot). Books are never mixed unless the owner asks for consolidation. +- Layer 2: AI agent platforms recommend one isolated workspace per company: its own credentials, data store and context, with shared orchestration code. +- Layer 3: those tools are cloud apps where a closed company still exists on a server. Here the office IS the running process on the owner's Mac, so "switch to the other company" means the other company stops working. Isolation and both running are two separate requirements, and the switcher pattern only gives the first. + +## Reality rows + +``` +REALITY: premise-table finding unverified=3 (new office inherits identity: inferred, not reproduced; two Mac users run both offices at once with fast user switching: unverified; one claude.ai account cannot hold two QuickBooks companies: unverified) src/main/index.ts:4203 +REALITY: already-done pass no commit on origin/main since 2026-11-01 adds per office config or concurrent offices (git log --grep office at cd757e20) src/main/index.ts:4203 +REALITY: surface-check pass Settings "Other offices" and "Change office folder" exist, no "Switch business" menu item exists src/renderer/src/components/SettingsModal.tsx:431-461 src/main/index.ts:3062-3104 +REALITY: binding-decisions pass gstack-decision-search returned no branch decisions; memory rules (reuse the orchestrator architecture, fix in code for every install) are kept src/main/officeFile.ts:79 +REALITY: numbers pass recentHives cap 8 [measured: src/main/fs.ts:292-307]; no other numbers claimed src/main/fs.ts:292-307 +REALITY: deferred-asks pass no linked issue; nothing deferred from an issue docs/FEATURES.md:879 +REALITY: pr-count pass no .gstack/ship-policy.json, default one PR per wave; T2 guard ships first, step one later TODOS.md:3 +``` + +## Decision ledger + +| ID and owner | Contract and evidence | Current | Proposed | Status | Exact approval and scope | +|---|---|---|---|---|---| +| BIZ-1 approach (owner) | two unrelated businesses, no mixing, both keep working; evidence above | none: switching leaks, one at a time | A) separate Mac user per business, B) per business settings with a switcher, one open at a time, C) per business settings, both running at once | approved: C | D1 answer 2026-11-18, "Both at once (recommended)": step one each business owns its settings (fixes the leak, ships alone), step two each business runs as its own office process with one window, a business switcher and a Needs you list marked by business | + +| BIZ-2 step two now or later (owner) | BIZ-1 C includes step two; mode SCOPE REDUCTION (D2) | deferred to TODOS.md | — | deferred | D3 answer 2026-11-18, "Defer to TODOS.md (recommended)": step two leaves this plan; direction BIZ-1 C stands | +| BIZ-3 own Claude account per business (owner) | Claude connectors hold one account per service (claude-connectors.md:4-6); app already honours CLAUDE_CONFIG_DIR (ptyEnv.ts:40) | in step one | — | approved: keep | D4 answer 2026-11-18, "Keep in step one (recommended)": a new business can choose its own Claude login, kept with the office | +| BIZ-4 Pulse keyed by a stable office id (owner) | TODOS.md:284-293; Pulse rows keyed by folder path (db.ts:214) | in step one | — | approved: keep | D5 answer 2026-11-18, "Keep in step one (recommended)": Pulse rows use the step one office id, old rows mapped from their folder | +| BIZ-5 switch uses closing time (eng review) | today's switch kills terminals at once (index.ts:4204) | kill | closing time like Close Office | settled in eng review | see Eng review ledger: BIZ-5 by D10, BIZ-7 by D11, BIZ-8 by D9 | +| BIZ-6 guard today's leaking switch (owner) | S1-1: index.ts:4203 carries the whole config into another office | in next release | — | approved: guard now, amended by D8 | D6 answer 2026-11-18, "Guard now (recommended)": a guard in the next release; D8 replaced how it detects and what a new empty office does (see OV-2) | +| BIZ-7 migration of installs with several offices (eng review) | one global config, several offices in recentHives (fs.ts:292-307) | none | only the open office gets the global settings; others get their office.json identity and empty mailboxes, schedules and grants | settled in eng review | see Eng review ledger: BIZ-5 by D10, BIZ-7 by D11, BIZ-8 by D9 | +| BIZ-8 where per office secrets, knowledge and journals live (eng review) | outside voice 6: a folder the owner may sync or copy breaks encryption; knowledge.ts:68-73 allows a chosen store path | move into the office folder | keep in userData, namespaced by office id | settled in eng review | see Eng review ledger: BIZ-5 by D10, BIZ-7 by D11, BIZ-8 by D9 | +| OV-1 verify the Mac user path first (owner) | outside voice 1 and 8: deferred C delivers B (closed business stops); A's "both running" is unverified and S effort; S1-1 not reproduced | not planned | A) include: before step one, test two Mac users with both apps running and reproduce S1-1; if both run, document a Mac user per business as the interim for owners who need both working | approved: include | D7 answer 2026-11-18, "Include (recommended)": test two Mac users with both apps running for a day and reproduce S1-1 before step one; document the interim only if both keep working | +| OV-2 how the guard detects another business (owner) | outside voice 3: offices most at risk have no office.json (backfillOfficeRecord refuses, officeFile.ts:79-85); names drift; per office setup needs the split | D6: compare office.json business; new empty office runs setup | — | approved: apply | D8 answer 2026-11-18, "Apply this change (recommended)": the guard detects another business by team (reuse configMatchesRegistry, officeFile.ts) and refuses "Start a new, empty office" while settings hold a business, pointing to the interim; this replaces D6's detection and its "runs setup" part | + +Mode: SCOPE REDUCTION, chosen in D2 (2026-11-18, recommended option). Proposed minimum core (kept unless a row above says otherwise): each business owns its settings, accounts, secrets and knowledge; a new business gets its own setup; a visible Switch business item stops one office and opens the other. + +## Answered: BIZ-1 (D1, "Both at once (recommended)") +Commitment comparison: + +```text +Commitment | Source/approval or pending | Current | A Mac user each | B switcher | C both at once +Business data never mixes | the ask | no (leaks) | yes, by the OS | yes, by the app | yes, by the app +Both businesses keep working | the ask ("running two") | no | yes (unverified) | no, closed one stops | yes +Own Claude account and connectors | pending (BIZ-3) | shared | yes, automatic | optional | optional +Owner sees both in one place | pending | no | no, log in/out | one at a time | yes +Fixes today's leaking switch | Section 1 finding | no | no, separate fix | yes | yes +Effort | estimate | | S | L | XL (L of it is B) +``` + +Question: D1 — BIZ-1: How should one owner run two unrelated businesses, such as a bakery and a real estate agency? +Project: Don't Be Michael, an office of AI agents on the owner's Mac. ELI10: today the app keeps each business's name, mailboxes, schedules and logins in one shared settings file, and only one office runs at a time. Switching to a second office carries the first business's settings across, so the bakery's agents could introduce themselves as the real estate agency. Stakes: a wrong company name or the wrong QuickBooks company in front of a customer, and one business going quiet while the owner looks at the other. Recommendation: C, built in two steps, because the businesses share nothing and both have customers waiting, so they must be isolated and both keep running; step one (each business owns its settings) is the same work as B and fixes today's leak on its own. Note: options differ in kind, not coverage — no completeness score. +Header: Approach +A) Separate Mac user each +The owner makes a second macOS user for the second business; the app documents it and blocks the leaking switch. Effort S, risk low, reuses everything; verify by running two Mac users side by side. ✅ Full isolation by the operating system, Claude account and connectors included, with almost no code. ✅ Ships this week as help text plus a guard on the switch. ❌ The owner logs in and out to see each business, and notifications from the other one are not seen. +B) Switcher, one open at a time +Each office owns its settings, accounts and secrets; a new business runs setup; a Switch business menu item stops one and opens the other. Effort L, risk medium, reuses office.json, recentHives and changeHome; verify with a two office switch test. ✅ Isolation inside one app, with a clear switch the owner understands. ✅ Fixes today's leak for every install. ❌ The closed business stops: its mail, schedules and agents wait until the owner switches back. +C) Both at once (recommended) +Step one is B's settings split; step two runs each business as its own office process, with one window, a business switcher and a Needs you list marked by business. Effort XL, risk high, reuses the hive and Michael per office; verify with two offices running a day side by side. ✅ Both businesses keep working, which is what running two businesses means. ✅ Step one ships alone and already fixes the leak. ❌ Largest build: two Michaels at once doubles Claude usage, and a per process app changes launch, the single instance lock and updates. + +## Current scope (after Step 0) + +- Mode: SCOPE REDUCTION (D2). Approach: BIZ-1 C (D1), built in two steps. +- Accepted (step one): each business owns its settings, accounts, secrets and knowledge; a new business runs its own setup; a visible Switch business item stops one office and opens the other; a new business may use its own Claude login (BIZ-3, D4); Pulse keys by a stable office id (BIZ-4, D5). +- Deferred: step two, both businesses running at once (BIZ-2, D3). +- Rejected: none. + +## Review sections (strategy-only depth) + +### Section 1: Architecture + +``` + TODAY STEP ONE + userData/config.json (ONE) userData/config.json install only: window, language, + ├ business identity, team Claude Code update, harnessHome, + ├ mailboxes, grants, connectors known offices (id, name, folder) + ├ schedules, integrations, research /office.json becomes the live settings of + └ harnessHome, recentHives (per business) that business: identity, team, + userData/integration-secrets.json (ONE) mailboxes, grants, connectors, + userData/knowledge/ (ONE) schedules, integrations, research + userData/mail-*.json, broker journal (ONE) /private/ secrets, knowledge, mail and + ~/.claude (ONE login, ONE connector set) broker journals, dock keys + /claude/ optional own Claude login + (CLAUDE_CONFIG_DIR), BIZ-3 + app process (one office at a time, unchanged in step one) + └ reads install config + the open office's settings; nothing business-shaped is global +``` + +- **Also business shaped (outside voice 7):** the job, standing and trust check folders (index.ts:1221-1291), failures.jsonl, the Pulse database rows, mail and broker journals, owner dock keys and renderer localStorage. The field by field proof covers every per install file in userData, not only config.ts. +- **Boundary rule:** anything that names a customer, an account, a schedule, a team member or the business belongs to the office; only how the app itself behaves is install-wide. Implementation owner must prove the split field by field (config.ts:229-393 is the list to sort). +- **Coupling:** reads of `cfg.businessName`, `cfg.mailboxes`, `cfg.missions` and the rest are spread through src/main/index.ts (e.g. 616-619, 700, 1746-1760, 3528-3570). The split must go through one accessor for "the open office's settings", or a missed reader keeps leaking. Implementation owner must prove every reader moved (a test that the global config holds no business field after migration). +- **Single point of failure:** the office record. Today office.json is a mirror nobody reads back (index.ts:4110-4114); in step one it is the source of truth, so a corrupt or missing file loses the business's settings. Needs the same atomic write and backup the roster already has (roster-backups, homeFolder.ts:63). +- **Rollback (corrected after outside voice 5):** the migration removes business fields from the live config, which the new version never reads again, and keeps a frozen copy of the old config next to it for one release, so a downgraded build can be pointed back at it. Decided as a small mechanic under the owner's plan review rule; owner: eng review to confirm the downgrade path. +- **Switching:** today's switch kills terminals at once (index.ts:4204) after stopping services (index.ts:4179-4185). Switch business must use closing time like Close Office, so a member mid task finishes or hands off instead of being cut. Pending row BIZ-5, owner eng review. + +**Finding S1-1 (CRITICAL, shipped today):** the existing "Start a new, empty office here" and "Other offices, Open" paths carry one business's identity, mailboxes, grants and schedules into another office (index.ts:4203). Pending decision BIZ-6. + +### Section 2: Error and rescue map (capability rows) + +``` + CAPABILITY | WHAT CAN GO WRONG | USER SEES (required) + -------------------------------|------------------------------------------------|---------------------------------- + Settings migration (first run) | crash midway; two offices in recentHives | each office opens with its own + | both claim the one global config | name, or a setup card, never the other's + Open office settings | office.json missing, corrupt, older version | "This office's settings could not be + | | read" with restore from backup + Switch business | member mid task; other office folder gone; | closing time progress; the missing + | relaunch fails | office screen (OfficeFolderMissing.tsx) + New business setup | owner quits halfway | the half set office reopens setup, + | | never runs with the old business's data + Own Claude login (BIZ-3) | not signed in; plan detection reads the wrong | "Sign in to Claude for " + | .claude.json (claudeAccount.ts:17); sign in | card in that office only + | lands in the owner's main Keychain entry | (implementation owner must prove with + | (undocumented env, hiddenClaude.ts:180-188) | a probe before building BIZ-3) + Secrets per office | mailbox id collides across offices | each office's mailbox keeps its own + | (secret key mail:, mail.ts:2157-2181) | password + Pending mail proposals | bakery proposal approved while agency is open | proposals belong to their office and + | (global mail-proposals.json, index.ts:1198) | only show and send there +``` + +Rescue rule: none of these may fall back to "use the other office's value". Implementation owner must prove each row with a failing case. + +### Section 3: Security and threat model + +| Threat | Likelihood | Impact | Mitigated by plan? | +|---|---|---|---| +| One business's agent sends mail as the other business (shared mailboxes and identity) | Med (any owner who uses the switch) | High | Yes in step one; today no (S1-1) | +| Secrets readable across offices (one integration-secrets.json) | Med | High | Yes: secrets move under the office; keys namespaced by office id | +| Claude connector shares one QuickBooks company across businesses | High for two business owners | High | Yes when the owner gives the business its own Claude login (BIZ-3); otherwise connectors stay off for the second business | +| Company knowledge from one business retrieved by the other's agents (global knowledge store, knowledge.ts:68-73) | Med | High | Yes: knowledge moves under the office | +| Prompt injection from one business's mail reaching the other's Michael | Low | Med | Yes, follows from separate mailboxes and memory | +| Deep link or hire link lands in the wrong business | Low | Low | Lands in the open office; the link screen must name the business it will join | + +Audit: switching, migration and setup of a new business write a line to each office's log (hive log.jsonl) naming the office id. + +### Section 4: Data flow and interaction edge cases + +``` + INPUT (Switch business) -> CHECK (target office exists, has settings) -> CLOSE (closing time) -> PERSIST (harnessHome) + -> RELAUNCH -> LOAD (install config + office settings) -> OUTPUT (floor of that business) + shadow: target folder deleted -> missing office screen; settings corrupt -> restore card; closing time + times out -> say which member was cut; relaunch fails -> the office it came from reopens +``` + +| Interaction | Edge case | Handled? | How (required) | +|---|---|---|---| +| Switch business | double click | gap | one switch at a time, button busy during closing time | +| Switch business | Ask me card half answered | gap | the draft stays with its office (renderer state is cleared on switch today, localState.ts:9-34) | +| New business setup | owner picks the same business folder as the first business | gap | refuse: two businesses never share a business folder | +| New business setup | owner connects a mailbox the other business already has | gap | refuse with "this address belongs to " (mail.ts:2161-2164 already refuses per install) | +| Closed business | mail arrives, schedules come due | known | waits until it is opened, like the app closed today; say so on the switcher | +| Migration | owner has several offices, only one matches the global config | gap | pending BIZ-7 | + +### Section 5: Code quality + +- The split must remove business fields from config, not copy them; two live copies is how the leak happens again. +- Reuse `office.json`, `officeRecord.ts` and `syncOfficeRecord` rather than a new store (memory rule: reuse the orchestrator architecture). +- Over-engineering to avoid: no per office process, IPC layer or office manager service in step one (that is step two). + +### Section 6: Tests (capability level) + +| New thing | Test type | Must assert | no_claim | +|---|---|---|---| +| Settings split | unit | after migration the global config holds no business field; the open office's settings equal the old global values | real Electron relaunch (unit only) | +| Switch between two offices | integration | office A's name, mailboxes, schedules and grants never appear in office B after a switch and back | live mail servers (fixtures) | +| New business setup | integration | a new office starts with no identity, team, mailbox, schedule or grant, and runs setup | packaged app UI | +| Secrets per office | unit | the same mailbox id in two offices keeps two passwords | Keychain (file store) | +| Own Claude login | unit | the office's Claude folder drives plan detection and terminal env | real Claude sign in | +| Pulse office id | unit | rows keyed by folder map to the office id; moving the folder keeps history | none beyond protects | +| Hostile QA | integration | switch during closing time, switch to a deleted folder, corrupt office.json | | + +Friday 2am test: two offices with different businesses, a schedule and a mailbox each, switched back and forth five times; each Michael's first message names its own business. + +### Section 7: Performance + +No issues found. Reading one office settings file at launch replaces reading one global file; switch cost is dominated by closing time, which exists today. + +### Section 8: Observability + +- Each office log records migration, switch out, switch in and setup completion with the office id and app version. +- The failure report (auto report failures) must include the office id, never the business name or mailbox addresses. +- Gap: today a leak would be silent. Step one adds a launch check that the office settings' business name matches the office record, and reports a mismatch. + +### Section 9: Deployment and rollout + +- Migration runs once at launch, before any service starts, with a backup of the global config kept next to it. +- Order: write the office settings, verify by reading back, write the frozen copy, then remove the business fields from the live config. A crash between steps leaves both, and the next launch resumes. +- Windows ships every release (memory rule): migration paths must be case insensitive for folder matching (officeFile.ts already does this). +- Rollback: the frozen copy (Section 1). The live config never holds business fields again. + +### Section 10: Long-term trajectory + +- Reversibility 2/5: once settings live in the office, going back means another migration. +- Step two (both at once) depends on step one's boundary being complete; any global business field left behind becomes a cross-business bug when two offices run in one app. +- Debt paid: TODOS.md:284-293 (Pulse office id) closes. + +### Section 11: Design and UX + +``` + My Office menu -> Switch business -> list: Bakery (open), Realty Agency (paused since 9:12) + | | + | [Open] -> closing time for Bakery -> Realty floor + +-> [Add a business] -> setup (pack, name, city, team, own Claude login?) +``` + +| Feature | Loading | Empty | Error | Success | Partial | +|---|---|---|---|---|---| +| Switch business | closing time progress | only one business: list shows Add a business | folder gone: missing office screen | other floor opens | a member cut by timeout is named | +| New business setup | existing setup steps | | Claude sign in fails: retry card | floor opens | half done setup resumes | + +- The window title and the floor's business name plate must always show which business is open (floor-business-name.md exists). +- Less verbose UI rule: the switcher shows names and one state word; explanations go behind an InfoTip. +- Consider running /plan-design-review for the switcher and the second business setup before building. + +## Outside voice (Claude subagent, native; Codex not run) + +Codex was not run: the owner's standing rule limits Codex to adversarial diff review. A Claude Plan subagent gave an independent read (no outside coverage credit). Eight findings, dispositions: + +| # | Severity | Finding | Disposition | +|---|---|---|---| +| 1 | Critical | Deferred C builds B; the Mac user path may meet both needs at S effort and was never tested | D7: include the test before step one (OV-1) | +| 2 | High | BIZ-3 rests on undocumented `CLAUDE_SECURESTORAGE_CONFIG_DIR`; several readers hardcode `~/.claude` | factual correction in 0B and Section 2; probe required before BIZ-3 (T4); second plan cost was in D4's option text | +| 3 | High | Guard by business name misses offices with no record and false alarms on renamed businesses | D8: detect by team, refuse a new empty office (OV-2) | +| 4 | High | Migration of several offices is the crux and has no data | kept pending for eng review (BIZ-7) with a required count of installs with more than one recent office, if any telemetry exists; otherwise the owner's own installs | +| 5 | Medium | Rollback text contradicts "remove, not copy" | corrected: frozen copy for downgrade, live config never holds business fields | +| 6 | Medium | Moving secrets into a syncable folder adds exposure | pending for eng review (BIZ-8) | +| 7 | Medium | Business shaped files beyond config.ts not listed | added to Section 1 | +| 8 | Low | S1-1 not reproduced | covered by OV-1 (reproduce first) | + +## Approval readiness + +Approval readiness: PASS. Checked rows: BIZ-1 (D1), BIZ-2 (D3, deferred), BIZ-3 (D4), BIZ-4 (D5), BIZ-6 (D6 amended by D8), OV-1 (D7), OV-2 (D8). Pending, not approved and not in tasks as decisions: BIZ-5, BIZ-7, BIZ-8 (owner: /plan-eng-review). + +## NOT in scope + +- Both businesses running at once (step two): deferred by D3, in TODOS.md "Both businesses running at once in one app". +- Combined views across businesses (a morning summary, one Ask me across both): not proposed in SCOPE REDUCTION; belongs with step two. + +## What already exists + +See Step 0B. Reused: the office folder and office.json record, recentHives and the Settings office list, changeHome's stop and relaunch, `configMatchesRegistry` for the guard, Pulse's office column, Claude Code's `CLAUDE_CONFIG_DIR`, the missing office screen. + +## Dream state delta + +After step one the businesses never mix, but only one works at a time. If OV-1 proves the Mac user path, owners who need both working have an interim. Step two (deferred) closes the rest of the gap to the 12 month ideal. + +## Failure modes registry (capability rows) + +``` + CAPABILITY | FAILURE MODE | RESCUED? | TEST? | USER SEES? | LOGGED? + ----------------------------|--------------------------------------------|----------|---------|--------------------------------|-------- + Today's Settings switch | carries one business into another office | N | N | Silent <- CRITICAL GAP (shipped) | N + Guard (BIZ-6, OV-2) | office has no record, team differs | planned | planned | plain stop message | planned + Settings migration | crash midway, several offices | planned | planned | own name or setup card | planned + Office settings read | office.json corrupt or missing | planned | planned | restore from backup card | planned + Switch business | member mid task | pending BIZ-5 | unknown | closing time progress | planned + Own Claude login (BIZ-3) | sign in lands in the main Keychain entry | unknown | probe T4 | wrong account, silent if missed | unknown + Per office secrets | mailbox id collides | planned | planned | each office keeps its password | n/a + Mail proposals | approved in the wrong office | planned | planned | shown only in their office | planned +``` + +Capability rows: 8. Critical gaps: 1 (the shipped switch; the guard closes it). + +## Diagrams + +System architecture (Section 1), data flow with shadow paths (Section 4), user flow (Section 11). No new state machine beyond the switch flow; deployment order and rollback are in Section 9 as steps. + +## Stale diagram audit + +The plan touches no file with an ASCII diagram yet (strategy-only). HIVE.md's folder layout (HIVE.md:66-84) must be updated when step one moves files into the office. + +## Reality check + +``` +REALITY: premise-table finding unverified=3 (new office inherits identity: inferred, reproduce in T1; two Mac users run both offices at once: unverified, T1; per office Claude sign in: unverified, T4) src/main/index.ts:4203 +REALITY: already-done pass no commit on origin/main since 2026-11-01 adds per office config or concurrent offices (git log --grep office at cd757e20) src/main/index.ts:4203 +REALITY: surface-check pass Settings "Other offices" and "Change office folder" exist, no "Switch business" menu item exists src/renderer/src/components/SettingsModal.tsx:431-461 src/main/index.ts:3062-3104 +REALITY: binding-decisions pass gstack-decision-search returned no branch decisions; memory rules (reuse the orchestrator architecture, fix in code for every install) are kept src/main/officeFile.ts:79 +REALITY: numbers pass recentHives cap 8 [measured: src/main/fs.ts:292-307]; no other numbers claimed src/main/fs.ts:292-307 +REALITY: deferred-asks pass no linked issue; nothing deferred from an issue docs/FEATURES.md:879 +REALITY: pr-count pass no .gstack/ship-policy.json, default one PR per wave; T2 guard ships first, step one later TODOS.md:3 +PLAN_REALITY: phase=ceo rows=7/7 missing=none unverified=3 verdict=complete +``` + +## Implementation Tasks + +Synthesized from this review's findings (strategy-only: next research, verification and design actions). + +- [ ] **T1 (deferred 2026-11-19, human: ~2h / CC: ~30min)** (code check done; owner: the leak reproduction is dropped, since the guard closes it; the two Mac user run waits until step two is decided or an owner asks for two businesses before step one ships) — verification — Reproduce the Settings leak and test two Mac users running the app at once + - Surfaced by: Section 1 S1-1; outside voice 1 and 8 (OV-1, D7) + - Files: none (live test from a second Mac user) + - Verify: write down what each office's Michael says first after the switch; leave both Mac users running a day and check both offices' schedules fired +- [x] **T2 (P1, human: ~4h / CC: ~20min)** (built 2026-11-19, see T1 and T2 progress) — src/main — Guard the Settings switch by team and refuse a new empty office while settings hold a business + - Surfaced by: BIZ-6 (D6) amended by OV-2 (D8) + - Files: src/main/index.ts (config:changeHome), src/main/officeFile.ts (configMatchesRegistry), src/renderer/src/components/SettingsModal.tsx, src/renderer/src/i18n/locales/en.json, a test under test/ + - Verify: a test switching between two offices with different teams, with and without office.json, is refused; the same office reopens +- [x] **T3 (P1, human: ~3h / CC: ~20min)** (done 2026-11-19, see T3 below) — design — List every business shaped field and file for step one + - Surfaced by: Section 1 boundary rule; outside voice 7 + - Files: src/main/config.ts, src/main/index.ts, files under userData + - Verify: the list is in this doc and each item has a home (office or install) +- [x] **T4 (P1, human: ~2h / CC: ~15min)** (probed 2026-11-19 on Claude Code 2.1.328, see T4 below; a live second account sign in is an optional owner check) — verification — Probe a separate Claude sign in per office folder + - Surfaced by: BIZ-3 (D4); outside voice 2 + - Files: none (probe with Claude Code and two config folders) + - Verify: two folders keep two signed in accounts and two connector lists; note the Claude Code version +- [x] **T5 (P1, human: ~1h / CC: ~15min)** (done 2026-11-18: the eng review below settled BIZ-5 by D10, BIZ-7 by D11 and BIZ-8 by D9) — review — Run /plan-eng-review on step one and settle BIZ-5, BIZ-7 and BIZ-8 + - Surfaced by: pending rows BIZ-5, BIZ-7, BIZ-8 + - Files: docs/designs/separate-businesses.md + - Verify: the eng review report clears those rows + +## T1 and T2 progress, 2026-11-19 + +### T2: the guard (built, not committed) + +- `officeSwitchGuard(cfg, newHome)` in src/main/officeFile.ts answers ok, otherBusiness or newBusiness. Before setup finishes, anything opens. An office opens when its registry has this team in the same folders (configMatchesRegistry, the backfill check), or when its office.json names the same business folder (covers a registry that drifted). A business with no team yet is told apart by office.json, or by members working outside the office folder; with neither, it opens. A folder with no office is newBusiness. Names never decide. +- `config:changeHome` asks it for every open (mode fresh) before it makes or saves anything, and returns `guard` with the refusal. A move is the same office and is never asked. +- Settings (Open another office, Change office folder) and the "We can't find your office" screen show OfficeGuardNotice: the title, an info tip with the why, one line and OK. +- Lines: "That office belongs to another business" / "It can't be opened from here yet." and "A new business can't start from here yet" / "To use a different folder for this business, choose Move my office here." The first line changes to "Open it from its own Mac user for now." only if the T1 live run passes. +- Test: test/office-guard.test.cjs (7 cases, with and without office.json, same name with another team, no team yet, drift, and a check that the switch asks before it touches anything). It fails when the guard is removed. Full suite: 4025 pass, 0 fail. +- Not guarded: "Start over here" on the missing office screen. It restarts the same business in its own folder, so it carries nothing to another business. + +### T1: what the code says about two Mac users + +| Question | Answer from the code | +|---|---| +| Does the second Mac user's app open? | Yes. The single instance lock (index.ts:2832) lives in each Mac user's own app data, so it locks per user. | +| Do the two apps fight over a port? | No. The integration broker and the usage listener bind 127.0.0.1 on a port the system picks (integrationBroker.ts:176, called with none at index.ts:6619; telemetry.ts:300). The hook socket sits in the per user temp folder (hive.ts:1008). | +| Claude login and connectors | Each Mac user has its own ~/.claude, so each business gets its own Claude login and its own Gmail and QuickBooks connections. That is BIZ-3 for free on this path. | +| Settings | Each Mac user has its own app data, so its own config.json. No leak between them. | +| Shared | The app in /Applications. An update installed from one user replaces it for both; the other keeps running the old version until it restarts. | +| Unknown until run live | Whether a Mac user in the background (fast user switching) keeps its schedules, mail polling and keep awake going for a day. | + +### T1: the owner's live run (deferred, owner 2026-11-19) + +Not needed for step one. Step 1 below is dropped. Steps 2 to 4 run before step two is decided, or sooner if an owner asks to run two businesses before step one ships. + +Use the Demo Mac user as the second business. Nothing here touches the main office. + +1. Reproduce the leak, on 0.4.2 as installed (the guard is not in it): in the Demo user, set up a business, then a second one with Settings, Change office folder, Start a new, empty office. Write down what Michael says first in the new office (its business name, mailboxes, schedules). Expected: the first business's. +2. Two Mac users at once: in your own user keep the main office open. Switch to Demo (fast user switching, not log out), open its office, give it one schedule that fires hourly, and switch back. +3. Leave both running a day. Then check each office: did the hourly schedule fire in Demo while it was in the background, did mail polling keep going, and did either app stop or show a sign in prompt. +4. Result: if both kept working, the guard's first line becomes "Open it from its own Mac user for now." and the Mac user per business is the documented interim (OV-1). If not, the line stays as built. + +## T3: what belongs to a business, field by field (2026-11-19) + +Rule (Section 1): anything that names a customer, an account, a schedule, a team member or the business goes with the office; only how the app itself behaves stays with the install. "Office" below means `config.json` under `offices[]` (D9) for settings, and a folder or key by office id for files. + +### Settings in config.json (HarnessConfig, config.ts:217-416) + +| Goes with | Fields | +|---|---| +| Office: who the business is | businessType, businessName, businessCity, companyProfile, businessFolder, officeFolder (legacy, read once then dropped), registeredRepos (its folders) | +| Office: setup and team | onboardingComplete (each business's own setup, for the Setup not finished row, D18; "first run" becomes "no offices yet"), businessTeam, businessTeamStarted, businessTeamRetry, instructionsRewritten, firstTasksRemoved, workStyleUpdatesDecided, agentCapabilities, agentTokenCaps, autoDeliveryPausedAgents | +| Office: mail and connectors | mailboxes, quickbooksClaude, connectorsOn, connectorsSeen, connectorsMigrated, claudeConnectors (the last read of the login this office uses), mcpDefaults (legacy, feeds the connectors carry over) | +| Office: Claude account | claudeAuth (account or API key, a login like any other, BIZ-3), planPriceMonthly (that account's price) | +| Office: schedules | missions, scheduleRequests, missionsOwnersMigrated, opsStandupSeeded, foundationsCheckSeeded, standupFocusSeeded, heartbeatSeeded (seed guards follow the schedules they guard, so a new business gets its own standup) | +| Office: Research and data | research, dataClasses | +| Office: knowledge and memory | knowledgeGraph (its rootPath override is a business folder), knowledgeOnSeeded, knowledgeOnNoticeSeen, embeddingModel (the palace in the office folder is built with it) | +| Office: owner messages | ownerAnswerKeys, ownerDockKeys (legacy, already moved to a file) | +| Office: integrations and budget | integrations (metadata; secrets below), costCapTokens, costCapUsd (deprecated, follows costCapTokens) | +| Install: how the app behaves | harnessHome (becomes the open office's id), recentHives (becomes the known offices list), audience, autoMode, maxTurns, circuitBreaker, notifications, strongKeepalive, autoUpdate (deprecated), terminalTheme, tvShowOffices | +| Install, by the rule, open to revisit after T4 | godProvider, godModel, defaultModel, defaultCommand, providerDefaultModels. Which models exist depends on the Claude account; if T4 makes a login per office real, these may follow the login. Not a step one blocker. | + +Count: all 60 fields placed: 44 with the office, 11 with the install, 5 with the install pending T4. + +### Files in the app's data folder (~/Library/Application Support/dontbemichael) + +| File | Goes with | Note | +|---|---|---| +| config.json | split | install part stays; business part under offices[] | +| integration-secrets.json | office, keyed | one encrypted file, entries keyed by office id: `mail:`, `apikey:anthropic`, integration secretRefs | +| knowledge/ | office | userData/knowledge/, unless the office's own rootPath override is set | +| mail-send-journal.json, broker-write-journal.json, mail-proposals.json | office | journals and approvals name customers and accounts; split by office id | +| owner-dock-keys.json | office | | +| pastes/ | office | **Step one must split it.** The launch sweep keeps only pastes the open office's queues still name (index.ts:6574), so with two offices it would delete pastes the closed one still needs. | +| opened-attachments/ | office | that business's mail attachments | +| job-check/, standing-check/, trust-check/, run-compare/, case-study/ | office | empty working folders, but their Claude conversations hold the business's job text; per office so a reset of one office sweeps only its own (E3) | +| harness.db: telemetry_*, cost_ledger, owner_notes | office, keyed | already have an `office` column, keyed by folder; re-key to office id (E5) | +| harness.db: kv (window.bounds) | install | | +| failures.jsonl | install, tagged | app failure reports; tag each with the office id | +| hero.json, model-catalog.json, updater.log, last-run-version | install | remote copy and app version | +| Renderer saved state (localStorage `cth.*`) | office | cleared on a switch today; step one keys it by office id so a business's view comes back with it | + +### Already in the office folder (nothing to do) + +The hive (registry, tasks, log), the palace, roster.json, office.json and Research's desk all live under harnessHome today. + +### Outside both (T4) + +~/.claude: the Claude sign in, its connectors (Gmail, QuickBooks) and the Claude conversations of every member and check. A separate login per office is T4. + +## T4: a separate Claude login per office (probed 2026-11-19, Claude Code 2.1.328) + +**Result: it works, and through the documented setting.** Each Claude config folder gets its own login. BIZ-3 does not rest on the undocumented variable for members; only the app's hidden checks need it, as they do today. + +### What the probe showed + +`claude auth status` (read only; no sign in was started, the account email was not printed): + +| Run | Signed in? | +|---|---| +| No CLAUDE_CONFIG_DIR (today's setup) | yes, the owner's account | +| CLAUDE_CONFIG_DIR = a new folder A | no: A has its own login, empty | +| A, with CLAUDE_SECURESTORAGE_CONFIG_DIR = "" | yes, the owner's account | +| A, with CLAUDE_SECURESTORAGE_CONFIG_DIR = ~/.claude written out | no | +| A new folder B, with CLAUDE_SECURESTORAGE_CONFIG_DIR = A | no (A has no login yet), so B reads A's entry | + +Why, from the Claude Code 2.1.328 binary: the login lives in the Keychain under `Claude Code-credentials`, plus `-` and the first 8 hex characters of sha256 of the config folder path whenever CLAUDE_CONFIG_DIR is set. CLAUDE_SECURESTORAGE_CONFIG_DIR, when set, picks the folder that name is made from, and an empty value means the default entry. So: + +- Office members run with `CLAUDE_CONFIG_DIR = `: a documented setting, its own login, its own `.claude.json`, plugins, local connectors and conversations. +- Hidden checks (isolated folders, hiddenClaude.ts:203-204) keep borrowing a login with `CLAUDE_SECURESTORAGE_CONFIG_DIR = `. That variable stays undocumented; if Claude drops it the checks fail closed (they stop at sign in), as today. +- The first business keeps today's login: no CLAUDE_CONFIG_DIR, and an empty CLAUDE_SECURESTORAGE_CONFIG_DIR for its checks. Writing ~/.claude out in full does **not** reach that login. +- Gmail, QuickBooks and the other claude.ai connectors belong to the account, so a second login brings its own list. + +### What this changes in step one (follows D9, no new choice) + +- **The office's Claude folder goes in the app's data folder, keyed by office id** (`userData/offices//claude`), not inside the office folder as Section 1's diagram drew it. The login name is a hash of the folder's path, so an office folder that is moved or opened from a synced copy would lose its login. The app data folder is also already outside every agent's reach (folderAccess.ts:323 refuses edits under ~/Library). +- A business uses its own Claude folder only when the owner chose "A different Claude account" in Add a business (DT, frame 4). Otherwise it shares the first business's login, as D4 allows. +- A second account is a second Claude plan (D4). + +### Readers E6 routes through one claudeHome() + +| Reader | Today | +|---|---| +| transcript.ts:47, 52 (projects, history) | follows CLAUDE_CONFIG_DIR | +| claudeAccount.ts:17 (plan) | follows CLAUDE_CONFIG_DIR | +| hooks.ts:1384, index.ts:3537 (projects folder walls) | follow CLAUDE_CONFIG_DIR | +| hiddenClaude.ts:204 (checks' login) | follows CLAUDE_CONFIG_DIR, empty for the default | +| config.ts:725 ensureClaudeGlobalPermissions | **hardcoded ~/.claude/settings.json** | +| config.ts:755 updateClaudeJson (trust and API key approvals) | **hardcoded ~/.claude.json**; with a config folder set, Claude reads `/.claude.json` instead | +| hive.ts:2072 ownerPluginsOffForSession | **hardcoded ~/.claude/settings*.json** | + +The three hardcoded readers are wrong today too for an owner who exports CLAUDE_CONFIG_DIR: the approvals land in a file Claude does not read, and the agent stops at the trust question. E6 fixes them for both cases. + +### Optional owner check (5 minutes, not needed for step one) + +Proves two logins side by side on this Mac. Any account works, even the same one. + +1. `CLAUDE_CONFIG_DIR=~/dbm-t4 claude auth login`, and sign in in the browser. +2. `CLAUDE_CONFIG_DIR=~/dbm-t4 claude auth status --text` shows that account; `claude auth status --text` still shows yours. +3. Clean up: `CLAUDE_CONFIG_DIR=~/dbm-t4 claude auth logout`, then delete ~/dbm-t4. + +## E1: the office id and the settings accessor (2026-11-19) + +- office.json gains `id` (a random UUID, made once by `ensureOfficeId`). Every later save keeps it (`syncOfficeRecord`). A record holding only the id describes no business: setup still sees no office to continue, and the launch backfill still writes the description (`describesBusiness`). An id read from a copied or synced record is checked (`isOfficeId`), so it is never a path. +- src/main/officeSettings.ts holds T3's two lists, `BUSINESS_KEYS` (44) and `INSTALL_KEYS` (16 plus `offices`). The build fails when a config field is in neither list or in both. +- `currentOfficeId()` reads office.json's id, else the `offices` entry last opened from this folder, so a lost office.json keeps its settings. `officeSettings()` gives that business's saved settings over the defaults (a business with none starts setup, with no mailboxes). `updateOfficeSettings(patch)` saves only business keys, and refuses (saving nothing) when no office is open or it has no id. `installConfig()` gives the install keys only. +- Nothing reads through it yet, so the app behaves as before. +- **Moved to E3:** `readConfig()` returning a type without business fields. Switched alone it breaks every reader, and the app would not run until E3 moved them; switched in E3, its compile errors are the list of readers still to move. +- Test: test/office-settings.test.cjs (8 cases: one home per field, the id kept through saves, backfill of an id only record, unsafe ids, two offices kept apart, a lost office.json, settings with nowhere to go, the pure helpers). Full suite 4033 pass, 0 fail. + +## E2: moving the settings at launch (2026-11-19) + +- `migrateToOfficeSettings()` in src/main/officeSettings.ts. Order: give each known office (the open one and the recent ones) its id; keep config.json as `config.before-offices.json` (the first copy is never overwritten); write `offices[]` for every office not already there; read it back; then one write removes the business fields from the top level and sets `officesMigrated: 1`. A stop before that last write leaves the top level as it was, and the next launch runs again, keeping entries already written. +- Who gets what (D11): an office is this business when the T2 guard would open it with these settings (team match, or the same business folder in office.json, or a business with no team and nothing to tell it apart), and it gets every business setting. Another business with an office.json gets its identity and team, `setupNoticePending`, and no mailboxes, grants, connectors or schedules of this one. An office with nothing to go on gets nothing and runs setup. While setup is unfinished, the open office gets what was typed so far. +- It waits, changing nothing, while no office is open yet or the open office's folder is missing (the "We can't find your office" screen), and runs once it is there. +- New fields: `officesMigrated` (install) and `setupNoticePending` (business; the notice itself is UI work in E3 and the design tasks). +- **Not called at launch yet.** Its last step empties the top level, and every reader still reads there until E3, so running it now would leave the app with blank settings. E3 adds the launch call (before any service starts) in the same change that moves the readers, and splits `DEFAULTS` so `readConfig()` stops filling business defaults at the top level. +- Test: test/office-settings-migration.test.cjs (7 cases: the one office regression, field by field; several offices by team match with a moved copy, another business, an unknown office and a deleted folder; no team; unfinished setup; waiting; resume after a stop; the pure rule). It fails when every office is given the settings. Full suite: 4039 pass; proc-kill.test.cjs failed once under load and passed alone twice (unrelated timing). + +## E3, part 1: every reader and writer through the open office (2026-11-19) + +- **Changed from the eng review's plan, same goal.** Instead of moving each of the 179 `readConfig()` and 53 `writeConfig()` callers and switching readConfig's type, the routing sits inside those two functions (config.ts). Before the move they work as today. After it, `readConfig()` gives the install fields from the top of config.json and the business fields from the open office's entry over the defaults, never another office's; `writeConfig()` saves business fields into the open office's entry (the folder being opened, when the save also sets harnessHome) and install fields at the top. No caller can be missed, which is what the type switch was for, so the type switch is dropped. `offices` is never part of what readers or the renderer see. +- Shared key logic moved to src/main/officeKeys.ts so config.ts and officeSettings.ts do not import each other. +- Launch: `migrateToOfficeSettings()` then `adoptOpenOffice()`, before the office check and `bootstrapHiveServices()`. `adoptOpenOffice()` gives the open office its id and entry, lets the entry follow an office moved in Finder or found again, and gives a duplicated folder its own id with a copy of the settings. A Settings move copies office.json and moves the entry with it (`officesAfterMove`). +- **Behind `DBM_OFFICE_SETTINGS=1` until step one is complete.** The move is one way, and a dev run shares config.json with the installed app, which cannot read moved settings. A config already moved keeps working without the switch. To try it, use the Demo Mac user. The last step one task removes the switch. +- The T2 guard stays until switching goes through closing time (E4) and Add a business exists (design tasks). +- Not yet: secrets, knowledge, journals, dock keys, pasted images, attachments and check folders by office id; a factory reset that erases only the open business (today's `resetConfig()` still erases every entry, as it erases everything today); the setupNoticePending notice. These are E3's next parts. +- Test: test/office-config-routing.test.cjs (9 cases: unchanged before the move; reads and saves after it, clearing a field, the token cap; another office; a save that also opens a folder, and setup adopting its id; a Settings move and the backup left behind; a Finder move; what a save announces; a retired schedule in an office; the launch switch). It fails when reads ignore the office. Full suite 4048 pass, 0 fail. + +## E3, part 2: secrets, files and the factory reset by office (2026-11-19) + +- **Secrets:** the secret store (integrations.ts) keeps each business's passwords and keys under `@/` once settings are per office, inside the same get, set, has and delete functions every caller uses. Two businesses with a mailbox or integration of the same id keep two passwords, and one never reads the other's. The move copies every saved secret (still encrypted) to each office of this business; the keys from before the move stay in the file for a downgrade and are never read after it. +- **Files:** `officeDataPath(name)` (config.ts) gives `userData/offices//` for the open office after the move (`userData/` before; `offices/none` with no office open). Used for the mail send and broker write journals, mail approvals, dock keys, pasted images, the check folders and the default knowledge store. The move renames the existing journals, approvals, dock keys, pasted images and knowledge into the open office's place (a knowledge store the owner placed elsewhere stays). Opened attachments stay shared: they are cleared at every quit, and a switch quits. +- **The launch move now runs as the main process starts**, right after the data folder is set, so the journals and approvals open in the office's place. Still behind `DBM_OFFICE_SETTINGS=1`. +- **The open office is always this business** in the move: the settings at the top are the ones it runs on. (Fixed from E2, where an office whose team had drifted could have received only its identity.) +- **Factory reset, after the move, erases only the open business:** its place in the app's data folder, its secrets (`deleteOfficeSecrets`), its rows in every table with an office column (`persist.eraseOffice`, OFFICE_TABLES), its office folder entries as before, and its settings entry (`forgetOffice`). The shared database, secrets file, install settings and every other business stay. Before the move it erases everything, as today. +- **Downgrade:** the frozen config copy, plus the knowledge store and journals, which now sit under `offices//`; a downgrade needs them moved back to the data folder. +- Not yet: the setupNoticePending notice (UI), Pulse's office column by id (E5), switching through closing time (E4), a login per office (E6). +- Test: test/office-data.test.cjs (8 cases: unchanged before the move; the move keeps secrets and files and the old keys; another business never reads this one's password; a knowledge store placed elsewhere; a stopped move; a one business reset; the office tables; the reset wiring). factory-reset.test.cjs now also checks every business file named through officeDataPath is erased by a reset. + +## E3, part 3: the setup notice and screen state (2026-11-19) + +- **Finish setting up this business:** a one time card on Ask me, from the app, for a business whose identity came from its office.json in the move (`setupNoticePending`). It says its mailboxes, schedules and connections were another business's and did not come with it. Got it clears it; Open Settings clears it and opens Connections. It counts with the reports and keeps Ask me from showing all clear. +- **Screen state per business:** the renderer's saved state (`cth.*`: cards, selection, queues, floor view) is stamped with the office id. The preload checks it before the page's code reads it: state from another business is cleared, whatever way the app switched (Settings, the missing office screen, the business menu still to come). State from before the move has no stamp and is the open office's, so it is stamped, not cleared. Before the move nothing is checked. A business's view does not come back when you return to it: its roster comes from its own folder, and a stale saved copy could override it. +- Test: test/office-renderer-state.test.cjs (6 cases: same business kept, another cleared, unstamped kept, nothing before the move, the card cleared once read, the card wiring and its copy). It runs the real preload, and fails when the clear is removed. +- **E3 is complete.** Still behind `DBM_OFFICE_SETTINGS=1`. Left for step one: E4 (switch through closing time, and the T2 guard removed), E5 (Pulse office column by id), E6 (a Claude login per office), E7 (the live switch test), the design tasks DT1 to DT5, and removing the switch. + +## E4: switching business through closing time (2026-11-19) + +- **D10:** once settings are per office, a switch from Settings (Open another office, or Change office folder) starts closing time with the target held in memory (`pendingSwitch`). Nothing is written, stopped or killed until Michael concludes; then `switchOffice()` saves the folder and reopens the app on the other business. With no Michael running (nothing to close), the switch is immediate, as before. +- **D20, the closing bar:** it reads "Closing to open " (B is "a new business" for a folder with no office yet), and "Opening …" once closed. Cancel becomes Cancel switch and keeps A open (main forgets the pending switch). Force quit becomes Switch now, which asks once: "3 people are still working. Switch anyway?" with Keep waiting and Switch anyway. Switch now stops closing time quietly (`stopForSwitch`: no "back to work" mail, no event, unread steers dropped) and switches. A hard quit forgets the switch. A switch asked while the office is already closing carries on to that business. +- Settings steps aside for the bar while closing runs, and its saved screen state stays (the other business's window clears it as it opens, E3 part 3). +- **The T2 guard now holds only before the move.** After it, another business's office opens with its own settings, and an empty folder starts a new business, which runs setup. Before the move nothing changes. +- Names on the bar: `businessNameAt(home)`, the business's own settings, else its office.json, else none. +- Test: test/switch-business.test.cjs (8 cases: the bar's names on every update; a plain closing and a cancel; a switch during a closing; a quiet Switch now; main writes nothing before conclusion, and conclusion, cancel, hard quit and Switch now; the guard only before the move; the bar, App and Settings wiring and the copy; the names). closing-time-dialog.test.cjs now checks the switch forms of Force quit too. +- Still behind `DBM_OFFICE_SETTINGS=1`. Not covered by a test: a real relaunch into the other business (E7, the live switch test). + +## E5: Pulse by office id (2026-11-19) + +- `pulseOffice()` (index.ts), the one key Pulse, the cost ledger, owner notes, run comparisons and the case study file rows under, is the office's lasting id once settings are per office, else its folder as before. A moved folder keeps its history. +- `persist.relabelOffice(folder, id)` runs right after the store opens, before any service writes: every row in the office tables and the kv marks keyed by office (`OFFICE_KV_PREFIXES`: the cost ledger import, Pulse backfill and Pulse processor position, run comparisons) move from the folder to the id, in one transaction, once per id (`office:relabelled:`). A row or mark the id already has wins. +- A factory reset of one business now erases its kv marks and relabel mark too. +- Found while testing: `pulse:state:` (the Pulse processor's position) was keyed by office and not in the list; without it Pulse would have read an office's history again after the move. +- Test: test/pulse-office-id.test.cjs, run under Electron's Node for the real store (5 cases: rows and marks move once; history found by id after a move; existing id data wins; a one business reset; no op cases), plus a scan that fails when a new office keyed kv mark is not listed, and the main wiring order. + +## E6: a Claude login per business (2026-11-19) + +- New business setting `claudeLogin` ('own' or 'shared', unset is shared). For a business with its own login, the app sets `CLAUDE_CONFIG_DIR` to `userData/offices//claude` once, as the main process starts (after the move, before any agent, check or reader). Everything already follows that variable: agents keep it (ptyEnv.ts), the checks' sign in points at it (hiddenClaude.ts, empty for the default as T4 showed), transcripts and the projects folder walls read it, and the connector list is read with it. A switch relaunches, so it never changes mid run. +- `claudeHome.ts` (plain node): where Claude's settings folder and `.claude.json` are, honoring `CLAUDE_CONFIG_DIR`. The three readers that hardcoded `~/.claude` now go through it: the trust and API key approvals (`.claude.json` moves inside the folder, where Claude reads it), the global permission prompts setting, and the owner plugins turned off per session. Plan detection uses it too. This also fixes those approvals for an owner who exports `CLAUDE_CONFIG_DIR` themselves. +- **Where the owner chooses:** not built here. The design puts it in Add a business, at its Ready step ("Same as " or "A different Claude account", mockup frame 4), which is DT3. Until then nothing sets `claudeLogin`. +- A factory reset of a business erases its Claude folder with the rest of its place in the app's data folder; its Keychain entry (named after the folder) stays, unused. +- Test: test/office-claude-login.test.cjs (6 cases: the usual places with no folder; the folder's settings and record; approvals written where Claude reads them; the business's folder only after the move and only for 'own'; agents' environment and plan detection; main sets it once at start, and no reader is left on a fixed ~/.claude). Live sign in of two accounts is the optional T4 owner check. + +## DT1: the business menu in the top bar (2026-11-19) + +- `BusinessMenu` (src/renderer/src/shell/BusinessMenu.tsx) sits right of the lockup: the open business's name as a quiet button, "Business: . Switch business", capped at 220 px with an ellipsis and the full name in a tooltip. Its menu lists every business (open first, then by name) with its state, then Add a business; with one business, only Add a business (D14). +- Row states from main (`listBusinesses`, `office:list`): Open (green); Closed since to open ". Cancel switch keeps open. "Switch now" asks once: "3 people are still working. Switch anyway?", with Switch anyway and Keep waiting. | D20 | +| 6A | The button is labelled "Business: . Switch business" and has aria-haspopup=menu. Menu rows are menuitemradio with aria-checked and are 40 px tall. Arrow keys move, Enter opens, Esc closes and returns focus. Names are capped at 220 px with an ellipsis and the full name in a tooltip. A switch is announced once: "Closing to open ". | D21 | +| 7A | The window title becomes ", Don't Be Michael", only when the install has two or more businesses. | D22 | + +The guard (T2) is one alert dialog: the title "That office belongs to another business" with an info tip, one line, and OK. The second line reads "Open it from its own Mac user for now." only if T1 shows two Mac users running side by side. Otherwise it reads "It can't be opened from here yet." Both follow the CEO decisions D6 and D8, so this review adds no new choice here. + +### Pass scores + +| Pass | Before | After | Remaining gap | +|---|---|---|---| +| 1 Information architecture | 3 | 9 | none material | +| 2 Interaction states | 4 | 9 | the guard's second line waits on T1 | +| 3 Journey | 4 | 8 | first time switch has no walkthrough (not needed) | +| 4 Generic UI risk | 8 | 8 | none; app UI from existing parts | +| 5 Design system | 7 | 9 | none material | +| 6 Responsive and accessibility | 4 | 9 | none material | +| 7 Decisions | | | 9 resolved, 0 deferred | + +Journey (storyboard): + +``` + STEP | OWNER DOES | FEELS | PLAN SPECIFIES + 1 | sees "Harbor & Pine Bakery" top left | oriented | 1A + 2 | opens the menu, picks Add a business | curious, a bit unsure | 1A, 3A + 3 | fills setup while the bakery works | unhurried | 3A, Claude account choice + 4 | Open the office: closing bar | in control | 5A, cancel and switch now + 5 | agency floor opens, title updates | clear which business | 1A, 7A + 6 | later: menu shows bakery Closed since| knows it is waiting | 2A +``` + +### Design tasks + +- [x] **DT1 (P1, human: ~1 day / CC: ~30min)**: TopBar and a new business menu. Build the name button and menu with the Open, Closed since, Folder not found and Setup not finished rows. (done 2026-11-19, see DT1 below; the narrow width check is live) + - Surfaced by: 1A, 2A, 2B, 2C, 6A + - Files: src/renderer/src/shell/TopBar.tsx, a new BusinessMenu component, src/renderer/src/i18n/locales/en.json + - Verify: a renderer test for the row states and keyboard; live check at narrow width with a long name +- [x] **DT2 (P1, human: ~3h / CC: ~15min)**: Settings. Rename to Your businesses, align its entries with the menu, and replace Start a new empty office with Add a business. (done 2026-11-19, see DT2 below) + - Surfaced by: 1B + - Files: src/renderer/src/components/SettingsModal.tsx, en.json + - Verify: the Settings test lists the same entries as the menu +- [x] **DT3 (P1, human: ~1 day / CC: ~40min)**: Setup wizard. Run Add a business over the app while the open business keeps working, add the Claude account choice on the Ready step, and switch at the end. (done 2026-11-19, see DT3 below) + - Surfaced by: 3A, BIZ-3 (D4) + - Files: src/renderer/src/components/OnboardingWizard.tsx, src/main/index.ts + - Verify: an integration test that the open office keeps running until Open the office +- [x] **DT4 (P2, human: ~2h / CC: ~10min)**: Closing bar. Add the switch subject, Cancel switch, and Switch now with its one time question. (done with E4: ClosingTimeBar's switch form, tested in switch-business.test.cjs and closing-time-dialog.test.cjs) + - Surfaced by: 5A + - Files: the closing bar component, en.json + - Verify: the closing bar test covers the switch variant +- [x] **DT5 (P2, human: ~30min / CC: ~5min)**: Window title. Name the business when there are two or more. (done with DT1: the renderer sets the page title, which the window follows; tested in business-menu.test.cjs) + - Surfaced by: 7A + - Files: src/main/index.ts + - Verify: a unit test of the title rule + +### NOT in scope (design) + +- Showing how many items the closed business has waiting: it needs reading another office while it is closed, which belongs with step two. +- DESIGN.md text for these components is written when they ship (the doc records shipped UI). + +### What already exists (design) + +§7.1 top bar icon button hover, §7.23 menus, closing bar and dialogs, §7.25 onboarding wizard and its Ready step sign in rows, the Office folder missing screen, InfoTip, the floor business name plate (docs/designs/floor-business-name.md), the hire wizard's indigo soft selection for the account choice. + +## Design Review Completion Summary + +``` + +====================================================================+ + | DESIGN PLAN REVIEW — COMPLETION SUMMARY | + +====================================================================+ + | System Audit | DESIGN.md present; UI scope: top bar, menu, | + | | Settings, wizard, closing bar, dialog | + | Step 0 | 3/10 initial; all 7 dimensions | + | Pass 1 (Info Arch) | 3/10 → 9/10 after fixes | + | Pass 2 (States) | 4/10 → 9/10 after fixes | + | Pass 3 (Journey) | 4/10 → 8/10 after fixes | + | Pass 4 (AI Slop) | 8/10 → 8/10 after fixes | + | Pass 5 (Design Sys) | 7/10 → 9/10 after fixes | + | Pass 6 (Responsive) | 4/10 → 9/10 after fixes | + | Pass 7 (Decisions) | 9 resolved, 0 deferred | + +--------------------------------------------------------------------+ + | NOT in scope | written (2 items) | + | What already exists | written | + | TODOS.md updates | 0 items proposed | + | Approved Mockups | 1 HTML mockup, updated to the decisions | + | Decisions made | 9 added to plan | + | Decisions deferred | 0 | + | Overall design score | 3/10 → 8/10 | + +====================================================================+ +``` + +Unresolved design decisions: none. Plan is design-complete for step one. Run /design-review after implementation for visual QA. + +## GSTACK REVIEW REPORT + +| Review | Trigger | Why | Runs | Status | Findings | +|--------|---------|-----|------|--------|----------| +| CEO Review | `/plan-ceo-review` | Scope & strategy | 1 | ISSUES OPEN | mode: SCOPE_REDUCTION, 1 critical gaps | +| Outside Review | Codex (not run, owner rule); native Claude subagent in the CEO review | Independent 2nd opinion | 2 | unavailable (native completed once) | 8 findings (native, CEO run); 8 resolved or routed; 0 unresolved; no completed external review | +| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 1 | ISSUES OPEN | 29 issues, 0 critical gaps | +| Design Review | `/plan-design-review` | UI/UX gaps | 1 | CLEAR | score: 3/10 → 8/10, 9 decisions | +| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | — | — | + +- **OUTSIDE COVERAGE:** plan-review phase: Codex not run (owner rule); the CEO review's native Claude subagent completed with 8 findings; the eng review ran no second pass; design phase: outside design voice skipped by the owner (D13). No completed external review. +- **VERDICT:** DESIGN CLEARED; CEO and eng reviews hold mapped work and no open decisions; eng review required to clear. + +**UNRESOLVED DECISIONS:** +- + 3 unresolved from prior reviews (the CEO review's BIZ-5, BIZ-7 and BIZ-8, settled in the eng review by D10, D11 and D9) diff --git a/package-lock.json b/package-lock.json index 5960cd759..ddfbc5119 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "dontbemichael", - "version": "0.4.2", + "version": "0.4.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dontbemichael", - "version": "0.4.2", + "version": "0.4.3", "hasInstallScript": true, "dependencies": { "@xterm/addon-fit": "^0.10.0", diff --git a/package.json b/package.json index 9aa5a60df..b76db98fd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dontbemichael", - "version": "0.4.2", + "version": "0.4.3", "private": true, "description": "An AI office for small business owners: Michael, your office manager, runs a team of AI agents on your own computer.", "main": "out/main/index.js", diff --git a/src/main/backup.ts b/src/main/backup.ts new file mode 100644 index 000000000..d87f8445b --- /dev/null +++ b/src/main/backup.ts @@ -0,0 +1,378 @@ +/** + * Back up everything on this computer, and restore it on a new one + * (docs/designs/backup-restore.md; owner 2026-11-19: everything on this Mac in + * one file, the team's working folders included, passwords and keys sealed + * with a backup password). + * + * Back up Restore (a new computer) + * ───────────────────────────────── ───────────────────────────────── + * roots: the app's data folder (an the backup password opens the + * allow list, no caches), each office secrets first: wrong, nothing is + * folder, each business and team folder, written + * the team's Claude conversations every file to its root's place, + * the database as a consistent snapshot paths under the old home folder + * secrets: decrypted here, sealed with the moved to this one's; a document + * backup password already there is kept + * one .dbmbackup file (backupArchive.ts) paths inside the app's own JSON + * and the database follow; the + * secrets are locked to this Mac + * + * What cannot move: the Claude sign in (Keychain) and its connectors (the + * claude.ai account). After a restore the owner signs in again, and the + * connectors come back with the account. + * + * No electron import here: the caller hands in where things are and how to + * reach the secrets and the database, so it tests as a node module. + */ +import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { BackupWriter, readEntries, readManifest, safeTarget, type EntryHeader } from './backupArchive'; +import { openSecrets, sealSecrets, type SealedSecrets } from './backupSecrets'; +import { isUsableTeamFolder } from './officeFile'; +import { APP_DATA_ENTRIES, APP_DATA_KEPT, CHECK_FOLDERS } from './factoryReset'; + +export type RootKind = 'userData' | 'office' | 'folder' | 'claude'; + +export interface BackupManifest { + v: 1; + createdAt: number; + appVersion: string; + platform: string; + /** The home folder it was made under: paths under it move to the new one's. */ + home: string; + roots: Record; + /** Business names, for the restore screen. */ + businesses: string[]; + secrets?: SealedSecrets; +} + +/** What the restore screen shows before anything is written. */ +export interface BackupSummary { + createdAt: number; + appVersion: string; + businesses: string[]; + hasSecrets: boolean; + fromOtherHome: boolean; +} + +/** The app's own files a backup carries: those a reset erases or keeps on + * purpose (factoryReset.ts, so a new one is never forgotten), each business's + * place, and the window's saved state; not the secrets file (sealed apart), + * the database (a snapshot), caches, or scratch folders. */ +const LEFT_OUT = new Set([ + 'integration-secrets.json', 'harness.db', 'harness.db-wal', 'harness.db-shm', 'opened-attachments', + 'last-run-version', 'updater.log', 'hero.json', 'model-catalog.json', 'skill-catalog.json', 'trigger-history.json', + ...CHECK_FOLDERS +]); +export const USER_DATA_ITEMS: readonly string[] = [ + ...new Set([...APP_DATA_ENTRIES, ...APP_DATA_KEPT, 'offices', 'Local Storage', 'config.before-offices.json']) +].filter((n) => !LEFT_OUT.has(n)); + +/** Never carried, wherever they are. `.credentials.json` is where Claude Code + * keeps its sign in off macOS (a business with its own Claude login has one + * in its place): a sign in is never in a backup, the owner signs in again. */ +const SKIP_NAMES = new Set(['.DS_Store', 'node_modules', 'hooks.sock', 'Thumbs.db', '.credentials.json']); +/** A backup file is never carried, so a backup saved in a business's folder + * holds neither itself nor the ones before it. */ +const isBackupFile = (n: string): boolean => n.toLowerCase().endsWith('.dbmbackup'); + +export interface BackupSource { + userData: string; + home: string; + appVersion: string; + platform: string; + /** config.json as stored. */ + config: Record; + /** Where Claude keeps a folder's conversations, when it has any. */ + claudeDirFor: (folder: string) => string | null; + /** Write a consistent copy of the database to `dest`; false when there is none. */ + dbSnapshot: (dest: string) => Promise; + /** Every saved secret, decrypted. */ + secrets: () => Record; + onProgress?: (files: number, bytes: number) => void; +} + +const holdsOffice = (p: string): boolean => existsSync(join(p, 'hive', 'registry.json')); +const isDir = (p: string): boolean => { try { return statSync(p).isDirectory(); } catch { return false; } }; +const inside = (child: string, parent: string): boolean => { + const c = resolve(child), p = resolve(parent); + return c === p || c.startsWith(p + sep); +}; + +/** Each business's settings: per office once moved, else the top of config.json. */ +function businessSettings(cfg: Record): Array> { + const offices = cfg.offices as Record }> | undefined; + if (cfg.officesMigrated && offices) return Object.values(offices).map((e) => e?.settings ?? {}); + return [cfg]; +} + +/** The folders a backup carries: offices, then business and team folders that + * are not inside one already taken. */ +export function backupRoots(src: Pick): { offices: string[]; folders: string[]; names: string[] } { + const cfg = src.config; + const offices: string[] = []; + const add = (list: string[], p: unknown): void => { + if (typeof p !== 'string' || !p.trim()) return; + const r = resolve(p); + if (!list.some((x) => resolve(x) === r)) list.push(r); + }; + add(offices, cfg.harnessHome); + for (const h of (cfg.recentHives as unknown[] | undefined) ?? []) add(offices, h); + for (const e of Object.values((cfg.offices as Record | undefined) ?? {})) add(offices, e?.home); + // Only folders a restore puts back (restorableFolder), so a backup never + // carries one that would be left out on the other computer. + const officeRoots = offices.filter((o) => holdsOffice(o) && restorableFolder(o, src.home)); + + const wanted: string[] = []; + const names: string[] = []; + for (const s of businessSettings(cfg)) { + if (typeof s.businessName === 'string' && s.businessName.trim()) names.push(s.businessName.trim()); + add(wanted, s.businessFolder); + for (const m of (s.businessTeam as Array<{ folder?: string }> | undefined) ?? []) add(wanted, m?.folder); + for (const r of (s.registeredRepos as unknown[] | undefined) ?? []) add(wanted, r); + } + // Outermost first, so a team folder inside the business folder is not taken twice. + const folders: string[] = []; + for (const f of wanted.sort((a, b) => a.length - b.length)) { + if (!isDir(f) || !restorableFolder(f, src.home)) continue; + if (folders.some((x) => inside(f, x)) || officeRoots.some((o) => inside(f, o))) continue; + folders.push(f); + } + return { offices: officeRoots, folders, names: [...new Set(names)] }; +} + +/** Every regular file under `dir`, skipping links, sockets, SKIP_NAMES and any + * folder in `except` (another root, carried on its own). */ +function* walk(dir: string, except: string[]): Generator { + let names: string[] = []; + try { names = readdirSync(dir); } catch { return; } + for (const n of names) { + if (SKIP_NAMES.has(n) || isBackupFile(n)) continue; + const p = join(dir, n); + if (except.some((x) => resolve(x) === resolve(p))) continue; + let st; + try { st = lstatSync(p); } catch { continue; } + if (st.isSymbolicLink()) continue; + if (st.isDirectory()) yield* walk(p, except); + else if (st.isFile()) yield p; + } +} + +/** Agents' working folders, for their Claude conversations: the business and + * team folders, and each office's members (its registry). */ +function agentFolders(offices: string[], folders: string[], cfg: Record): string[] { + const out = new Set(folders.map((f) => resolve(f))); + for (const s of businessSettings(cfg)) for (const m of (s.businessTeam as Array<{ folder?: string }> | undefined) ?? []) if (m?.folder) out.add(resolve(m.folder)); + for (const o of offices) { + try { + const reg = JSON.parse(readFileSync(join(o, 'hive', 'registry.json'), 'utf8')) as { agents?: Record }; + for (const a of Object.values(reg.agents ?? {})) if (typeof a?.cwd === 'string' && a.cwd) out.add(resolve(a.cwd)); + } catch { /* an office without a readable registry */ } + } + return [...out]; +} + +/** Write the backup. Throws when it cannot be written (the partial file is the caller's to remove). */ +export async function writeBackup(outPath: string, password: string, src: BackupSource): Promise<{ files: number; bytes: number }> { + const { offices, folders, names } = backupRoots(src); + const roots: BackupManifest['roots'] = { u: { kind: 'userData', path: src.userData } }; + offices.forEach((o, i) => { roots[`o${i}`] = { kind: 'office', path: o }; }); + folders.forEach((f, i) => { roots[`f${i}`] = { kind: 'folder', path: f }; }); + const claude: Array<[string, string]> = []; + agentFolders(offices, folders, src.config).filter((f) => restorableFolder(f, src.home)).forEach((folder) => { + const dir = src.claudeDirFor(folder); + if (dir && isDir(dir)) { const id = `c${claude.length}`; roots[id] = { kind: 'claude', path: folder }; claude.push([id, dir]); } + }); + const secrets = src.secrets(); + const manifest: BackupManifest = { + v: 1, createdAt: Date.now(), appVersion: src.appVersion, platform: src.platform, home: src.home, roots, + businesses: names, + ...(Object.keys(secrets).length ? { secrets: sealSecrets(secrets, password) } : {}) + }; + + const w = new BackupWriter(outPath, manifest); + const tick = (): void => { const c = w.counts; src.onProgress?.(c.files, c.bytes); }; + const put = async (root: string, base: string, abs: string): Promise => { + let st; + try { st = statSync(abs); } catch { return; } + await w.addFile(root, relative(base, abs), abs, st.mode, st.mtimeMs, st.size); + if (w.counts.files % 50 === 0) tick(); + }; + // The app's own files, then the database as one consistent snapshot. + for (const item of USER_DATA_ITEMS) { + const p = join(src.userData, item); + if (!existsSync(p)) continue; + if (statSync(p).isDirectory()) { for (const f of walk(p, [])) await put('u', src.userData, f); } + else await put('u', src.userData, p); + } + const snap = join(src.userData, `harness.db.backup-${process.pid}.tmp`); + try { + if (await src.dbSnapshot(snap)) await w.addBuffer('u', 'harness.db', readFileSync(snap), 0o600); + } finally { + rmSync(snap, { force: true }); + } + const everyRoot = [...offices, ...folders]; + for (const [id, r] of Object.entries(roots)) { + if (r.kind === 'office' || r.kind === 'folder') { + for (const f of walk(r.path, everyRoot.filter((x) => resolve(x) !== resolve(r.path)))) await put(id, r.path, f); + } + } + for (const [id, dir] of claude) for (const f of walk(dir, [])) await put(id, dir, f); + const done = await w.finish(); + src.onProgress?.(done.files, done.bytes); + return done; +} + +/** Throws 'wrong password' when the backup's secrets do not open with it (and + * 'not a backup file' when it is not one); a backup without secrets needs none. */ +export async function checkBackupPassword(path: string, password: string): Promise { + const m = await readManifest(path); + if (!m || m.v !== 1 || !m.roots) throw new Error('not a backup file'); + if (m.secrets) openSecrets(m.secrets, password); +} + +/** The backup file's suggested name: letters, digits and underscores only + * (owner, 2026-11-19), so it moves through any drive, cloud or email intact: + * Dont_Be_Michael_backup_2026_11_19.dbmbackup. */ +export function backupFileName(now: Date = new Date()): string { + const pad = (n: number): string => String(n).padStart(2, '0'); + return `Dont_Be_Michael_backup_${now.getFullYear()}_${pad(now.getMonth() + 1)}_${pad(now.getDate())}.dbmbackup`; +} + +/** What is in a backup, for the restore screen. Throws 'not a backup file'. */ +export async function inspectBackup(path: string, home: string): Promise { + const m = await readManifest(path); + if (!m || m.v !== 1 || !m.roots || typeof m.home !== 'string') throw new Error('not a backup file'); + return { + createdAt: m.createdAt, appVersion: m.appVersion, businesses: Array.isArray(m.businesses) ? m.businesses : [], + hasSecrets: !!m.secrets, fromOtherHome: resolve(m.home) !== resolve(home) + }; +} + +/** A path from the backup's computer, moved to this one: under the old home + * folder, it goes under this home folder; anywhere else, it stays. */ +export function movePath(p: string, oldHome: string, newHome: string): string { + const o = resolve(oldHome); + const r = resolve(p); + if (r === o) return resolve(newHome); + return r.startsWith(o + sep) ? join(resolve(newHome), r.slice(o.length + 1)) : r; +} + +/** The old home folder in text (JSON), moved to the new one, only where it is a + * whole folder: "/Users/sam/" and "/Users/sam\"" but never "/Users/samuel". */ +export function movePathsInText(text: string, oldHome: string, newHome: string): string { + if (resolve(oldHome) === resolve(newHome)) return text; + const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const forms = [[oldHome, newHome], [JSON.stringify(oldHome).slice(1, -1), JSON.stringify(newHome).slice(1, -1)]]; + let out = text; + for (const [from, to] of forms) out = out.replace(new RegExp(`${esc(from)}(?=[\\\\/"])`, 'g'), to); + return out; +} + +/** A path with its links followed as far as it exists on the disk; the parts + * not there yet are added as written (they cannot be links). */ +function onDisk(p: string): string | null { + let d = resolve(p); + const rest: string[] = []; + while (!existsSync(d) && dirname(d) !== d) { rest.unshift(basename(d)); d = dirname(d); } + try { return join(realpathSync.native(d), ...rest); } catch { return null; } +} + +/** Whether `target` is still inside `base` once links already on the disk are + * followed: a folder there that is a link elsewhere never takes a file. */ +function staysInside(base: string, target: string): boolean { + const root = onDisk(base); + const at = onDisk(dirname(target)); + if (!root || !at) return false; + return at === root || at.startsWith(root + sep); +} + +const ROOT_KINDS = new Set(['userData', 'office', 'folder', 'claude']); + +/** A folder a restore may write into: one setup could choose for a team + * (isUsableTeamFolder), and not a dot folder anywhere under home. */ +export function restorableFolder(folder: string, home: string): boolean { + if (!isAbsolute(folder)) return false; + // Checked as written and where it really leads: a link, a junction or a + // Windows short name that ends in a kept folder is that folder. + const real = onDisk(folder); + const realHome = onDisk(home); + if (!real || !realHome) return false; + const fold = process.platform === 'darwin' || process.platform === 'win32' ? (p: string) => p.toLowerCase() : (p: string) => p; + for (const [f, h] of [[resolve(folder), resolve(home)], [real, realHome]]) { + if (!isUsableTeamFolder(f, h)) return false; + const rel = relative(fold(h), fold(f)); + if (!rel || rel.startsWith('..') || isAbsolute(rel)) continue; + const parts = rel.split(sep); + // Windows keeps settings and login items in AppData, as a Mac does in Library. + if (parts[0] === 'appdata' || parts[0] === 'AppData' || parts.some((part) => part.startsWith('.'))) return false; + } + return true; +} + +export interface RestoreTarget { + userData: string; + home: string; + claudeDirFor: (folder: string) => string; + /** Lock the secrets to this computer. False when it cannot. */ + importSecrets: (secrets: Record) => boolean; + /** Move office paths kept in the database (the Pulse office column). */ + moveDbPaths: (dbPath: string, oldHome: string, newHome: string) => void; +} + +/** + * Put a backup back. The secrets are opened first, so a wrong password writes + * nothing. Returns what was written and skipped; throws 'wrong password', + * 'not a backup file', 'the backup file is cut short' or 'secrets not saved'. + * The caller stops the app's services before and reopens the app after. + */ +export async function restoreBackup(path: string, password: string, t: RestoreTarget): Promise<{ written: number; skipped: number }> { + const m = await readManifest(path); + if (!m || m.v !== 1 || !m.roots || typeof m.home !== 'string') throw new Error('not a backup file'); + const secrets = m.secrets ? openSecrets(m.secrets, password) : {}; + const to = (p: string): string => movePath(p, m.home, t.home); + const bases: Record = {}; + for (const [id, r] of Object.entries(m.roots)) { + if (!r || typeof r.path !== 'string' || !ROOT_KINDS.has(r.kind)) continue; + if (r.kind === 'userData') { bases[id] = { kind: r.kind, base: t.userData }; continue; } + // The backup names its own folders: each must be one a team could work + // in, never the home folder, a dot folder in it or Library, so a crafted + // file cannot write into the owner's settings, keys or login items. + const folder = to(r.path); + if (!restorableFolder(folder, t.home)) continue; + if (r.kind === 'claude') { bases[id] = { kind: r.kind, base: t.claudeDirFor(folder) }; continue; } + // An office's files replace the office they came from; a folder that is + // there and is not that office keeps what it holds, like a business folder. + const isOffice = r.kind === 'office' && (!existsSync(folder) || existsSync(join(folder, 'hive', 'registry.json'))); + bases[id] = { kind: isOffice ? 'office' : 'folder', base: folder }; + } + const counts = await readEntries(path, (h: EntryHeader) => { + const b = bases[h.r]; + if (!b) return null; + const target = safeTarget(b.base, h.p); + if (!target || !staysInside(b.base, target)) return null; + // A document already on this computer is the owner's: it stays as it is. + if (b.kind === 'folder' && existsSync(target)) return null; + return target; + }); + + // Paths the app keeps in its own files and its database follow the move. + if (resolve(m.home) !== resolve(t.home)) { + const textRoots = Object.values(bases).filter((b) => b.kind === 'userData' || b.kind === 'office').map((b) => b.base); + for (const root of textRoots) { + for (const f of walk(root, [])) { + if (!/\.(json|jsonl)$/.test(f) || basename(f) === 'harness.db') continue; + try { + if (statSync(f).size > 50 * 1024 * 1024) continue; + const before = readFileSync(f, 'utf8'); + const after = movePathsInText(before, m.home, t.home); + if (after !== before) writeFileSync(f, after); + } catch { /* left as it was */ } + } + } + const db = join(t.userData, 'harness.db'); + if (existsSync(db)) t.moveDbPaths(db, m.home, t.home); + } + if (Object.keys(secrets).length && !t.importSecrets(secrets)) throw new Error('secrets not saved'); + return counts; +} diff --git a/src/main/backupArchive.ts b/src/main/backupArchive.ts new file mode 100644 index 000000000..1ddd48429 --- /dev/null +++ b/src/main/backupArchive.ts @@ -0,0 +1,248 @@ +/** + * The backup file (`.dbmbackup`): one gzip stream holding a manifest and every + * file, written and read as a stream so a large documents folder never sits in + * memory. Plain node (zlib, fs), no electron import, so it tests as a node + * module; no archive library is needed and it reads the same on any platform. + * + * gzip( + * "DBMBACKUP 1\n" + * \n + * { "r": root, "p": "rel/path", "s": size, "m": mode, "t": mtimeMs }\n + * ... one header line and its bytes per file ... + * { "end": true, "n": files }\n + * ) + * + * Paths are relative to their root and use "/". A reader never writes outside + * the folder it is given for a root: an absolute path, a "..", or anything that + * resolves outside is refused, so a crafted backup cannot write elsewhere. + */ +import { chmodSync, createReadStream, createWriteStream, lstatSync, mkdirSync, renameSync, unlinkSync, utimesSync } from 'node:fs'; +import { dirname, isAbsolute, resolve, sep } from 'node:path'; +import { createGunzip, createGzip, constants as zc } from 'node:zlib'; +import { once } from 'node:events'; +import { finished } from 'node:stream/promises'; +import type { Readable, Writable } from 'node:stream'; + +export const BACKUP_MAGIC = 'DBMBACKUP 1\n'; +/** A manifest or header line longer than this is not a backup. */ +const MAX_LINE = 8 * 1024 * 1024; + +export interface EntryHeader { + /** The root it belongs to (a key of the manifest's roots). */ + r: string; + /** Path inside the root, with "/". */ + p: string; + /** Size in bytes. */ + s: number; + /** File mode bits (0o777 at most). */ + m: number; + /** Modified time, ms. */ + t: number; +} + +/** Writes a backup file. Add files in any order, then finish(). */ +export class BackupWriter { + private readonly gzip = createGzip({ level: zc.Z_BEST_SPEED }); + private readonly out: Writable; + private files = 0; + private bytes = 0; + private done: Promise; + + constructor(path: string, manifest: object) { + mkdirSync(dirname(path), { recursive: true }); + this.out = createWriteStream(path, { mode: 0o600 }); + this.gzip.pipe(this.out); + this.done = once(this.out, 'close'); + this.gzip.write(BACKUP_MAGIC); + this.gzip.write(`${JSON.stringify(manifest)}\n`); + } + + get counts(): { files: number; bytes: number } { return { files: this.files, bytes: this.bytes }; } + + private async put(chunk: Buffer | string): Promise { + if (!this.gzip.write(chunk)) await once(this.gzip, 'drain'); + } + + /** One file from disk, streamed. Its size is read as it is written, so a file + * that grew or shrank since it was listed is stored as it was when read. */ + async addFile(root: string, rel: string, abs: string, mode: number, mtimeMs: number, size: number): Promise { + // Read it whole into the stream with the size taken from the bytes read: + // a size from an earlier stat could be wrong for a file still being written. + const chunks: Buffer[] = []; + let total = 0; + if (size <= 64 * 1024 * 1024) { + for await (const c of createReadStream(abs)) { chunks.push(c as Buffer); total += (c as Buffer).length; } + await this.addBuffer(root, rel, Buffer.concat(chunks, total), mode, mtimeMs); + return; + } + // A large file streams with its listed size; a file that changes while it is + // read is padded or cut to that size, so the archive stays readable. + await this.put(`${JSON.stringify(header(root, rel, size, mode, mtimeMs))}\n`); + let left = size; + for await (const c of createReadStream(abs, { end: size - 1 })) { + const b = (c as Buffer).subarray(0, left); + left -= b.length; + await this.put(b); + } + if (left > 0) await this.put(Buffer.alloc(left)); + this.files += 1; + this.bytes += size; + } + + async addBuffer(root: string, rel: string, data: Buffer, mode = 0o600, mtimeMs = Date.now()): Promise { + await this.put(`${JSON.stringify(header(root, rel, data.length, mode, mtimeMs))}\n`); + await this.put(data); + this.files += 1; + this.bytes += data.length; + } + + async finish(): Promise<{ files: number; bytes: number }> { + await this.put(`${JSON.stringify({ end: true, n: this.files })}\n`); + this.gzip.end(); + await this.done; + return this.counts; + } +} + +function header(root: string, rel: string, size: number, mode: number, mtimeMs: number): EntryHeader { + return { r: root, p: rel.split(sep).join('/'), s: size, m: mode & 0o777, t: Math.round(mtimeMs) }; +} + +/** A path from a backup, safe to write under `base`, or null when it is not + * (absolute, "..", empty, or resolving outside). */ +export function safeTarget(base: string, rel: string): string | null { + if (typeof rel !== 'string' || !rel || rel.includes('\0') || isAbsolute(rel) || /^[a-zA-Z]:/.test(rel)) return null; + const parts = rel.split('/'); + if (parts.some((p) => p === '..' || p === '')) return null; + const root = resolve(base); + const target = resolve(root, ...parts); + return target.startsWith(root + sep) ? target : null; +} + +/** A byte reader over the gunzipped stream: lines and exact byte counts. */ +class Bytes { + private buf: Buffer = Buffer.alloc(0); + private ended = false; + private readonly it: AsyncIterator; + constructor(private readonly src: Readable, private readonly file?: Readable) { this.it = (src as AsyncIterable)[Symbol.asyncIterator](); } + /** Let go of the backup file, also when reading stopped before its end, and + * wait until it is let go: an open file cannot be moved or deleted on Windows. */ + async close(): Promise { + const file = this.file as (Readable & { closed?: boolean }) | undefined; + const closed = file && !file.closed ? once(file, 'close').catch(() => undefined) : Promise.resolve(); + this.src.destroy(); + file?.destroy(); + await closed; + } + private async more(): Promise { + if (this.ended) return false; + const n = await this.it.next(); + if (n.done) { this.ended = true; return false; } + this.buf = this.buf.length ? Buffer.concat([this.buf, n.value]) : n.value; + return true; + } + async line(): Promise { + for (;;) { + const at = this.buf.indexOf(10); + if (at >= 0) { const l = this.buf.subarray(0, at).toString('utf8'); this.buf = this.buf.subarray(at + 1); return l; } + if (this.buf.length > MAX_LINE) throw new Error('not a backup file'); + if (!(await this.more())) return null; + } + } + /** Hand exactly `n` bytes to `sink` (null skips them). */ + async take(n: number, sink: ((b: Buffer) => Promise) | null): Promise { + let left = n; + while (left > 0) { + if (this.buf.length === 0 && !(await this.more())) throw new Error('the backup file is cut short'); + const b = this.buf.subarray(0, left); + this.buf = this.buf.subarray(b.length); + left -= b.length; + if (sink) await sink(b); + } + } +} + +function open(path: string): Bytes { + const gunzip = createGunzip(); + const file = createReadStream(path); + file.on('error', (e) => gunzip.destroy(e)).pipe(gunzip); + return new Bytes(gunzip, file); +} + +/** The manifest, read without going through the files. */ +export async function readManifest(path: string): Promise { + const b = open(path); + try { + if ((await b.line()) + '\n' !== BACKUP_MAGIC) throw new Error('not a backup file'); + const m = await b.line(); + if (m === null) throw new Error('not a backup file'); + return JSON.parse(m) as T; + } catch (e) { + throw e instanceof SyntaxError ? new Error('not a backup file') : e; + } finally { + await b.close(); + } +} + +/** + * Read every file. `place` says where a file goes (an absolute path made with + * safeTarget), or null to skip it. Returns how many were written and skipped; + * throws when the file is not a whole backup. + */ +export async function readEntries( + path: string, + place: (h: EntryHeader) => string | null +): Promise<{ written: number; skipped: number }> { + const b = open(path); + try { + if ((await b.line()) + '\n' !== BACKUP_MAGIC) throw new Error('not a backup file'); + if ((await b.line()) === null) throw new Error('not a backup file'); + let written = 0; + let skipped = 0; + for (;;) { + const l = await b.line(); + if (l === null) throw new Error('the backup file is cut short'); + let h: EntryHeader & { end?: boolean }; + try { h = JSON.parse(l); } catch { throw new Error('not a backup file'); } + if (h.end) break; + if (typeof h.s !== 'number' || h.s < 0 || !Number.isFinite(h.s)) throw new Error('not a backup file'); + const target = place(h); + if (!target) { await b.take(h.s, null); skipped += 1; continue; } + mkdirSync(dirname(target), { recursive: true }); + // Written beside the target and swapped in only once whole: a cut backup + // never leaves a file of the owner's half gone, a read only git object is + // replaced, and a link at the target is replaced, never written through. + const part = `${target}.dbm-restoring`; + try { unlinkSync(part); } catch { /* none left over */ } + const out = createWriteStream(part, { mode: (h.m & 0o777) || 0o600, flags: 'wx' }); + // A file that cannot be opened or written (a full disk, a folder in the + // way) stops the restore with its error, never a wait with no end. + let failed: Error | null = null; + out.on('error', (e) => { failed = e; }); + try { + await b.take(h.s, async (chunk) => { + if (failed) throw failed; + if (!out.write(chunk)) await once(out, 'drain'); + }); + out.end(); + await finished(out); + // Windows refuses to rename over a read only file (a git object): make + // the one being replaced writable first. It stays whole until the swap. + try { if (lstatSync(target).isFile()) chmodSync(target, 0o600); } catch { /* not there */ } + renameSync(part, target); + } catch (e) { + // Closed before it is deleted: Windows cannot delete an open file. + if (!out.closed) await new Promise((done) => { out.once('close', () => done()); out.destroy(); }); + try { unlinkSync(part); } catch { /* never written */ } + throw e; + } + // Keep the file's own time, so a restored office looks as it did. + if (h.t > 0) { try { utimesSync(target, new Date(), new Date(h.t)); } catch { /* the time only */ } } + written += 1; + } + return { written, skipped }; + } finally { + await b.close(); + } +} + diff --git a/src/main/backupSecrets.ts b/src/main/backupSecrets.ts new file mode 100644 index 000000000..1cfc35de4 --- /dev/null +++ b/src/main/backupSecrets.ts @@ -0,0 +1,52 @@ +/** + * Saved passwords and keys in a backup (docs/designs/backup-restore.md): + * the app keeps them encrypted with this computer's own key (Keychain), which + * no other computer can read. A backup carries them sealed with a password the + * owner chooses instead: scrypt for the key, AES-256-GCM to seal, so a wrong + * password or a changed file is refused, never read as garbage. Restore opens + * them and locks them to the new computer again. + * + * Plain node crypto, no electron import, so it tests as a node module. + */ +import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto'; + +export interface SealedSecrets { + v: 1; + salt: string; + iv: string; + tag: string; + data: string; +} + +/** The shortest backup password accepted. */ +export const MIN_BACKUP_PASSWORD = 8; +const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }; + +function keyFor(password: string, salt: Buffer): Buffer { + return scryptSync(password.normalize('NFC'), salt, 32, SCRYPT); +} + +/** Seal { ref: plaintext } with the backup password. */ +export function sealSecrets(secrets: Record, password: string): SealedSecrets { + if (password.length < MIN_BACKUP_PASSWORD) throw new Error('password too short'); + const salt = randomBytes(16); + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', keyFor(password, salt), iv); + const data = Buffer.concat([cipher.update(JSON.stringify(secrets), 'utf8'), cipher.final()]); + return { v: 1, salt: salt.toString('base64'), iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') }; +} + +/** Open them with the backup password; throws 'wrong password' when it is not + * the one they were sealed with (or the file was changed). */ +export function openSecrets(sealed: SealedSecrets, password: string): Record { + try { + const decipher = createDecipheriv('aes-256-gcm', keyFor(password, Buffer.from(sealed.salt, 'base64')), Buffer.from(sealed.iv, 'base64')); + decipher.setAuthTag(Buffer.from(sealed.tag, 'base64')); + const plain = Buffer.concat([decipher.update(Buffer.from(sealed.data, 'base64')), decipher.final()]).toString('utf8'); + const v = JSON.parse(plain) as unknown; + if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('bad'); + return Object.fromEntries(Object.entries(v as Record).filter(([, x]) => typeof x === 'string')) as Record; + } catch { + throw new Error('wrong password'); + } +} diff --git a/src/main/claudeAccount.ts b/src/main/claudeAccount.ts index 72e5dc607..20ae8f457 100644 --- a/src/main/claudeAccount.ts +++ b/src/main/claudeAccount.ts @@ -4,9 +4,8 @@ * the file holds no secret the app looks at, and nothing is written. */ import { readFileSync } from 'node:fs'; -import { homedir } from 'node:os'; -import { join } from 'node:path'; import { planFromAccount, type ClaudePlanId } from '../shared/claudePlan'; +import { claudeJsonFile } from './claudeHome'; const KEEP_MS = 10 * 60_000; let cached: { at: number; plan: ClaudePlanId | null } | null = null; @@ -14,7 +13,7 @@ let cached: { at: number; plan: ClaudePlanId | null } | null = null; /** The account record's path: Claude Code keeps it beside its config folder's * contents when CLAUDE_CONFIG_DIR is set, else in the home folder. */ export function claudeAccountFile(): string { - return process.env.CLAUDE_CONFIG_DIR ? join(process.env.CLAUDE_CONFIG_DIR, '.claude.json') : join(homedir(), '.claude.json'); + return claudeJsonFile(); } /** The detected plan, read at most every ten minutes. */ diff --git a/src/main/claudeHome.ts b/src/main/claudeHome.ts new file mode 100644 index 000000000..b2f9b1f00 --- /dev/null +++ b/src/main/claudeHome.ts @@ -0,0 +1,32 @@ +/** + * Where Claude Code keeps its settings and account record for this app run. + * + * Claude Code reads CLAUDE_CONFIG_DIR when it is set: its settings.json, + * plugins, projects and conversations live there, and its account record is + * `/.claude.json` instead of `~/.claude.json`. Its sign in is kept per + * folder too (probed on Claude Code 2.1.328, docs/designs/separate-businesses.md + * T4). The app sets it for a business with its own Claude login (E6), and an + * owner may export it themselves; either way, every file the app reads or + * writes for Claude goes through here, so it is the folder Claude really uses. + * + * Plain node, no electron import, so it tests as a node module. + */ +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +/** The CLAUDE_CONFIG_DIR in effect, or null for Claude's default (~/.claude). */ +export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env): string | null { + const d = env.CLAUDE_CONFIG_DIR?.trim(); + return d ? d : null; +} + +/** Claude Code's settings folder: settings.json, settings.local.json, plugins. */ +export function claudeSettingsDir(home: string = homedir(), env: NodeJS.ProcessEnv = process.env): string { + return claudeConfigDir(env) ?? join(home, '.claude'); +} + +/** Claude Code's account record and per project trust: `.claude.json`. */ +export function claudeJsonFile(home: string = homedir(), env: NodeJS.ProcessEnv = process.env): string { + const d = claudeConfigDir(env); + return d ? join(d, '.claude.json') : join(home, '.claude.json'); +} diff --git a/src/main/closingTime.ts b/src/main/closingTime.ts index 90ef38e20..1e7a59077 100644 --- a/src/main/closingTime.ts +++ b/src/main/closingTime.ts @@ -63,6 +63,10 @@ export interface ClosingTimeEvent { godLive: boolean; /** The app reopens itself after closing (a Claude Code update, cliUpdate.ts). */ relaunch: boolean; + /** Closing to open another business (docs/designs/separate-businesses.md, + * D10, D20): the names the bar shows, "Closing to open ". `to` + * is null for a business with no name yet. Absent on a plain closing. */ + switching?: { from: string; to: string | null }; } export type ClosingTimeActionResult = { ok: true } | { ok: false; error: string }; @@ -91,8 +95,18 @@ export class ClosingTimeController { private active = false; private godId = 'god'; private relaunch = false; + private switching: { from: string; to: string | null } | null = null; private workers = new Set(); private acked = new Set(); + /** Michael was told every team member confirmed (tellMichaelAllIn). */ + private toldAllIn = false; + /** The note again while he has not closed (tellMichaelAllIn). */ + private allInTimer: NodeJS.Timeout | null = null; + /** How long Michael has to close after the note before it comes again, and + * how many times it comes again (2026-11-20: a note filed unread with the + * confirmations it followed held closing time). */ + static ALL_IN_REMIND_MS = 45_000; + static ALL_IN_REMINDERS = 2; private excused = new Set(); private lastRemind = new Map(); /** Set once COMPLETE is accepted. `active` stays true through the teardown @@ -138,10 +152,13 @@ export class ClosingTimeController { /** Kick off the protocol. Returns an error string when the floor cannot run * it (no live god agent) so the UI can fall back to the hard quit. */ - start(opts: { relaunch?: boolean } = {}): { ok: boolean; error?: string } { + start(opts: { relaunch?: boolean; switching?: { from: string; to: string | null } } = {}): { ok: boolean; error?: string } { if (this.active) { // Already closing down after COMPLETE: nothing to restart. if (this.concluded) return { ok: false, error: 'Closing time has finished; the app is closing.' }; + // A switch asked for while the office is already closing: the closing + // carries on, now to open that business. + if (opts.switching) this.switching = opts.switching; // Re-pressed while running (e.g. from the timeout view): keep waiting, // unless Michael is gone, when waiting can never end. if (!this.getLiveAgentIds().includes(this.godId)) { @@ -172,6 +189,7 @@ export class ClosingTimeController { }) ); this.acked = new Set(); + this.toldAllIn = false; this.excused = new Set(); this.lastRemind = new Map(); this.concluded = false; @@ -181,6 +199,7 @@ export class ClosingTimeController { this.owedWaitNote = new Set(); this.active = true; this.relaunch = opts.relaunch === true; + this.switching = opts.switching ?? null; const names = [...this.workers] .map((id) => `${reg.agents[id]?.name ?? id} (${id})`) @@ -223,9 +242,24 @@ export class ClosingTimeController { return { ok: true }; } + /** + * The owner chose Switch now: stop waiting, quietly. The office is about to + * stop and open another business, so nobody is told to go back to work + * (a cancel would), and no event goes to the bar, which stays up until the + * app relaunches. Steers no hook boundary has read yet are dropped. + */ + stopForSwitch(): void { + if (!this.active) return; + this.cleanup(); + this.concluded = true; + this.control?.clearSteers(this.godId); + for (const id of this.workers) this.control?.clearSteers(id); + } + /** Human changed their mind — stand the floor back up. */ cancel(): void { if (!this.active) return; + this.switching = null; this.cleanup(); this.excused = new Set(); this.lastRemind = new Map(); @@ -488,6 +522,7 @@ export class ClosingTimeController { // Closed without, but confirmed anyway: it moves to confirmed. this.excused.delete(msg.from); this.emitProgress(); + this.tellMichaelAllIn(); } return; } @@ -528,6 +563,49 @@ export class ClosingTimeController { } } + /** + * Every team member has confirmed: Michael hears it from the app, naming + * them, once per closing. Seen live (2026-11-20): Michael moved his whole + * inbox to .done after reading one ACK, and the three that had just arrived + * went with it unread; the app had all four, Michael thought he was still + * waiting, and closing time hung. The app's own count is what lets the + * office close, so it says so. + */ + private tellMichaelAllIn(): void { + if (this.toldAllIn || this.concluded) return; + const reg = this.hive.registry(); + if (this.pendingIds(reg).length > 0) return; + this.toldAllIn = true; + const names = [...this.acked].map((id) => `${reg.agents[id]?.name ?? id} (${id})`).join(', ') || 'nobody'; + const note = (again: boolean): void => { + try { + this.hive.send({ + to: 'god', + act: 'inform', + subject: again ? 'Closing time: everyone has confirmed (again)' : 'Closing time: everyone has confirmed', + body: [ + `Every team member has sent CLOSING-TIME-ACK: ${names}. Their notes are in your inbox, or in inbox/.done if you moved them there.`, + 'Do not wait for anything more: update tasks.json and board.md now, then send CLOSING-TIME-COMPLETE ("to": "human").' + ].join('\n') + }, 'human'); + } catch (e) { console.error('[closing-time] telling Michael everyone confirmed', e); } + }; + note(false); + // Again while he has not closed: a note filed unread with the + // confirmations it followed held closing time (2026-11-20). + let left = ClosingTimeController.ALL_IN_REMINDERS; + const again = (): void => { + this.allInTimer = setTimeout(() => { + this.allInTimer = null; + if (!this.active || this.concluded || left <= 0) return; + left--; + note(true); + if (left > 0) again(); + }, ClosingTimeController.ALL_IN_REMIND_MS); + }; + again(); + } + private armTimeout(): void { if (this.timeoutTimer) clearTimeout(this.timeoutTimer); this.timeoutTimer = setTimeout(() => { @@ -538,6 +616,7 @@ export class ClosingTimeController { private cleanup(): void { if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); this.timeoutTimer = null; } if (this.teardownTimer) { clearTimeout(this.teardownTimer); this.teardownTimer = null; } + if (this.allInTimer) { clearTimeout(this.allInTimer); this.allInTimer = null; } this.active = false; } @@ -554,7 +633,8 @@ export class ClosingTimeController { notReporting, godId: this.godId, godLive: this.getLiveAgentIds().includes(this.godId), - relaunch: this.relaunch + relaunch: this.relaunch, + ...(this.switching ? { switching: this.switching } : {}) }; try { this.getWebContents()?.send('app:closingTime', ev); } catch { /* window tore down */ } } diff --git a/src/main/config.ts b/src/main/config.ts index 2837f8f34..c5993533f 100644 --- a/src/main/config.ts +++ b/src/main/config.ts @@ -17,6 +17,11 @@ import { MAX_AGENT_TOKEN_CAP } from '../shared/tokenCaps'; import { expandTilde, normalizeHiveHome } from './fs'; import { isHeldRename, RENAME_RETRY_MS, sleepSync, writeFileAtomic } from './atomicFile'; import type { IntegrationRecord } from '../shared/integrations'; +import { randomUUID } from 'node:crypto'; +import { businessKeySet, installKeySet, officeIdIn, officesWith, pick, settingsIn, type OfficeEntry, type OfficeSettings } from './officeKeys'; +import { ensureOfficeId, readOfficeId } from './officeFile'; +import { homeFolderStatus } from './homeFolder'; +import { claudeJsonFile, claudeSettingsDir } from './claudeHome'; /** A recurring schedule. The type and every rule about it (ownership, next run, * what a run sends) live in shared/missions.ts so main, preload and the @@ -253,6 +258,9 @@ export interface HarnessConfig { /** The owner's data classes that differ from the seeded defaults * (shared/dataClasses.ts): what the team may send to Research. */ dataClasses?: Partial>; + /** Always allowed (shared/publicTerms.ts): what the owner says is the + * business's own and public, kept as written by the privacy check. */ + researchPublic?: string[]; /** Team members that failed their first start, tried again (and only they) * on each later launch until they start. */ businessTeamRetry?: string[]; @@ -288,6 +296,11 @@ export interface HarnessConfig { * secret store under `apikey:anthropic` and handed to each Claude agent as * ANTHROPIC_API_KEY at start. */ claudeAuth?: 'account' | 'apiKey'; + /** This business's own Claude login (docs/designs/separate-businesses.md, + * BIZ-3, D4): 'own' keeps its sign in, connectors and conversations in its + * own Claude folder in the app's data folder; unset or 'shared' uses the + * Claude sign in the app already uses. A second account is a second plan. */ + claudeLogin?: 'shared' | 'own'; /** What the owner pays for their Claude plan a month, in USD (Settings > Agents). * Unset: the detected plan's list price. Pulse splits it by share of the work. */ planPriceMonthly?: number; @@ -412,6 +425,18 @@ export interface HarnessConfig { tvShowOffices?: boolean; /** Per-CLI-provider default model slug, used to pre-fill the model picker. */ providerDefaultModels?: Partial>; + /** Each business's own settings, by office id (src/main/officeSettings.ts, + * docs/designs/separate-businesses.md). Read and written only through + * officeSettings / updateOfficeSettings. */ + offices?: Record; + /** Set when the business settings that used to sit at the top level were + * moved into `offices` (migrateToOfficeSettings). Its version, 1. */ + officesMigrated?: number; + /** This business's identity came from its office.json when settings moved + * per office, but its mailboxes, schedules, grants and connectors were + * another business's and were not carried over: tell the owner once, on + * first open (docs/designs/separate-businesses.md, D11). */ + setupNoticePending?: boolean; } @@ -442,6 +467,12 @@ const DEFAULTS: HarnessConfig = { knowledgeGraph: { enabled: true } }; +/** A fresh copy of the defaults: nested values (missions, knowledgeGraph) are + * not shared with DEFAULTS, so a caller may change what it gets. */ +export function configDefaults(): HarnessConfig { + return structuredClone(DEFAULTS); +} + function configPath(): string { return join(app.getPath('userData'), 'config.json'); } @@ -480,7 +511,14 @@ function dropRemovedWebhookData(p: string, parsed: T): T { return next as T; } -export function readConfig(): HarnessConfig { +/** + * config.json as stored, with the defaults filled in. Before the move to per + * office settings (officesMigrated unset) this is what every reader sees; after + * it, only the install part is meant to be read from here, and the business + * settings live in `offices`. readConfig() is the view to use; this is for the + * code that files settings by office (officeSettings.ts). + */ +export function readStoredConfig(): HarnessConfig { const p = configPath(); // No file yet = a first run with nothing to migrate; the defaults ARE the // post-migration shape. Deliberately does not persist — a bare read must not @@ -495,6 +533,103 @@ export function readConfig(): HarnessConfig { } } +/** + * The config every reader sees. Before the move it is config.json as today. + * After it, the install fields come from the top of config.json and the + * business fields from the open office's own entry (its saved ones over the + * defaults), so the same readConfig().businessName, .mailboxes or .missions + * read the business that is open, and no reader can read another one's + * (docs/designs/separate-businesses.md). Other businesses' entries are never + * part of it. + */ +export function readConfig(): HarnessConfig { + return configView(readStoredConfig()); +} + +function businessPart(cfg: HarnessConfig): Partial { + return pick(cfg, businessKeySet) as Partial; +} + +/** The open office's id once settings are per office; null before the move, + * or when no office is open. */ +export function openOfficeId(stored: HarnessConfig = readStoredConfig()): string | null { + if (!stored.officesMigrated) return null; + return officeIdIn(stored, readOfficeId(stored.harnessHome)); +} + +/** + * Where the app keeps one of its own files or folders that belong to a + * business (journals, dock keys, pasted images, check folders, knowledge): + * `userData/offices//` for the open office once settings are per + * office, else `userData/` as before. After the move with no office open + * (the missing office screen), `userData/offices/none/`: never another + * business's, and nothing runs there. + */ +export function officeDataPath(name: string): string { + const stored = readStoredConfig(); + const userData = app.getPath('userData'); + if (!stored.officesMigrated) return join(userData, name); + return join(userData, 'offices', openOfficeId(stored) ?? 'none', name); +} + +/** A business's own files in the app's data folder from before the move. */ +export const BUSINESS_DATA_FILES = [ + 'mail-send-journal.json', 'broker-write-journal.json', 'mail-proposals.json', 'owner-dock-keys.json', 'pastes', 'knowledge' +] as const; + +/** + * At the move: put these files and folders of the app's data folder into the + * office's own place (officeDataPath), so the business keeps its journals, + * approvals, pasted images and knowledge. One already there is kept (a move + * that stopped midway and runs again). False when one could not be moved. + */ +export function moveIntoOffice(id: string, names: readonly string[]): boolean { + const userData = app.getPath('userData'); + const moved: Array<[string, string]> = []; + for (const name of names) { + const from = join(userData, name); + const to = join(userData, 'offices', id, name); + try { + if (!existsSync(from) || existsSync(to)) continue; + mkdirSync(dirname(to), { recursive: true }); + renameSync(from, to); + moved.push([from, to]); + } catch (e) { + console.error(`[config] could not move ${name} into the office:`, e); + // All or none: the move did not finish, so the app runs on the old + // places this launch; what this run moved goes back there. + for (const [back, there] of moved.reverse()) { + try { renameSync(there, back); } catch (err) { console.error(`[config] could not move ${there} back:`, err); } + } + return false; + } + } + return true; +} + +function configView(stored: HarnessConfig): HarnessConfig { + const { offices: _offices, ...rest } = stored; + if (!stored.officesMigrated) return rest as HarnessConfig; + const id = openOfficeId(stored); + const install = pick(rest, installKeySet); + return dropRetiredMissions({ ...install, ...settingsIn(stored, id, businessPart(DEFAULTS)) } as HarnessConfig); +} + +/** + * The office id business settings are saved under for this folder: its own + * (office.json), else the entry last opened from it, else a new one. A folder + * that holds an office gets the new id in its office.json at once; one that + * does not yet (setup has not made it) keeps it in the entry, and the office + * takes it when it is made (adoptOpenOffice). Null with no folder at all. + */ +function officeIdForSave(stored: HarnessConfig, home: string | null | undefined): string | null { + if (!home) return null; + const known = officeIdIn({ harnessHome: home, offices: stored.offices }, readOfficeId(home)); + if (known) return known; + if (homeFolderStatus(home).hasOffice) return ensureOfficeId(home); + return randomUUID(); +} + /** (#140, the upgrade path) A config.json persisted BEFORE `writeConfig` * learned to expand `~` still holds literal `~/…` strings in `harnessHome` / * `recentHives`, and nothing rewrites the file until the next write — so the @@ -587,7 +722,7 @@ function persistConfig(patched: HarnessConfig): HarnessConfig { // Saving one setting stores only that setting, so fill the rest back in first: // subscribers must see the same complete config a read gives them, never a // half-filled one. - const view = normalizeStoredHomes({ ...DEFAULTS, ...next }); + const view = configView(normalizeStoredHomes({ ...DEFAULTS, ...next })); // The change is already saved, so one failed subscriber must not fail the save // for its caller, nor stop the subscribers after it. for (const listener of configWriteListeners) { @@ -596,8 +731,30 @@ function persistConfig(patched: HarnessConfig): HarnessConfig { return next; } +/** Save this whole config in place of the stored one: unlike writeConfig, a + * field left out is removed. Only the move to per office settings uses it. */ +export function replaceConfig(next: HarnessConfig): HarnessConfig { + return persistConfig(next); +} + +/** Copy config.json, as it is on disk, to `name` beside it, unless that copy + * already exists (the first copy is the one to keep). True when the copy is + * there afterwards, or there was no config.json to copy. */ +export function keepConfigCopy(name: string): boolean { + const p = configPath(); + const copy = join(dirname(p), name); + try { + if (existsSync(copy) || !existsSync(p)) return true; + copyFileSync(p, copy); + return existsSync(copy); + } catch (e) { + console.error(`[config] could not keep a copy as ${name}:`, e); + return false; + } +} + export function writeConfig(patch: Partial): HarnessConfig { - const current = readConfig(); + const current = readStoredConfig(); const next: HarnessConfig = { ...current, ...patch }; // Project INGESTION — a registered repo is typed by hand ("~/dev/foo") as often // as it is picked from the folder dialog. Expand `~` here so the persisted list @@ -624,7 +781,32 @@ export function writeConfig(patch: Partial): HarnessConfig { next.harnessHome = home; next.recentHives = recentHives; } - return persistConfig(next); + if (!current.officesMigrated) return configView(persistConfig(next)); + return configView(persistConfig(routedToOffice(current, next, patch))); +} + +/** + * After the move: the business fields of a save go to the open office's entry + * (the folder being opened, when the save also sets harnessHome), and the top + * of config.json keeps install fields only. A business field saved with no + * folder at all has nowhere to go and is left out. + */ +function routedToOffice(current: HarnessConfig, merged: HarnessConfig, patch: Partial): HarnessConfig { + // `merged` has the save applied (registeredRepos and harnessHome cleaned up). + const business: Record = {}; + for (const k of Object.keys(patch)) if (businessKeySet.has(k)) business[k] = (merged as unknown as Record)[k]; + const top: Record = { ...merged }; + for (const k of businessKeySet) delete top[k]; + const out = top as unknown as HarnessConfig; + if (Object.keys(business).length === 0) return out; + const home = out.harnessHome; + const id = officeIdForSave(current, home); + if (!home || !id) { + console.error('[config] business settings with no office to save them in were left out:', Object.keys(business).join(', ')); + return out; + } + out.offices = officesWith(out, id, home, business) as Record; + return out; } /** Set or clear one agent's token ceiling against the latest config on disk. @@ -652,14 +834,22 @@ export function setAgentTokenCap(agentId: unknown, tokenCap: unknown): HarnessCo const agentTokenCaps = { ...(current.agentTokenCaps ?? {}) }; if (tokenCap === undefined) delete agentTokenCaps[agentId]; else agentTokenCaps[agentId] = tokenCap; - return persistConfig({ - ...current, - agentTokenCaps - }); + return writeConfig({ agentTokenCaps }); } /** Wipe the persisted config back to first-run defaults so the app boots into * onboarding again. Used by the "reset & start over" flow. */ +/** A factory reset of the open business once settings are per office: its + * entry goes, the install settings and every other business stay. Before the + * move (no id) it is resetConfig(). */ +export function forgetOffice(id: string | null): HarnessConfig { + const stored = readStoredConfig(); + if (!id || !stored.officesMigrated) return resetConfig(); + const offices = { ...(stored.offices ?? {}) }; + delete offices[id]; + return configView(persistConfig({ ...stored, offices })); +} + export function resetConfig(): HarnessConfig { // Saved like any other change, so a reset announces itself too. persistConfig({ ...DEFAULTS }); @@ -722,7 +912,9 @@ export function ensureHarnessHome(path: string): { ok: boolean; error?: string } } function ensureClaudeGlobalPermissions(home: string): void { - const dir = join(home, '.claude'); + // The folder Claude really uses (CLAUDE_CONFIG_DIR, for a business with its + // own login or an owner's export), else ~/.claude (claudeHome.ts). + const dir = claudeSettingsDir(home); const p = join(dir, 'settings.json'); try { let s: Record = {}; @@ -752,7 +944,10 @@ type ClaudeConfig = Record & { projects?: Record boolean): boolean { - const p = join(home, '.claude.json'); + // `/.claude.json` when one is set, else ~/.claude.json: + // an approval written where Claude does not read stops every agent at the + // trust question (claudeHome.ts). + const p = claudeJsonFile(home); // Claude Code writes this file too. Write a copy beside it and swap it in, so // a crash never leaves it half written, and start again (up to three times) // when Claude changed it between our read and our write, so its edit is kept. diff --git a/src/main/db.ts b/src/main/db.ts index 5fea5c2cb..c092f487b 100644 --- a/src/main/db.ts +++ b/src/main/db.ts @@ -200,6 +200,20 @@ const MIGRATIONS: Array<(db: Database.Database) => void> = [ } ]; +/** The tables whose rows belong to one office (the `office` column). */ +export const OFFICE_TABLES = [ + 'telemetry_events', 'telemetry_runs', 'telemetry_daily', 'telemetry_failures', 'telemetry_dismissed', + 'telemetry_applied', 'telemetry_safety', 'cost_ledger', 'owner_notes' +] as const; + +/** kv keys that end in the office they belong to (the cost ledger's import + * mark, Pulse's backfill mark and processor position, the run comparison's + * suggestions). pulse-office-id.test.cjs fails when a new one is not listed. */ +export const OFFICE_KV_PREFIXES = ['cost-ledger:import:', 'pulse:backfill:', 'pulse:state:', 'run-compare:'] as const; + +/** The kv key that marks an office's rows as moved from its folder to its id. */ +const relabelledKey = (id: string): string => `office:relabelled:${id}`; + export class PersistStore { private db: Database.Database | null = null; @@ -246,6 +260,77 @@ export class PersistStore { * telemetry), or null when it is closed or failed to open. */ database(): Database.Database | null { return this.db; } + /** Every row one office wrote (Pulse, the cost ledger, owner notes), in one + * transaction: a factory reset of one business leaves the others' history. + * True when they are gone (or the store is closed and there is nothing to + * do here). */ + eraseOffice(office: string): boolean { + const db = this.db; + if (!db) return false; + try { + db.transaction(() => { + for (const t of OFFICE_TABLES) db.prepare(`DELETE FROM ${t} WHERE office = ?`).run(office); + for (const p of OFFICE_KV_PREFIXES) db.prepare('DELETE FROM kv WHERE key = ?').run(p + office); + db.prepare('DELETE FROM kv WHERE key = ?').run(relabelledKey(office)); + })(); + return true; + } catch (e) { + console.error('[db] could not erase the office rows:', e); + return false; + } + } + + /** + * Once settings are per office, Pulse keys an office's rows by its lasting id + * instead of its folder (docs/designs/separate-businesses.md, E5), so moving + * the folder keeps its history. This moves the rows and kv marks written + * under the folder (`from`) to the id (`to`), once per id, in one + * transaction. A row the id already has for the same key stays as it is. + * True when the rows are under the id now (moved now or before); false when + * the store is closed or the move failed (nothing changed; next launch tries + * again). + */ + relabelOffice(from: string, to: string): boolean { + const db = this.db; + if (!db || !from || !to || from === to) return false; + try { + if (db.prepare('SELECT 1 FROM kv WHERE key = ?').get(relabelledKey(to))) return true; + db.transaction(() => { + for (const t of OFFICE_TABLES) db.prepare(`UPDATE OR IGNORE ${t} SET office = ? WHERE office = ?`).run(to, from); + for (const p of OFFICE_KV_PREFIXES) { + const had = db.prepare('SELECT 1 FROM kv WHERE key = ?').get(p + to); + if (!had) db.prepare('UPDATE kv SET key = ? WHERE key = ?').run(p + to, p + from); + } + db.prepare('INSERT OR REPLACE INTO kv (key, value, updated_at) VALUES (?, ?, ?)').run(relabelledKey(to), JSON.stringify(from), Date.now()); + })(); + return true; + } catch (e) { + console.error('[db] could not move the office rows to its id:', e); + return false; + } + } + + /** + * A restore on a computer whose home folder differs (backup.ts): office rows + * and marks filed under a folder in the old home move to the same folder in + * this one. Office ids (once settings are per office) are not paths and stay. + */ + movePathPrefix(from: string, to: string): void { + const db = this.db; + if (!db || !from || !to || from === to) return; + const n = from.length; + db.transaction(() => { + for (const t of OFFICE_TABLES) { + db.prepare(`UPDATE OR IGNORE ${t} SET office = ? || substr(office, ?) WHERE office = ? OR substr(office, 1, ?) = ?`) + .run(to, n + 1, from, n + 1, `${from}/`); + } + for (const p of OFFICE_KV_PREFIXES) { + db.prepare('UPDATE OR IGNORE kv SET key = ? || ? || substr(key, ?) WHERE key = ? OR substr(key, 1, ?) = ?') + .run(p, to, p.length + n + 1, p + from, p.length + n + 1, `${p}${from}/`); + } + })(); + } + // ─── kv (scalar app state) ───────────────────────────────────────────────── /** Read a JSON-decoded scalar, or undefined if absent/unparseable. */ diff --git a/src/main/factoryReset.ts b/src/main/factoryReset.ts index 6e2e58819..5e631611a 100644 --- a/src/main/factoryReset.ts +++ b/src/main/factoryReset.ts @@ -101,6 +101,9 @@ export const APP_DATA_ENTRIES = [ 'slack-reply.json', 'slack-done-notified.json', 'slack-files', 'pastes', + // A business's own Claude login (separate-businesses.md, E6). Only ever in + // its office's place (offices//claude), which a reset erases whole. + 'claude', ...CHECK_FOLDERS ] as const; @@ -153,7 +156,7 @@ function setAsideJournals(userData: string): string[] { * hive and palace where they resolve, Research's and the checks' Claude Code * conversations). Returns the paths it could not remove; a reset carries on * past them rather than stopping half way. */ -export function eraseOfficeData(p: { home: string | null; userData: string; extra?: string[]; knowledgeRoot?: string | null }): string[] { +export function eraseOfficeData(p: { home: string | null; userData: string; extra?: string[]; knowledgeRoot?: string | null; officeId?: string | null }): string[] { const home = p.home && isOfficeFolder(p.home) ? p.home : null; // Company knowledge the owner moved out of the app's data folder: its store's // own entries, and only when it really is one. @@ -166,9 +169,13 @@ export function eraseOfficeData(p: { home: string | null; userData: string; extr ...(home ? PRIVATE_ENTRIES.map((n) => join(privateRoot(home), n)) : []), // Only the app's own office record, never an owner's file of that name. ...(home && readOfficeRecord(home) ? [officeRecordPath(home)] : []), - ...APP_DATA_ENTRIES.map((n) => join(p.userData, n)), - // A damaged connected app write journal the broker set aside (brokerWriteOnce.ts). - ...setAsideJournals(p.userData), + // Once each business keeps its own files (separate-businesses.md), only this + // office's place in the app's data folder goes, and the attachments the owner + // opened; the shared database, secrets file and other offices stay (their + // rows and keys are erased by office in the reset itself). + ...(p.officeId + ? [join(p.userData, 'offices', p.officeId), join(p.userData, 'opened-attachments')] + : [...APP_DATA_ENTRIES.map((n) => join(p.userData, n)), ...setAsideJournals(p.userData)]), ...(p.extra ?? []).filter(Boolean) ]; const failed: string[] = []; diff --git a/src/main/foundations.ts b/src/main/foundations.ts index 1a7d79ead..4b34fdd61 100644 --- a/src/main/foundations.ts +++ b/src/main/foundations.ts @@ -24,7 +24,7 @@ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } import { privateRoot } from '../shared/agentPrivatePaths'; import { writeFileAtomic } from './atomicFile'; import { - FIT_PICTURES, FIT_TEXT_MAX, FOLDER_REF, FOUNDATION_FILE_TAG, FOUNDATION_QUESTIONS, FOUNDATIONS_TAG, FOUNDATIONS_TITLE, RETIRED_IDS, SEEN_ITEM_MAX, SEEN_LATER_MS, capFor, systemAnswerable, cleanRecord, emptyRecord, fileAnswerLine, folderAnswerLine, isExpired, isFoundationId, isFoundationsDoc, isLater, isListQuestion, isSettled, itemKey, joinListLines, listState, oneLine, questionOf, questionVersion, questionsFor, renderFoundations, + FIT_PICTURES, FIT_TEXT_MAX, FOLDER_REF, FOUNDATION_FILE_TAG, FOUNDATION_QUESTIONS, FOUNDATIONS_TAG, FOUNDATIONS_TITLE, RETIRED_IDS, SEEN_ITEM_MAX, SEEN_LATER_MS, capFor, systemAnswerable, cleanRecord, emptyRecord, fileAnswerLine, folderAnswerLine, isExpired, isFoundationId, isFoundationsDoc, isLater, isListQuestion, isSettled, itemKey, joinListLines, listLines, listState, oneLine, questionOf, questionVersion, questionsFor, renderFoundations, type Coverage, type FoundationAnswer, type FoundationId, type FoundationJob, type FoundationPast, type FoundationSourceKind, type FoundationsRecord, type FoundationsView, type SeenItem } from '../shared/foundations'; import { IMAGES, type DocExtraction } from './docText'; @@ -110,6 +110,12 @@ const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', const monthName = (m: number): string => MONTHS[m - 1].charAt(0).toUpperCase() + MONTHS[m - 1].slice(1); /** The profile fields a question shares, both ways. */ +/** The seen items a list answer does not name yet, matched on their key. */ +function notListed(items: SeenItem[], text: string): SeenItem[] { + const on = new Set(listLines(text).map(itemKey)); + return items.filter((s) => !on.has(itemKey(s.item))); +} + const PROFILE_LINKS: Array<{ id: FoundationId; read: (p: ProfileFacts) => string | undefined; write: (text: string) => ProfileFacts | null }> = [ { id: 'hours', @@ -194,6 +200,9 @@ export class Foundations { private cache: { home: string; rec: FoundationsRecord } | null = null; private timer: ReturnType | null = null; private expiryCheckedAt = 0; + /** Seen items the owner added on a card this run, kept so Undo can bring + * each back; an add from before a restart stays (Undo is gone with its row). */ + private addedSeen = new Map(); constructor(private readonly d: FoundationsDeps) {} @@ -335,11 +344,12 @@ export class Foundations { } /** What the owner's save of a list card means (design review D4): the seen - * items added go; every other one must be put off, and then the list stays - * known so far. One left undecided refuses the save. */ - private ownerCoverage(rec: FoundationsRecord, id: FoundationId, added: unknown): CoverageDecision { + * items added go, and so does any the saved list already names (the card + * may have lost which ones it added); every other one must be put off, and + * then the list stays known so far. One left undecided refuses the save. */ + private ownerCoverage(rec: FoundationsRecord, id: FoundationId, added: unknown, text: string): CoverageDecision { const ids = new Set(Array.isArray(added) ? added.filter((x): x is string => typeof x === 'string') : []); - const remaining = (rec.seen[id] ?? []).filter((s) => !ids.has(s.id)); + const remaining = notListed(rec.seen[id] ?? [], text).filter((s) => !ids.has(s.id)); const now = this.now(); if (remaining.some((s) => !isLater(s, now))) return { ok: false }; return { ok: true, remaining, coverage: remaining.length ? 'known' : 'complete' }; @@ -360,6 +370,19 @@ export class Foundations { const answers = { ...rec.answers }; let history = rec.history; let changed = first; + // A seen item the saved list already names is settled: an older card + // saved the item but kept it waiting (owner report, 18 Nov). + let seen = rec.seen; + for (const id of Object.keys(rec.seen) as FoundationId[]) { + const a = answers[id]; + const items = rec.seen[id] ?? []; + if (!a || !isListQuestion(id) || !items.length) continue; + const kept = notListed(items, a.text); + if (kept.length === items.length) continue; + seen = { ...seen }; + if (kept.length) seen[id] = kept; else delete seen[id]; + changed = true; + } for (const id of Object.keys(answers) as FoundationId[]) { const a = answers[id]; if (!a || !isListQuestion(id)) continue; @@ -374,7 +397,7 @@ export class Foundations { changed = true; } } - if (changed) { this.save({ ...rec, answers, history, ...(first ? { listsAt: this.iso() } : {}) }); this.publishSoon(); } + if (changed) { this.save({ ...rec, answers, history, seen, ...(first ? { listsAt: this.iso() } : {}) }); this.publishSoon(); } } /** @@ -427,13 +450,24 @@ export class Foundations { if (this.d.canTell && !this.d.canTell()) return; let rec = this.read(); const due = RETIRED_IDS.filter((id) => rec.answers[id] && !rec.answers[id]!.retiredNoticeAt); - if (!due.length) return; + // A retired question the work hit while it was empty: the hit goes, so it + // is never brought back, and Michael withdraws any card it raised. + const hitOnly = RETIRED_IDS.filter((id) => rec.hits[id] && !rec.answers[id]); + if (!due.length && !hitOnly.length) return; const at = this.iso(); for (const id of due) { const a = rec.answers[id]!; rec = { ...rec, answers: { ...rec.answers, [id]: { ...a, retiredNoticeAt: at } } }; } + if (hitOnly.length) { + const hits = { ...rec.hits }; + for (const id of hitOnly) delete hits[id]; + rec = { ...rec, hits }; + } this.save(rec); + for (const id of hitOnly) { + this.toMichael('Foundation question retired', `"${FOUNDATION_QUESTIONS[id].text}" (${id}) is no longer a company foundations question: the list now lives with the member whose role keeps it, so the owner is not asked it. Withdraw any open foundation card for it and raise none again.`); + } for (const id of due) { const a = rec.answers[id]!; const seen = (rec.seen?.[id] ?? []).map((s) => s.item); @@ -513,7 +547,7 @@ export class Foundations { this.publishSoon(); return { ok: true }; } - const cov = this.ownerCoverage(rec, id, added); + const cov = this.ownerCoverage(rec, id, added, a.text); if (!cov.ok) return { ok: false, error: 'undecided' }; this.save(this.withAnswer(rec, id, { ...a, ...this.coverageFields(id, cov.coverage) }, null, { seen: cov.remaining })); if (typed) this.toProfile(id, typed, true); @@ -522,13 +556,17 @@ export class Foundations { return { ok: true, complete: cov.coverage === 'complete' }; } - /** What the owner did with a seen item on a list card: Not ours and Decide - * later are saved at once, each with its own undo (design review D4, D7). */ - seenAction(id: unknown, seenId: unknown, action: unknown): { ok: boolean } { + /** What the owner did with a seen item on a list card: Add, Not ours and + * Decide later are each saved at once, with their own undo (design review + * D4, D7), so an owner who settles a few today keeps them. Add puts the item + * on the saved list, known so far: only Save says it is the whole list. + * `text` is the saved list after an Add or its undo. */ + seenAction(id: unknown, seenId: unknown, action: unknown): { ok: boolean; text?: string; error?: 'too-long' } { if (!isFoundationId(id) || typeof seenId !== 'string' || !seenId || !this.file()) return { ok: false }; const rec = this.read(); const seen = rec.seen[id] ?? []; const notOurs = rec.notOurs[id] ?? []; + if (action === 'add' || action === 'undoAdd') return isListQuestion(id) ? this.seenAdd(rec, id, seenId, action === 'undoAdd') : { ok: false }; const put = (nextSeen: SeenItem[], nextNot = notOurs): void => { const s2 = { ...rec.seen }, n2 = { ...rec.notOurs }; if (nextSeen.length) s2[id] = nextSeen; else delete s2[id]; @@ -559,6 +597,46 @@ export class Foundations { return { ok: false }; } + /** Add a seen item to the saved list, or undo that while the app runs: the + * item goes on as its own line (once, matched on its key), the seen item + * goes, and the answer stays the owner's, known so far. Undo takes the line + * off again and brings the seen item back. */ + private seenAdd(rec: FoundationsRecord, id: FoundationId, seenId: string, undo: boolean): { ok: boolean; text?: string; error?: 'too-long' } { + const had = rec.answers[id]; + const lines = had ? listLines(had.text) : []; + const seen = rec.seen[id] ?? []; + const key = `${id}\u0000${seenId}`; + const s = undo ? this.addedSeen.get(key) : seen.find((x) => x.id === seenId); + if (!s) return { ok: false }; + const k = itemKey(s.item); + let next = lines; + if (undo) { + const i = lines.map(itemKey).lastIndexOf(k); + if (i >= 0) next = [...lines.slice(0, i), ...lines.slice(i + 1)]; + } else if (!lines.some((l) => itemKey(l) === k)) next = [...lines, s.item]; + const text = joinListLines(next.join('\n')); + if (text.length > capFor(id)) return { ok: false, error: 'too-long' }; + const nextSeen = undo ? (seen.some((x) => x.id === seenId) ? seen : [...seen, s]) : seen.filter((x) => x !== s); + let out: FoundationsRecord; + if (text) { + const a: FoundationAnswer = { text, by: 'owner', source: 'owner', at: this.iso(), ...(had?.ref ? { ref: had.ref } : {}), ...this.coverageFields(id, 'known') }; + out = this.withAnswer(rec, id, a, null, { seen: nextSeen }); + // The card is still open: the next seen item needs no new note to Michael. + if (rec.hits[id]) out = { ...out, hits: { ...out.hits, [id]: rec.hits[id]! } }; + } else { + // The undo took off the only line: the list is empty again. + const answers = { ...rec.answers }; + delete answers[id]; + const s2 = { ...rec.seen }; + if (nextSeen.length) s2[id] = nextSeen; else delete s2[id]; + out = { ...rec, answers, seen: s2, history: had ? this.withPast(rec, id, had) : rec.history }; + } + this.save(out); + this.publishSoon(); + if (undo) this.addedSeen.delete(key); else this.addedSeen.set(key, s); + return { ok: true, text }; + } + /** A file the owner adds on the card (D2, D3, D4, D5, D10): read it once; * an unreadable file stops here with its reason. A picture is shown to the * check as a picture, anything else by its text. Only a file the check @@ -691,6 +769,8 @@ export class Foundations { if (!isFoundationId(id)) return `No company foundations question "${String(id ?? '')}". Use an id from your COMPANY FOUNDATIONS context, in square brackets after each question.`; const q = FOUNDATION_QUESTIONS[id].text; if (p.retired === 'kept') return this.retiredKept(from, id); + // A retired question takes no new answer, gap or draft, from Michael either. + if (questionOf(id).retired) return `"${q}" is retired: that list lives with the member whose role keeps it. Send nothing more for it.`; if (typeof p.gap === 'string' || typeof p.item === 'string') return this.gap(from, id, typeof p.gap === 'string' ? p.gap : '', p.item, p.source); // A draft comes only from the member the owner asked, or Michael (draft()). if (typeof p.draft === 'string') return this.draft(from, id, p.draft); diff --git a/src/main/hive.ts b/src/main/hive.ts index bc2e12d9e..78a001fc2 100644 --- a/src/main/hive.ts +++ b/src/main/hive.ts @@ -1,3 +1,4 @@ +import { MAX_KEPT_OPEN, type ResearchKept } from '../shared/researchKept'; /** * The Hive — the on-disk multi-agent coordination layer. * @@ -19,10 +20,11 @@ * Everything here runs in the Electron main process. */ import { placeLinkRule } from '../shared/settingsPlaces'; +import { claudeSettingsDir } from './claudeHome'; import { WEB_SETTINGS_UNREADABLE, WEB_TOOLS, type SandboxNetwork } from '../shared/webAccess'; import { addressedToResearch, ANSWER_UNCHECKED, ANSWER_UNCHECKED_SUBJECT, hasAttachments, looksLikeInjection, NOT_SENT_SUBJECT, - PRIVACY_CHECK_SENDER, REFUSAL_CHECK_FAILED, REFUSAL_FILES, REFUSAL_NOT_DELIVERED, REFUSAL_OFF, REFUSAL_TOO_LONG, RESEARCH_HOUSE_RULE, RESEARCH_ID, RESEARCH_REPLY_LABEL, + PRIVACY_CHECK_SENDER, REFUSAL_CHECK_FAILED, REFUSAL_FILES, REFUSAL_NOT_DELIVERED, REFUSAL_NOT_RUNNING, REFUSAL_OFF, REFUSAL_TOO_LONG, RESEARCH_HOUSE_RULE, RESEARCH_ID, RESEARCH_REPLY_LABEL, RESEARCH_UNCHECKED_TOOL, NOT_SENT_SUBJECT_OUT, RESEARCH_ONLY_ASKERS, RESEARCH_NAME, RESEARCH_ROLE, isReservedName, SENT_AS_SUBJECT, sentAsBody, nameKey, researchText, cleanResearchName, RESEARCH_ONLY_SKILLS } from '../shared/research'; @@ -433,14 +435,17 @@ export function michaelInstructions(name: string, b: PromptBusiness, p: PromptPa '', '## Company foundations', 'The company foundations are one document of questions each job needs answered about this business, such as who we sell to or our financial year, each answered once for the whole office. The app gives you the whole document at the start of each session and when it changes, with the empty questions the work hit, and gives each team member its own job\'s part. The app alone writes it: answers reach it from the owner\'s foundation cards and from what the team learns. When an answer names a company knowledge document, read it with get before work that depends on that answer.', - 'When a team member\'s work needs an empty question, the app tells you the first time ("Foundation gap"). Raise one card for it on Ask me unless one is open for that question, never one per task or per member: title it with the question, assign it to the team member whose work hit it, and give it one humanQA entry {"kind": "foundation", "foundation": "", "q": "", "askedAt": "