Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
write changelog entries as per-branch fragments so parallel agents stop conflicting
[._.]/ Adam Eivyf888f8da5e79
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f5b9139971..8a464c41b3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,3 +1,8 @@+<!-- Do NOT append a new entry here on a branch — parallel agents collide and the merge conflicts.+ Run: npm run changelog:add -- <added|changed|fixed|removed> "entry text"+ That writes .changelog/next/<section>-<branch>.md, which merges cleanly. See .changelog/README.md.+ npm run changelog:collect folds the fragments back into this file before a release. -->+## Added- CoS now notices when a scheduled task (the overnight branch-reconcile loop) finishes the same work over and over in short-lived agent runs. It parks a looping coordinator so it stops burning quota and keeps the per-run duration signal local for a future Layered Intelligence run to assess and, only when justified, turn into a concrete planned fix.diff --git a/.changelog/README.md b/.changelog/README.mdindex 0f0d152503..cd29f6a576 100644--- a/.changelog/README.md+++ b/.changelog/README.md@@ -6,13 +6,88 @@ This directory contains detailed release notes for each version of PortOS.## Structure+### next/ — Where You Write Your Entry++**Write your changelog entry as a fragment file, not by appending to `NEXT.md`.**++```bash+npm run changelog:add -- fixed "Notifications panel no longer clips on a phone."+```++That writes `.changelog/next/fixed-<your-branch>.md`. Sections are `added`,+`changed`, `fixed`, `removed`.++The slug defaults to the last segment of your current branch (`claim/issue-3916`+→ `issue-3916`, `cos/task-x/agent-d3651f27` → `agent-d3651f27`), which is already+unique per unit of work. Pass `--slug <slug>` to override — required on a+detached HEAD, since there is no branch name to derive from. Adding a second+entry for the same branch and section appends to the same file rather than+creating another one.++Writing the file by hand is fine too; the CLI just gets the name and the bullet+formatting right.++#### Why fragments++Every parallel agent, `/claim` worktree, and swarm worker used to append a+bullet to the end of the same section of the same file. Two branches cut from+the same base therefore added different lines in the same place — the textbook+shape of a merge conflict. Every second PR of a parallel run stalled on a+hand-resolved changelog, and conflict markers have reached `main` more than once.++Ordering conventions do not fix this. Alphabetizing by agent id, or leaving a+blank line between entries, still leaves both branches editing adjacent lines,+and git's three-way merge conflicts on adjacent changed hunks regardless of what+the lines say. The only structural fix is for two branches never to write the+same file: **git merges by path**, so two different paths always merge cleanly.++This is the same fragment/"news file" pattern used by towncrier, reno, and+changesets. `scripts/changelogFragments.js` carries the implementation notes.++#### Collecting before a release++`npm run changelog:collect` folds every fragment into `NEXT.md` under its+matching heading (creating the heading when absent) and deletes the fragments.+**Run it before `/do:release`.**++`npm run changelog:preview` prints the same result and changes nothing, which is+how to read the full set of unreleased notes while entries are still split+across fragments.++Collection is append-only and deterministic — fragments are folded in filename+order, so two installs collecting the same set produce identical output. Nothing+is lost by forgetting to collect: uncollected fragments simply ride along to the+next release.++#### Why `NEXT.md` is deliberately not union-merged++`.gitattributes` marks `.changelog/next/*.md` with git's built-in `union` merge+driver. That covers the one residual fragment collision: two branches whose+names share a last segment derive the same slug and write the same file, where+keeping both bullets is the right answer. A fragment is short-lived — created on+a branch, deleted at collection — so it has no cross-release failure mode.++`NEXT.md` is **not** union-merged, and that is on purpose even though it looks+like the same append-only shape. `/do:release` renames `NEXT.md` to+`v{version}.md` and starts a fresh one, and git does not pair that rename+because the path still exists on `main`. Any branch that outlives a release is+therefore a plain modify/modify on `NEXT.md`, and union resolves it by keeping+both sides — reviving the **entire previous release's entries** into the next+release's notes, cleanly, with no conflict and no warning. Verified both ways:+with union the merge succeeds and republishes the old entries; without it git+raises a conflict, which is the correct outcome.++So a direct append to `NEXT.md` on a branch still conflicts with a parallel one.+That is not a gap to be patched — it is the reason to write fragments.+### NEXT.md — Unreleased Changes Accumulator-During development, all changelog entries are appended to `NEXT.md`. This file accumulates changes across multiple commits until a release is created.+`NEXT.md` accumulates collected entries across multiple commits until a release+is created.-- During development, append changelog entries to `NEXT.md` under the appropriate section (Added, Changed, Fixed, Removed)- `/do:release` (a Claude Code slash command skill) renames `NEXT.md` to `v{version}.md` and finalizes it with the version number and release date. The release workflow then uses this versioned file for the GitHub release notes- Do NOT create versioned changelog files manually — `/do:release` handles that+- Editing `NEXT.md` directly still works, and is the right move when correcting an entry that is already collected. For a *new* entry on a branch, write a fragment instead### Versioned Files@@ -68,9 +143,14 @@ The GitHub Actions release workflow (`.github/workflows/release.yml`) automatica## Development Workflow-1. **During Development**: Append entries to `NEXT.md` under the appropriate section (Added, Changed, Fixed, Removed)+1. **During Development**: `npm run changelog:add -- <section> "entry"` writes a+ per-branch fragment under `.changelog/next/`. Never append a new entry to+ `NEXT.md` on a branch — that is what makes parallel agents collide.++2. **Before Release**: `npm run changelog:collect` folds the fragments into+ `NEXT.md`. This is the first step of `/do:release`.-2. **During Release** (`/do:release`):+3. **During Release** (`/do:release`):- Determines the version bump from conventional commit prefixes- Bumps `package.json` version- Renames `NEXT.md` → `v{new_version}.md`diff --git a/.changelog/next/.gitkeep b/.changelog/next/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/.changelog/next/added-agent-d3651f27.md b/.changelog/next/added-agent-d3651f27.mdnew file mode 100644index 0000000000..2cb533dab2--- /dev/null+++ b/.changelog/next/added-agent-d3651f27.md@@ -0,0 +1 @@+- Changelog entries are now written as one small file per branch under `.changelog/next/` instead of being appended to the end of a shared file. Parallel agents each wrote their entry into the same place in `NEXT.md`, so their branches conflicted on merge — routinely stalling every second pull request of a parallel run, and more than once landing conflict markers on main. Two branches writing two different files merge cleanly every time. `npm run changelog:add -- fixed "…"` writes the entry, `npm run changelog:collect` folds them all back into the release notes before a release, and `npm run changelog:preview` reads the assembled unreleased notes without changing anything.diff --git a/.gitattributes b/.gitattributesindex dfdb8b771c..215762120b 100644--- a/.gitattributes+++ b/.gitattributes@@ -1 +1,17 @@*.sh text eol=lf++# Changelog fragments are one file per branch (see scripts/changelogFragments.js),+# so two branches normally touch two different paths and never conflict. `union`+# covers the residual case: two branches whose names share a last segment derive+# the same slug and write the same fragment, where keeping both bullets is the+# right answer. A fragment is short-lived — created on a branch, deleted at+# collection — so it has no cross-release failure mode.+#+# Deliberately NOT applied to .changelog/NEXT.md. It looks like the same+# append-only shape, but `/do:release` renames NEXT.md to v{version}.md and+# starts a fresh one, and git does not pair that rename (the path still exists+# on main). A branch that outlives a release is then a plain modify/modify, and+# union resolves it by keeping BOTH sides — silently reviving the entire+# previous release's entries into the next release's notes, with no conflict and+# no warning. A loud conflict there is the correct outcome.+.changelog/next/*.md merge=uniondiff --git a/CLAUDE.md b/CLAUDE.mdindex ba1eda810f..5b6a697cfd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -191,7 +191,7 @@ This complements the Security Model (which governs the deployed product) — thi- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.- **Push pattern**: `git pull --rebase --autostash && git push`-- **Changelog**: append entries to `.changelog/NEXT.md` during development; `/do:release` finalizes them into a versioned file. Format details in `.changelog/README.md`.+- **Changelog — write a fragment, never append to `NEXT.md`.** `npm run changelog:add -- <added|changed|fixed|removed> "entry text"` writes `.changelog/next/<section>-<your-branch>.md`. Every parallel agent used to append a bullet to the end of the same section of `NEXT.md`, so two branches cut from the same base added different lines in the same place — a guaranteed merge conflict, and conflict markers have reached `main` because of it. Ordering conventions don't help; git conflicts on adjacent hunks regardless. One file per branch does, because git merges by path. `npm run changelog:collect` folds the fragments into `NEXT.md` and is the **first step of `/do:release`**; `npm run changelog:preview` reads the assembled unreleased notes without changing anything. Editing an already-collected entry in `NEXT.md` is still fine — the rule is about *new* entries on a branch. Note `NEXT.md` is deliberately **not** union-merged: union would resolve a branch that outlives a release by keeping both sides, silently republishing the whole previous release. Full rationale: `.changelog/README.md`.- **Versioning**: the version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.- After each feature or bug fix, run `/simplify`, then commit and push.- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into `PLAN.md` as `- [ ]` items (or a filed issue), specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the full labeling contract.diff --git a/README.md b/README.mdindex b3656bbef9..fe62ec9a5a 100644--- a/README.md+++ b/README.md@@ -360,7 +360,7 @@ PortOS/├── docs/ # Documentation, ADRs, design plans, and screenshots├── lib/slashdo/ # Slashdo submodule (provides /do:* slash commands)├── scripts/ # Setup, migration, and maintenance scripts-├── .changelog/ # Per-release changelogs (NEXT.md accumulates in-flight work)+├── .changelog/ # Per-release changelogs (next/ holds in-flight entries, one file per branch)└── ecosystem.config.cjs # PM2 configuration + canonical PORTS map```diff --git a/package.json b/package.jsonindex e827d26152..b8af69dc84 100644--- a/package.json+++ b/package.json@@ -13,6 +13,9 @@"dev": "node scripts/checkNodeVersion.js && node scripts/dev-start.js","dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","build": "npm run build --prefix client",+ "changelog:add": "node scripts/changelog-add.js",+ "changelog:collect": "node scripts/changelog-collect.js",+ "changelog:preview": "node scripts/changelog-collect.js --preview","start": "node scripts/checkNodeVersion.js && node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && node scripts/setup-cert.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save","pm2:start": "node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs","pm2:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs",diff --git a/scripts/changelog-add.js b/scripts/changelog-add.jsnew file mode 100644index 0000000000..c010f67f60--- /dev/null+++ b/scripts/changelog-add.js@@ -0,0 +1,79 @@+/**+ * Write a changelog entry as a per-branch fragment — the conflict-free+ * replacement for appending to `.changelog/NEXT.md` by hand.+ *+ * npm run changelog:add -- fixed "Notifications panel no longer clips on a phone."+ * npm run changelog:add -- added --slug issue-3916 "Backups can be scheduled per app."+ * git log -1 --format=%s | npm run changelog:add -- changed+ *+ * The slug defaults to the current branch's last segment, so two agents running+ * in parallel worktrees write two different files and their PRs merge cleanly.+ * See scripts/changelogFragments.js for why that is the fix and orderings are not.+ */++import { execFileSync } from 'child_process';+import { readFileSync } from 'fs';+import { relative } from 'path';++import { REPO_ROOT, SECTIONS, slugFromBranch, slugify, writeFragment } from './changelogFragments.js';++const USAGE = `Usage: npm run changelog:add -- <${SECTIONS.join('|')}> [--slug <slug>] "entry text"++Reads the entry from stdin when no text argument is given.`;++/**+ * The branch this fragment belongs to.+ *+ * A detached HEAD (CI checkouts, a rebase in progress) has no branch name, in+ * which case the caller must pass --slug rather than get every detached run+ * writing to the same `HEAD.md`.+ */+function currentBranch() {+ const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {+ cwd: REPO_ROOT,+ encoding: 'utf8',+ }).trim();+ return branch === 'HEAD' ? '' : branch;+}++function parseArgs(argv) {+ const positional = [];+ let slug = '';+ for (let i = 0; i < argv.length; i += 1) {+ if (argv[i] === '--slug') {+ slug = argv[i + 1] || '';+ i += 1;+ } else {+ positional.push(argv[i]);+ }+ }+ return { section: (positional[0] || '').toLowerCase(), text: positional.slice(1).join(' '), slug };+}++async function main() {+ const { section, text, slug: slugArg } = parseArgs(process.argv.slice(2));++ if (!SECTIONS.includes(section)) {+ console.error(`❌ Unknown changelog section "${section || '(none)'}"\n\n${USAGE}`);+ process.exit(1);+ }++ // `readFileSync(0)` blocks on an interactive terminal, so only reach for+ // stdin when it is actually a pipe and no text argument was supplied.+ const entry = text || (process.stdin.isTTY ? '' : readFileSync(0, 'utf8'));+ if (!entry.trim()) {+ console.error(`❌ No entry text given\n\n${USAGE}`);+ process.exit(1);+ }++ const slug = slugify(slugArg) || slugFromBranch(currentBranch());+ if (!slug) {+ console.error('❌ Could not derive a slug from the current branch (detached HEAD?) — pass --slug <slug>');+ process.exit(1);+ }++ const { path, appended } = await writeFragment({ section, slug, text: entry });+ console.log(`📝 ${appended ? 'Appended to' : 'Wrote'} ${relative(REPO_ROOT, path)}`);+}++await main();diff --git a/scripts/changelog-collect.js b/scripts/changelog-collect.jsnew file mode 100644index 0000000000..281736a869--- /dev/null+++ b/scripts/changelog-collect.js@@ -0,0 +1,41 @@+/**+ * Fold every `.changelog/next/*.md` fragment into `.changelog/NEXT.md`.+ *+ * npm run changelog:collect # rewrite NEXT.md and delete the fragments+ * npm run changelog:preview # print what collection would produce, change nothing+ *+ * Run this before `/do:release`, which renames `NEXT.md` → `v{version}.md`.+ * Skipping it is not destructive — uncollected fragments simply ride along to+ * the next release — but the notes for this one would be missing entries.+ */++import { relative } from 'path';++import { collectFragments, NEXT_PATH, REPO_ROOT } from './changelogFragments.js';++async function main() {+ const preview = process.argv.includes('--preview');+ const { collected, invalid, markdown } = await collectFragments({ keep: preview });++ for (const filename of invalid) {+ console.error(`⚠️ Ignoring malformed changelog fragment: .changelog/next/${filename}`);+ }++ if (collected === 0) {+ console.log('✅ No changelog fragments to collect');+ // A malformed fragment is a real entry that will silently miss the release,+ // so it fails the run rather than reading as "nothing to do".+ process.exit(invalid.length > 0 ? 1 : 0);+ }++ if (preview) {+ console.log(markdown);+ console.log(`👀 Preview only — ${collected} fragment(s) left in place`);+ return;+ }++ console.log(`📜 Collected ${collected} changelog fragment(s) into ${relative(REPO_ROOT, NEXT_PATH)}`);+ if (invalid.length > 0) process.exit(1);+}++await main();diff --git a/scripts/changelogFragments.js b/scripts/changelogFragments.jsnew file mode 100644index 0000000000..cc36220876--- /dev/null+++ b/scripts/changelogFragments.js@@ -0,0 +1,262 @@+/**+ * Conflict-free changelog accumulation for parallel agents.+ *+ * The problem this solves: every CoS agent, `/claim` worktree and swarm worker+ * finishes its work by appending a bullet to the END of a section in+ * `.changelog/NEXT.md`. Two branches cut from the same base therefore add+ * different lines at the same place in the same file, which is the textbook+ * shape of a git merge conflict — so every second PR of a parallel run stalls+ * on a hand-resolved changelog, and at least once a conflict marker has been+ * committed to main and had to be swept up afterwards.+ *+ * Ordering tricks (alphabetize by agent id, blank line between entries) do not+ * fix this: git's 3-way merge conflicts on *adjacent* changed hunks regardless+ * of what the lines say. The only structural fix is to stop two branches from+ * writing the same file at all.+ *+ * So changelog entries are written as **fragments** — one small file per+ * branch per section, under `.changelog/next/`:+ *+ * .changelog/next/fixed-issue-3916.md+ * .changelog/next/added-agent-d3651f27.md+ *+ * Two branches adding two different paths merge cleanly every time, because+ * git merges by path. The slug defaults to the branch name's last segment,+ * which is already unique per agent/claim, so collisions need no coordination.+ *+ * `changelog-collect.js` folds the fragments back into `NEXT.md` before a+ * release, which keeps `/do:release` (a slashdo submodule command that renames+ * `NEXT.md` → `v{version}.md`) working exactly as it does today.+ *+ * Nothing here deletes or rewrites existing entries — collection is append-only+ * into the matching `## Section`, so a fragment that is never collected is+ * carried into the next release rather than lost.+ */++import { existsSync, readdirSync, readFileSync, rmSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++import { atomicWrite } from '../server/lib/fileUtils.js';++export const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++/** Directory holding one-entry fragment files awaiting collection. */+const FRAGMENT_DIR = join(REPO_ROOT, '.changelog', 'next');++/** The accumulator `/do:release` renames into `v{version}.md`. */+export const NEXT_PATH = join(REPO_ROOT, '.changelog', 'NEXT.md');++/**+ * The Keep-a-Changelog sections, in the order `.changelog/README.md` documents.+ * A fragment's section is encoded in its filename prefix, so this list is also+ * the filename grammar.+ */+export const SECTIONS = ['added', 'changed', 'fixed', 'removed'];++/** `added` → `## Added` */+const sectionHeading = (section) => `## ${section[0].toUpperCase()}${section.slice(1)}`;++/**+ * Split a fragment filename into its section and slug.+ *+ * Returns `null` for anything that is not a well-formed fragment, so callers+ * can report the bad name rather than silently skipping (and dropping) it.+ * `.gitkeep` and other dotfiles are the caller's job to filter out first.+ */+export function parseFragmentName(filename) {+ const match = /^([a-z]+)-([a-z0-9][a-z0-9-]*)\.md$/.exec(filename);+ if (!match) return null;+ const [, section, slug] = match;+ if (!SECTIONS.includes(section)) return null;+ return { section, slug };+}++/**+ * Turn arbitrary text into a filename-safe slug.+ *+ * Returns `''` when nothing usable survives, which callers treat as "fall back+ * to the default" rather than writing a file named `-.md`.+ */+export function slugify(text) {+ return String(text || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/**+ * The default slug for a fragment: the last segment of the current branch.+ *+ * Branch names are already unique per unit of work — `claim/issue-3916`,+ * `next/issue-2148`, `cos/task-msrknq4w/agent-d3651f27` — and their last+ * segment (`issue-3916`, `agent-d3651f27`) is both unique and readable. That+ * is what makes the whole scheme coordination-free: an agent never has to know+ * what any other agent named its fragment.+ */+export function slugFromBranch(branch) {+ const lastSegment = String(branch || '').split('/').filter(Boolean).pop() || '';+ return slugify(lastSegment);+}++/**+ * Normalize entry text into changelog bullets.+ *+ * Hand-written fragments arrive either as bullets already or as bare prose; a+ * bare paragraph becomes one bullet so `changelog-add.js "some text"` is the+ * shortest possible call. Blank lines between bullets are dropped — the+ * collector controls spacing in the assembled file.+ */+export function toBullets(text) {+ const trimmed = String(text || '').trim();+ if (!trimmed) return [];+ if (!/^[-*]\s/m.test(trimmed)) return [`- ${trimmed.replace(/\s*\n\s*/g, ' ')}`];+ return trimmed+ .split('\n')+ .map((line) => line.trimEnd())+ .filter((line) => line.length > 0)+ .map((line) => line.replace(/^\*\s/, '- '));+}++/**+ * Every fragment on disk, sorted by filename.+ *+ * Sorting is what makes collection deterministic: two installs collecting the+ * same fragment set produce byte-identical NEXT.md, so a collect run is never+ * itself a source of merge noise.+ */+export function readFragments(dir = FRAGMENT_DIR) {+ if (!existsSync(dir)) return { fragments: [], invalid: [] };+ const fragments = [];+ const invalid = [];+ for (const filename of readdirSync(dir).sort()) {+ if (filename.startsWith('.')) continue;+ const parsed = parseFragmentName(filename);+ if (!parsed) {+ invalid.push(filename);+ continue;+ }+ const bullets = toBullets(readFileSync(join(dir, filename), 'utf8'));+ if (bullets.length === 0) {+ invalid.push(filename);+ continue;+ }+ fragments.push({ ...parsed, path: join(dir, filename), bullets });+ }+ return { fragments, invalid };+}++/**+ * Split a changelog document into a preamble plus one block per `## Heading`.+ *+ * Unknown headings are preserved verbatim and in place — a released file may+ * carry `## Overview` or `## Full Changelog`, and collection must not reorder+ * or drop them.+ */+function splitSections(markdown) {+ const lines = markdown.split('\n');+ const preamble = [];+ const blocks = [];+ let current = null;+ for (const line of lines) {+ const heading = /^##\s+(.+?)\s*$/.exec(line);+ if (heading) {+ current = { heading: line, title: heading[1].toLowerCase(), body: [] };+ blocks.push(current);+ continue;+ }+ (current ? current.body : preamble).push(line);+ }+ return { preamble, blocks };+}++/** Drop leading/trailing blank lines from a section body. */+const trimBlanks = (lines) => {+ const start = lines.findIndex((line) => line.trim());+ return start === -1 ? [] : lines.slice(start, lines.findLastIndex((line) => line.trim()) + 1);+};++/**+ * Append `bullets` to `markdown` under `## Section`, creating the section when+ * it is absent.+ *+ * A new section is inserted so the known sections stay in `SECTIONS` order+ * relative to each other, without disturbing unknown ones.+ */+export function appendToSection(markdown, section, bullets) {+ if (bullets.length === 0) return markdown;+ const { preamble, blocks } = splitSections(markdown);+ const title = section.toLowerCase();+ const existing = blocks.find((block) => block.title === title);++ if (existing) {+ existing.body = [...trimBlanks(existing.body), ...bullets];+ } else {+ const rank = SECTIONS.indexOf(title);+ const block = { heading: sectionHeading(title), title, body: [...bullets] };+ const followerIndex = blocks.findIndex((candidate) => {+ const candidateRank = SECTIONS.indexOf(candidate.title);+ return candidateRank !== -1 && candidateRank > rank;+ });+ if (followerIndex === -1) blocks.push(block);+ else blocks.splice(followerIndex, 0, block);+ }++ const rendered = blocks.map((block) => [block.heading, '', ...trimBlanks(block.body)].join('\n'));+ const head = trimBlanks(preamble);+ return [...(head.length ? [head.join('\n')] : []), ...rendered].join('\n\n') + '\n';+}++/**+ * Fold every fragment into the target changelog and (unless `keep`) delete them.+ *+ * Returns what happened so the CLI can report it and tests can assert on it+ * without re-reading the filesystem. `invalid` is surfaced rather than thrown+ * on so one malformed name cannot strand every other agent's entry.+ */+export async function collectFragments({ dir = FRAGMENT_DIR, target = NEXT_PATH, keep = false } = {}) {+ const { fragments, invalid } = readFragments(dir);+ if (fragments.length === 0) return { collected: 0, invalid, markdown: null };++ let markdown = existsSync(target) ? readFileSync(target, 'utf8') : '';+ for (const section of SECTIONS) {+ const bullets = fragments+ .filter((fragment) => fragment.section === section)+ .flatMap((fragment) => fragment.bullets);+ markdown = appendToSection(markdown, section, bullets);+ }++ if (!keep) {+ // atomicWrite (temp + rename), not a plain write: the very next statement+ // deletes the fragments, which are the only other copy of these entries. A+ // write torn by a kill or a full disk would otherwise leave a truncated+ // changelog behind.+ await atomicWrite(target, markdown);+ for (const fragment of fragments) rmSync(fragment.path);+ }++ return { collected: fragments.length, invalid, markdown };+}++/**+ * Write (or extend) the fragment for a section + slug.+ *+ * Appending to an existing file rather than minting a suffixed one is+ * deliberate: a branch that ships several fixes keeps them in one file, and the+ * file is only ever touched by that one branch, so appending stays conflict-free.+ */+export async function writeFragment({ section, slug, text, dir = FRAGMENT_DIR }) {+ if (!SECTIONS.includes(section)) {+ throw new Error(`Unknown changelog section "${section}" — expected one of ${SECTIONS.join(', ')}`);+ }+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) {+ throw new Error(`Unusable changelog slug "${slug}" — expected lowercase letters, digits and dashes`);+ }+ const bullets = toBullets(text);+ if (bullets.length === 0) throw new Error('Refusing to write an empty changelog entry');++ const path = join(dir, `${section}-${slug}.md`);+ const existing = existsSync(path) ? toBullets(readFileSync(path, 'utf8')) : [];+ await atomicWrite(path, `${[...existing, ...bullets].join('\n')}\n`);+ return { path, appended: existing.length > 0 };+}diff --git a/scripts/changelogFragments.test.js b/scripts/changelogFragments.test.jsnew file mode 100644index 0000000000..e126e1ce95--- /dev/null+++ b/scripts/changelogFragments.test.js@@ -0,0 +1,276 @@+/**+ * Covers the conflict-free changelog fragment scheme, plus two drift guards+ * over the repo itself:+ *+ * - every fragment currently sitting in `.changelog/next/` is well-formed, so+ * a typo'd filename fails in CI rather than at release time when the entry+ * would silently miss the notes (this file is in ALWAYS_RUN_TESTS so a+ * changelog-only PR actually runs it);+ * - `.gitattributes` unions the fragments and, deliberately, NOT `NEXT.md` —+ * union there silently revives a whole previous release across the+ * `/do:release` rename. The guard pins both halves of that decision.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import {+ appendToSection,+ collectFragments,+ parseFragmentName,+ readFragments,+ REPO_ROOT,+ SECTIONS,+ slugFromBranch,+ slugify,+ toBullets,+ writeFragment,+} from './changelogFragments.js';++let dir;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'portos-changelog-'));+});++afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+});++const write = (name, body) => writeFileSync(join(dir, name), body);++describe('parseFragmentName', () => {+ it('accepts a known section prefix with a dashed slug', () => {+ expect(parseFragmentName('fixed-issue-3916.md')).toEqual({ section: 'fixed', slug: 'issue-3916' });+ expect(parseFragmentName('added-agent-d3651f27.md')).toEqual({ section: 'added', slug: 'agent-d3651f27' });+ });++ it('rejects an unknown section, a missing slug, and a non-markdown file', () => {+ expect(parseFragmentName('deprecated-thing.md')).toBeNull();+ expect(parseFragmentName('fixed-.md')).toBeNull();+ expect(parseFragmentName('fixed-thing.txt')).toBeNull();+ expect(parseFragmentName('Fixed-Thing.md')).toBeNull();+ });+});++describe('slug derivation', () => {+ it('takes the last branch segment, which is unique per agent or claim', () => {+ expect(slugFromBranch('claim/issue-3916')).toBe('issue-3916');+ expect(slugFromBranch('cos/task-msrknq4w/agent-d3651f27')).toBe('agent-d3651f27');+ expect(slugFromBranch('main')).toBe('main');+ });++ it('returns empty for a branch that yields nothing usable, so callers can fall back', () => {+ expect(slugFromBranch('')).toBe('');+ expect(slugFromBranch('///')).toBe('');+ expect(slugify('!!!')).toBe('');+ });++ it('normalizes mixed case and punctuation', () => {+ expect(slugify('Fix The_Thing (again)')).toBe('fix-the-thing-again');+ });+});++describe('toBullets', () => {+ it('wraps bare prose as a single bullet and flattens its newlines', () => {+ expect(toBullets('The thing\nno longer breaks.')).toEqual(['- The thing no longer breaks.']);+ });++ it('preserves an existing bullet list and normalizes the marker', () => {+ expect(toBullets('- one\n\n* two\n')).toEqual(['- one', '- two']);+ });++ it('returns nothing for empty or whitespace-only text', () => {+ expect(toBullets(' \n ')).toEqual([]);+ });+});++describe('appendToSection', () => {+ it('appends under an existing heading without disturbing the others', () => {+ const before = '## Added\n\n- first\n\n## Fixed\n\n- a fix\n';+ expect(appendToSection(before, 'added', ['- second'])).toBe(+ '## Added\n\n- first\n- second\n\n## Fixed\n\n- a fix\n'+ );+ });++ it('creates a missing section in canonical order rather than at the end', () => {+ const after = appendToSection('## Added\n\n- a\n\n## Fixed\n\n- f\n', 'changed', ['- c']);+ expect(after).toBe('## Added\n\n- a\n\n## Changed\n\n- c\n\n## Fixed\n\n- f\n');+ });++ it('appends a section that sorts last when nothing follows it', () => {+ expect(appendToSection('## Added\n\n- a\n', 'removed', ['- r'])).toBe('## Added\n\n- a\n\n## Removed\n\n- r\n');+ });++ it('builds the file from scratch when the changelog is empty', () => {+ expect(appendToSection('', 'fixed', ['- f'])).toBe('## Fixed\n\n- f\n');+ });++ it('keeps an unknown heading and any preamble in place', () => {+ const before = '# Release v9.9.9\n\n## Overview\n\nA release.\n\n## Fixed\n\n- f\n';+ expect(appendToSection(before, 'fixed', ['- g'])).toBe(+ '# Release v9.9.9\n\n## Overview\n\nA release.\n\n## Fixed\n\n- f\n- g\n'+ );+ });++ it('is a no-op when there are no bullets to add', () => {+ expect(appendToSection('## Added\n\n- a\n', 'fixed', [])).toBe('## Added\n\n- a\n');+ });+});++describe('readFragments', () => {+ it('sorts by filename so collection is deterministic across installs', () => {+ write('fixed-zeta.md', '- z');+ write('fixed-alpha.md', '- a');+ expect(readFragments(dir).fragments.map((f) => f.slug)).toEqual(['alpha', 'zeta']);+ });++ it('reports malformed and empty fragments instead of silently dropping them', () => {+ write('fixed-ok.md', '- ok');+ write('notes.md', '- stray');+ write('fixed-blank.md', ' \n');+ const { fragments, invalid } = readFragments(dir);+ expect(fragments.map((f) => f.slug)).toEqual(['ok']);+ expect(invalid.sort()).toEqual(['fixed-blank.md', 'notes.md']);+ });++ it('ignores dotfiles such as .gitkeep', () => {+ write('.gitkeep', '');+ expect(readFragments(dir).invalid).toEqual([]);+ });++ it('returns empty for a directory that does not exist yet', () => {+ expect(readFragments(join(dir, 'absent'))).toEqual({ fragments: [], invalid: [] });+ });+});++describe('collectFragments', () => {+ it('folds every section into the target and deletes the fragments', async () => {+ const target = join(dir, 'NEXT.md');+ writeFileSync(target, '## Fixed\n\n- existing\n');+ write('fixed-b.md', '- second fix');+ write('added-a.md', '- a feature');+ write('removed-c.md', '- a removal');++ const result = await collectFragments({ dir, target });++ expect(result.collected).toBe(3);+ expect(readFileSync(target, 'utf8')).toBe(+ '## Added\n\n- a feature\n\n## Fixed\n\n- existing\n- second fix\n\n## Removed\n\n- a removal\n'+ );+ // The fragments are gone, so a second collect cannot duplicate them.+ expect(readdirSync(dir)).toEqual(['NEXT.md']);+ });++ it('creates the target when a release has already consumed NEXT.md', async () => {+ const target = join(dir, 'NEXT.md');+ write('added-a.md', '- a feature');+ await collectFragments({ dir, target });+ expect(readFileSync(target, 'utf8')).toBe('## Added\n\n- a feature\n');+ });++ it('leaves everything alone under keep, so a preview cannot lose an entry', async () => {+ const target = join(dir, 'NEXT.md');+ writeFileSync(target, '## Fixed\n\n- existing\n');+ write('fixed-a.md', '- new');++ const result = await collectFragments({ dir, target, keep: true });++ expect(result.markdown).toContain('- new');+ expect(readFileSync(target, 'utf8')).toBe('## Fixed\n\n- existing\n');+ expect(existsSync(join(dir, 'fixed-a.md'))).toBe(true);+ });++ it('collects the valid fragments even when one is malformed', async () => {+ const target = join(dir, 'NEXT.md');+ write('fixed-good.md', '- good');+ write('bogus.md', '- bogus');++ const result = await collectFragments({ dir, target });++ expect(result.collected).toBe(1);+ expect(result.invalid).toEqual(['bogus.md']);+ expect(readFileSync(target, 'utf8')).toBe('## Fixed\n\n- good\n');+ expect(existsSync(join(dir, 'bogus.md'))).toBe(true);+ });++ it('preserves the guidance comment NEXT.md carries above its first heading', async () => {+ const target = join(dir, 'NEXT.md');+ writeFileSync(target, '<!-- write a fragment, do not append here -->\n\n## Fixed\n\n- existing\n');+ write('fixed-a.md', '- new');+ await collectFragments({ dir, target });+ expect(readFileSync(target, 'utf8')).toBe(+ '<!-- write a fragment, do not append here -->\n\n## Fixed\n\n- existing\n- new\n'+ );+ });++ it('is a no-op with nothing to collect', async () => {+ const target = join(dir, 'NEXT.md');+ writeFileSync(target, '## Fixed\n\n- existing\n');+ expect((await collectFragments({ dir, target })).collected).toBe(0);+ expect(readFileSync(target, 'utf8')).toBe('## Fixed\n\n- existing\n');+ });+});++describe('writeFragment', () => {+ it('writes a bullet for a bare sentence', async () => {+ const { path, appended } = await writeFragment({ section: 'fixed', slug: 'issue-1', text: 'It works.', dir });+ expect(appended).toBe(false);+ expect(readFileSync(path, 'utf8')).toBe('- It works.\n');+ });++ it('appends to the same branch fragment instead of minting a second file', async () => {+ await writeFragment({ section: 'fixed', slug: 'issue-1', text: 'First.', dir });+ const { path, appended } = await writeFragment({ section: 'fixed', slug: 'issue-1', text: 'Second.', dir });+ expect(appended).toBe(true);+ expect(readFileSync(path, 'utf8')).toBe('- First.\n- Second.\n');+ expect(readdirSync(dir)).toEqual(['fixed-issue-1.md']);+ });++ it('refuses an unknown section, an unusable slug, and empty text', async () => {+ await expect(writeFragment({ section: 'deprecated', slug: 'a', text: 'x', dir })).rejects.toThrow(+ /Unknown changelog section/+ );+ await expect(writeFragment({ section: 'fixed', slug: '-bad-', text: 'x', dir })).rejects.toThrow(+ /Unusable changelog slug/+ );+ await expect(writeFragment({ section: 'fixed', slug: 'a', text: ' ', dir })).rejects.toThrow(+ /empty changelog entry/+ );+ });++ it('round-trips through readFragments for every section', async () => {+ for (const section of SECTIONS) await writeFragment({ section, slug: 'x', text: `${section} entry`, dir });+ const { fragments, invalid } = readFragments(dir);+ expect(invalid).toEqual([]);+ expect(fragments.map((f) => f.section).sort()).toEqual([...SECTIONS].sort());+ });+});++describe('repo guards', () => {+ it('every fragment checked into .changelog/next is well-formed', () => {+ expect(readFragments().invalid).toEqual([]);+ });++ it('.gitattributes unions the fragments but never the NEXT.md accumulator', () => {+ const gitattributes = readFileSync(join(REPO_ROOT, '.gitattributes'), 'utf8');+ expect(gitattributes).toMatch(/^\.changelog\/next\/\*\.md\s+merge=union$/m);+ // Union on NEXT.md resolves the modify/modify a branch outliving a+ // /do:release produces by keeping BOTH sides, which silently republishes+ // the previous release's whole changelog. A conflict there is correct.+ expect(gitattributes).not.toMatch(/^\.changelog\/NEXT\.md\s+merge=union$/m);+ });++ it('the fragment guard runs on every CI plan, including a changelog-only PR', async () => {+ const { ALWAYS_RUN_TESTS } = await import('./ci-test-plan.js');+ expect(ALWAYS_RUN_TESTS).toContain('scripts/changelogFragments.test.js');+ });++ it('the collect and add entry points are wired as npm scripts', () => {+ const { scripts } = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8'));+ expect(scripts['changelog:add']).toContain('changelog-add.js');+ expect(scripts['changelog:collect']).toContain('changelog-collect.js');+ expect(scripts['changelog:preview']).toContain('--preview');+ });+});diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 662ead3ecb..3c62051eb9 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -38,8 +38,17 @@ const FULL_TRIGGER_RULES = [// so it is never scoped out. The file runs in ~150ms and imports only prompt// data, which is cheap enough to pay on every PR including documentation-only// ones, where the alternative is reasoning per-scope about what can reach it.-const ALWAYS_RUN_TESTS = [+//+// `changelogFragments.test.js` is here for the same reason. It guards that every+// fragment in `.changelog/next/` parses — a typo'd filename means that entry+// silently misses the release notes. But a PR that only adds a fragment is a+// documentation-only change under DOCUMENTATION_RULES, so the impact scope+// selects nothing that reaches it, and the guard would first fire on the+// post-merge full run: after the bad name has already landed. It runs 33 tests+// in ~90ms over pure filesystem helpers.+export const ALWAYS_RUN_TESTS = ['server/services/taskPromptDefaults.test.js',+ 'scripts/changelogFragments.test.js',];const DB_RISK_RULES = [diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex f19ed04f8f..ab0279ee57 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -971,7 +971,7 @@ export function desiredEndState(state, actions, { prNumber, worktreePath, collis// leaving it for a human, since it converts recoverable scratch state into// branch history.const where = worktreePath ? `\`${worktreePath}\`` : 'the branch\'s worktree';- const assess = `This branch has no commits of its own — its work is sitting UNCOMMITTED in ${where}, the worktree of a CoS agent that is no longer running (it exited, crashed, or was reaped before committing). Nothing is lost, but nothing lands either until someone finishes it. Working INSIDE that worktree, run \`git status\` and \`git diff\` (plus \`git diff\` against untracked files) and read the WHOLE change set before touching anything. Then judge whether it is coherent, finished work: the test suites for the touched workspaces pass, no stub/TODO/placeholder left mid-edit, no half-renamed symbol, and a \`.changelog/NEXT.md\` entry present.`;+ const assess = `This branch has no commits of its own — its work is sitting UNCOMMITTED in ${where}, the worktree of a CoS agent that is no longer running (it exited, crashed, or was reaped before committing). Nothing is lost, but nothing lands either until someone finishes it. Working INSIDE that worktree, run \`git status\` and \`git diff\` (plus \`git diff\` against untracked files) and read the WHOLE change set before touching anything. Then judge whether it is coherent, finished work: the test suites for the touched workspaces pass, no stub/TODO/placeholder left mid-edit, no half-renamed symbol, and a changelog entry present (a \`.changelog/next/*.md\` fragment, or an entry in \`.changelog/NEXT.md\`).`;const bail = 'If it is NOT finished, do not commit it and do not delete it — leave every file exactly as it is and report what the work appears to be, how far it got, and what is missing, so a human can decide whether to finish or discard it.';const commit = 'If it IS finished, commit it on this branch (a message that states what changed and why — never a bare "wip"), then ship it with `/do:pr --no-merge` (by hand, if slash commands are unavailable: self-review the diff, `git push -u origin <branch>`, then `gh pr create` with a Summary + Test plan).';if (!actionOn(actions, 'autoMerge')) {