Skip to content

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

Close the too-small good-first issues as one change

[._.]/ Adam Eivye105de7f9526
diff --git a/.changelog/next/changed-tiny-gfi-docs-and-cleanup.md b/.changelog/next/changed-tiny-gfi-docs-and-cleanup.md
new file mode 100644
index 0000000000..4e9842978b
--- /dev/null
+++ b/.changelog/next/changed-tiny-gfi-docs-and-cleanup.md
@@ -0,0 +1 @@
+- Documented changelog:add, fixed stale docs pointers, and collapsed a handful of duplicated helpers.
diff --git a/client/src/components/city/CityVitalsList.jsx b/client/src/components/city/CityVitalsList.jsx
index c3514e7fac..ec53daca4e 100644
--- a/client/src/components/city/CityVitalsList.jsx
+++ b/client/src/components/city/CityVitalsList.jsx
@@ -1,5 +1,5 @@
import { useNavigate } from 'react-router';
-import { formatDurationMs } from '../../utils/formatters';
+import { formatDurationMs, formatMonthDay } from '../../utils/formatters';
import { StatButton, metricColor } from './cityHudBits';
// The System Vitals rows (uptime, health CPU/MEM/DISK, agents, stopped, archived,
@@ -121,7 +121,7 @@ export default function CityVitalsList({
<div className="flex items-center justify-between">
<span className="font-pixel text-[9px] text-cyan-500/40 tracking-widest">SYS.OK</span>
<span className="font-pixel text-[9px] text-cyan-500/40 tracking-widest">
- {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' }).toUpperCase()}
+ {formatMonthDay(new Date()).toUpperCase()}
</span>
</div>
</div>
diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsx
index 647ace602f..836771fccc 100644
--- a/client/src/components/meatspace/post/PostHistory.jsx
+++ b/client/src/components/meatspace/post/PostHistory.jsx
@@ -9,6 +9,7 @@ import useChartColors from '../../../hooks/useChartColors.js';
import useUserTimezone from '../../../hooks/useUserTimezone.js';
import { todayKeyInTimezone, shiftDayKey } from '../../../utils/timezone.js';
import { DRILL_TO_DOMAIN, DRILL_LABELS, domainLabel } from './constants';
+import { clickableProps } from '../../../lib/a11yKeyboard.js';
const RANGES = [
{ label: '7d', days: 7 },
@@ -263,15 +264,9 @@ export default function PostHistory({ onBack }) {
return (
<tr
key={s.id}
- role="button"
- tabIndex={0}
+ {...clickableProps(open)}
aria-label={`Session ${s.date}, score ${s.score}. Open details.`}
onClick={open}
- onKeyDown={(e) => {
- if (e.key !== 'Enter' && e.key !== ' ') return;
- e.preventDefault();
- open();
- }}
className="border-b border-port-border/50 hover:bg-port-bg/50 cursor-pointer focus:outline-none focus:ring-2 focus:ring-port-accent focus:ring-inset"
>
<td className="px-4 py-2 text-gray-500">
diff --git a/client/src/components/media/PromptEnhancer.jsx b/client/src/components/media/PromptEnhancer.jsx
index b4027852cb..078c1ce3de 100644
--- a/client/src/components/media/PromptEnhancer.jsx
+++ b/client/src/components/media/PromptEnhancer.jsx
@@ -5,6 +5,7 @@ import useProviderModels from '../../hooks/useProviderModels';
import { refineMediaPrompt } from '../../services/api';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
+import { safeReadStorage, safeRemoveStorage, safeWriteStorage } from '../../lib/safeStorage';
const LS_KEY_PROVIDER = 'portos_enhance_prompt_provider';
const LS_KEY_MODEL = 'portos_enhance_prompt_model';
@@ -20,13 +21,7 @@ export default function PromptEnhancer({
disabled = false,
}) {
const [isOpen, setIsOpen] = useState(false);
- const [effort, setEffort] = useState(() => {
- try {
- return localStorage.getItem(LS_KEY_EFFORT) || '';
- } catch {
- return '';
- }
- });
+ const [effort, setEffort] = useState(() => safeReadStorage(LS_KEY_EFFORT) || '');
const [enhancing, setEnhancing] = useState(false);
const {
@@ -42,61 +37,36 @@ export default function PromptEnhancer({
// Restore saved provider / model preference once provider list loads
useEffect(() => {
if (providersLoading || !providers.length) return;
- try {
- const savedProvider = localStorage.getItem(LS_KEY_PROVIDER);
- const savedModel = localStorage.getItem(LS_KEY_MODEL);
- if (savedProvider && providers.some((p) => p.id === savedProvider)) {
- setSelectedProviderId(savedProvider);
- if (savedModel) {
- setSelectedModel(savedModel);
- }
+ const savedProvider = safeReadStorage(LS_KEY_PROVIDER);
+ const savedModel = safeReadStorage(LS_KEY_MODEL);
+ if (savedProvider && providers.some((p) => p.id === savedProvider)) {
+ setSelectedProviderId(savedProvider);
+ if (savedModel) {
+ setSelectedModel(savedModel);
}
- } catch {
- // Ignore localStorage errors
}
}, [providers, providersLoading, setSelectedProviderId, setSelectedModel]);
const handleProviderChange = (id) => {
setSelectedProviderId(id);
setEffort('');
- try {
- if (id) {
- localStorage.setItem(LS_KEY_PROVIDER, id);
- } else {
- localStorage.removeItem(LS_KEY_PROVIDER);
- }
- localStorage.removeItem(LS_KEY_MODEL);
- localStorage.removeItem(LS_KEY_EFFORT);
- } catch {
- // Ignore localStorage errors
- }
+ if (id) safeWriteStorage(LS_KEY_PROVIDER, id);
+ else safeRemoveStorage(LS_KEY_PROVIDER);
+ safeRemoveStorage(LS_KEY_MODEL);
+ safeRemoveStorage(LS_KEY_EFFORT);
};
const handleModelChange = (model) => {
setSelectedModel(model);
- try {
- if (selectedProviderId) localStorage.setItem(LS_KEY_PROVIDER, selectedProviderId);
- if (model) {
- localStorage.setItem(LS_KEY_MODEL, model);
- } else {
- localStorage.removeItem(LS_KEY_MODEL);
- }
- } catch {
- // Ignore localStorage errors
- }
+ if (selectedProviderId) safeWriteStorage(LS_KEY_PROVIDER, selectedProviderId);
+ if (model) safeWriteStorage(LS_KEY_MODEL, model);
+ else safeRemoveStorage(LS_KEY_MODEL);
};
const handleEffortChange = (val) => {
setEffort(val);
- try {
- if (val) {
- localStorage.setItem(LS_KEY_EFFORT, val);
- } else {
- localStorage.removeItem(LS_KEY_EFFORT);
- }
- } catch {
- // Ignore localStorage errors
- }
+ if (val) safeWriteStorage(LS_KEY_EFFORT, val);
+ else safeRemoveStorage(LS_KEY_EFFORT);
};
const handleEnhance = async () => {
diff --git a/client/src/components/media/PromptFromMedia.jsx b/client/src/components/media/PromptFromMedia.jsx
index 58624a20e8..8ed42cf6d5 100644
--- a/client/src/components/media/PromptFromMedia.jsx
+++ b/client/src/components/media/PromptFromMedia.jsx
@@ -11,6 +11,7 @@ import { FormField } from '../ui/FormField';
import { promptFromMedia } from '../../services/apiMediaJobs';
import { isVisionCapableCliProvider, visionLocalModelFilter } from '../../utils/providers';
import { copyToClipboard } from '../../lib/clipboard';
+import { safeReadStorage, safeRemoveStorage, safeWriteStorage } from '../../lib/safeStorage';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
@@ -72,9 +73,7 @@ export default function PromptFromMedia({
const [videoPickerOpen, setVideoPickerOpen] = useState(false);
const [wantImage, setWantImage] = useState(kindDefault !== 'video');
const [wantVideo, setWantVideo] = useState(kindDefault !== 'image');
- const [effort, setEffort] = useState(() => {
- try { return localStorage.getItem(LS_KEY_EFFORT) || ''; } catch { return ''; }
- });
+ const [effort, setEffort] = useState(() => safeReadStorage(LS_KEY_EFFORT) || '');
const [running, setRunning] = useState(false);
const [result, setResult] = useState(null);
const { idsByProvider: visionIds } = useVisionModelIds(isOpen);
@@ -100,14 +99,12 @@ export default function PromptFromMedia({
useEffect(() => {
if (providersLoading || !providers.length) return;
- try {
- const savedProvider = localStorage.getItem(LS_KEY_PROVIDER);
- const savedModel = localStorage.getItem(LS_KEY_MODEL);
- if (savedProvider && providers.some((p) => p.id === savedProvider)) {
- setSelectedProviderId(savedProvider);
- if (savedModel) setSelectedModel(savedModel);
- }
- } catch { /* ignore */ }
+ const savedProvider = safeReadStorage(LS_KEY_PROVIDER);
+ const savedModel = safeReadStorage(LS_KEY_MODEL);
+ if (savedProvider && providers.some((p) => p.id === savedProvider)) {
+ setSelectedProviderId(savedProvider);
+ if (savedModel) setSelectedModel(savedModel);
+ }
}, [providers, providersLoading, setSelectedProviderId, setSelectedModel]);
useEffect(() => {
@@ -117,12 +114,10 @@ export default function PromptFromMedia({
}, [initialSource]);
const persistProvider = (id) => {
- try {
- if (id) localStorage.setItem(LS_KEY_PROVIDER, id);
- else localStorage.removeItem(LS_KEY_PROVIDER);
- localStorage.removeItem(LS_KEY_MODEL);
- localStorage.removeItem(LS_KEY_EFFORT);
- } catch { /* ignore */ }
+ if (id) safeWriteStorage(LS_KEY_PROVIDER, id);
+ else safeRemoveStorage(LS_KEY_PROVIDER);
+ safeRemoveStorage(LS_KEY_MODEL);
+ safeRemoveStorage(LS_KEY_EFFORT);
};
const handleProviderChange = (id) => {
@@ -133,19 +128,15 @@ export default function PromptFromMedia({
const handleModelChange = (model) => {
setSelectedModel(model);
- try {
- if (selectedProviderId) localStorage.setItem(LS_KEY_PROVIDER, selectedProviderId);
- if (model) localStorage.setItem(LS_KEY_MODEL, model);
- else localStorage.removeItem(LS_KEY_MODEL);
- } catch { /* ignore */ }
+ if (selectedProviderId) safeWriteStorage(LS_KEY_PROVIDER, selectedProviderId);
+ if (model) safeWriteStorage(LS_KEY_MODEL, model);
+ else safeRemoveStorage(LS_KEY_MODEL);
};
const handleEffortChange = (val) => {
setEffort(val);
- try {
- if (val) localStorage.setItem(LS_KEY_EFFORT, val);
- else localStorage.removeItem(LS_KEY_EFFORT);
- } catch { /* ignore */ }
+ if (val) safeWriteStorage(LS_KEY_EFFORT, val);
+ else safeRemoveStorage(LS_KEY_EFFORT);
};
const targets = [
diff --git a/client/src/lib/mediaNavigation.test.js b/client/src/lib/mediaNavigation.test.js
new file mode 100644
index 0000000000..a42f5c0f65
--- /dev/null
+++ b/client/src/lib/mediaNavigation.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi } from 'vitest';
+import { getAdjacentMedia, getMediaNavProps } from './mediaNavigation.js';
+
+const items = [
+ { key: 'one' },
+ { key: 'two' },
+ { key: 'three' },
+];
+
+describe('getAdjacentMedia', () => {
+ it('returns both neighbors for a middle item', () => {
+ const nav = getAdjacentMedia(items, { key: 'two' });
+ expect(nav.previous).toEqual({ key: 'one' });
+ expect(nav.next).toEqual({ key: 'three' });
+ expect(nav.hasPrevious).toBe(true);
+ expect(nav.hasNext).toBe(true);
+ });
+
+ it('has no previous on the first item and no next on the last', () => {
+ expect(getAdjacentMedia(items, { key: 'one' })).toMatchObject({
+ previous: null, hasPrevious: false, next: { key: 'two' }, hasNext: true,
+ });
+ expect(getAdjacentMedia(items, { key: 'three' })).toMatchObject({
+ next: null, hasNext: false, previous: { key: 'two' }, hasPrevious: true,
+ });
+ });
+
+ it('returns empty nav when the item has no key or the list is empty', () => {
+ const empty = { previous: null, next: null, hasPrevious: false, hasNext: false };
+ expect(getAdjacentMedia(items, {})).toEqual(empty);
+ expect(getAdjacentMedia([], { key: 'one' })).toEqual(empty);
+ expect(getAdjacentMedia(null, { key: 'one' })).toEqual(empty);
+ });
+});
+
+describe('getMediaNavProps', () => {
+ it('calls onSelect with the adjacent item', () => {
+ const onSelect = vi.fn();
+ const props = getMediaNavProps(items, { key: 'two' }, onSelect);
+ props.onPrevious();
+ props.onNext();
+ expect(onSelect.mock.calls).toEqual([[{ key: 'one' }], [{ key: 'three' }]]);
+ });
+});
diff --git a/client/src/lib/roundDraft.test.js b/client/src/lib/roundDraft.test.js
new file mode 100644
index 0000000000..9a30e39903
--- /dev/null
+++ b/client/src/lib/roundDraft.test.js
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseTempo, clampTempo, stripTempId, localId, buildRoundPatch, TEMPO_MIN, TEMPO_MAX,
+} from './roundDraft.js';
+
+describe('roundDraft tempo', () => {
+ it('parseTempo returns null for empty or non-numeric input', () => {
+ expect(parseTempo('')).toBeNull();
+ expect(parseTempo(null)).toBeNull();
+ expect(parseTempo('abc')).toBeNull();
+ });
+
+ it('clampTempo floors to the band without touching a mid-keystroke parse', () => {
+ expect(parseTempo('6')).toBe(6);
+ expect(clampTempo(6)).toBe(TEMPO_MIN);
+ expect(clampTempo(400)).toBe(TEMPO_MAX);
+ expect(clampTempo(null)).toBeNull();
+ });
+});
+
+describe('roundDraft ids', () => {
+ it('stripTempId blanks a -new-N id and keeps a stable one', () => {
+ expect(stripTempId({ id: 'sec-new-0', title: 'Verse' })).toEqual({ id: '', title: 'Verse' });
+ expect(stripTempId({ id: 'lead' })).toEqual({ id: 'lead' });
+ });
+
+ it('buildRoundPatch blanks nested temp layerIds on reference segments', () => {
+ const tempLayer = localId('layer');
+ const patch = buildRoundPatch({
+ title: 'Song',
+ sections: [{ id: 'sec-new-1' }],
+ layers: [{ id: tempLayer }],
+ scoreParts: [],
+ recordings: [],
+ references: [{
+ id: 'ref-1',
+ segments: [{ layerId: tempLayer }, { layerId: 'lead' }],
+ }],
+ });
+ expect(patch.sections[0].id).toBe('');
+ expect(patch.layers[0].id).toBe('');
+ expect(patch.references[0].segments).toEqual([
+ { layerId: '' },
+ { layerId: 'lead' },
+ ]);
+ });
+});
diff --git a/client/src/lib/unsorted.test.js b/client/src/lib/unsorted.test.js
new file mode 100644
index 0000000000..aa31cce182
--- /dev/null
+++ b/client/src/lib/unsorted.test.js
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import { UNSORTED_ID, buildUnsortedCollection } from './unsorted.js';
+
+describe('buildUnsortedCollection', () => {
+ it('omits images and videos already filed in a collection', () => {
+ const collections = [{
+ items: [
+ { kind: 'image', ref: 'kept.png' },
+ { kind: 'video', ref: 'vid-1' },
+ ],
+ }];
+ const images = [
+ { filename: 'kept.png', createdAt: '2026-01-02' },
+ { filename: 'loose.png', createdAt: '2026-01-03' },
+ ];
+ const videos = [
+ { id: 'vid-1', createdAt: '2026-01-01' },
+ { id: 'vid-2', createdAt: '2026-01-04' },
+ ];
+ const result = buildUnsortedCollection(collections, images, videos);
+ expect(result.id).toBe(UNSORTED_ID);
+ expect(result.synthetic).toBe(true);
+ expect(result.items.map((i) => `${i.kind}:${i.ref}`)).toEqual([
+ 'video:vid-2',
+ 'image:loose.png',
+ ]);
+ });
+
+ it('treats a missing collections/images/videos list as empty', () => {
+ const result = buildUnsortedCollection(null, null, null);
+ expect(result.items).toEqual([]);
+ expect(result.synthetic).toBe(true);
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index a87ec422ec..7f4ef424e3 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -56,6 +56,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiReferenceRepos.js` | Per-app reference-repo registry. |
| `apiReview.js` | Review hub. |
| `apiCodeReview.js` | Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model). |
+| `apiCatalog.js` | Creative catalog ingredients (list/create/update/delete scraps + `listCatalogIngredientsByIds` / facets). |
| `apiCatalogTypes.js` | User-defined catalog ingredient types (list active registry + create/update/delete user types). |
| `apiRuns.js` | Agent run history. |
| `apiScaffold.js` | App scaffolding templates. |
diff --git a/client/src/utils/cityFilter.test.js b/client/src/utils/cityFilter.test.js
new file mode 100644
index 0000000000..5434249d15
--- /dev/null
+++ b/client/src/utils/cityFilter.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest';
+import { computeFilterResult } from './cityFilter.js';
+
+const apps = [
+ { id: 'a', name: 'Alpha', tags: ['prod'], archived: false, overallStatus: 'online', pm2Status: {} },
+ { id: 'b', name: 'Beta', tags: [], archived: false, overallStatus: 'stopped', pm2Status: {} },
+ { id: 'c', name: 'Gamma', tags: ['ops'], archived: false, overallStatus: 'online', pm2Status: { web: { status: 'errored' } } },
+ { id: 'd', name: 'Delta', tags: [], archived: true, overallStatus: 'online', pm2Status: {} },
+];
+
+describe('computeFilterResult', () => {
+ it('returns every app as a match for status=all with no search', () => {
+ const { matches, dimmed } = computeFilterResult({ apps, status: 'all', search: '' });
+ expect(matches.map((a) => a.id)).toEqual(['a', 'b', 'c', 'd']);
+ expect(dimmed.size).toBe(0);
+ });
+
+ it('excludes archived apps from online/stopped/errored', () => {
+ // `online` is overallStatus; an app can also match `errored` via pm2.
+ expect(computeFilterResult({ apps, status: 'online' }).matches.map((a) => a.id)).toEqual(['a', 'c']);
+ expect(computeFilterResult({ apps, status: 'stopped' }).matches.map((a) => a.id)).toEqual(['b']);
+ expect(computeFilterResult({ apps, status: 'errored' }).matches.map((a) => a.id)).toEqual(['c']);
+ });
+
+ it('filters by name, id, or tag and puts the rest in dimmed', () => {
+ const byName = computeFilterResult({ apps, status: 'all', search: 'alp' });
+ expect(byName.matches.map((a) => a.id)).toEqual(['a']);
+ expect([...byName.dimmed]).toEqual(['b', 'c', 'd']);
+
+ const byTag = computeFilterResult({ apps, status: 'all', search: 'ops' });
+ expect(byTag.matches.map((a) => a.id)).toEqual(['c']);
+ });
+
+ it('restricts the agent filter to ids present in agentMap', () => {
+ const agentMap = new Set(['b']);
+ const { matches, dimmed } = computeFilterResult({ apps, status: 'agent', agentMap });
+ expect(matches.map((a) => a.id)).toEqual(['b']);
+ expect(dimmed.has('a')).toBe(true);
+ });
+});
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
index 106f8e9280..157b21fd45 100644
--- a/client/src/utils/fileUpload.js
+++ b/client/src/utils/fileUpload.js
@@ -42,9 +42,10 @@ export const ATTACHMENT_ACCEPT = [
].join(',');
/**
- * Largest raw file the server can accept. Every helper here POSTs its payload
- * base64-encoded inside a JSON body, so the express body limit is the real
- * ceiling — advertising anything larger just produces an opaque 413.
+ * Largest raw file the upload endpoints can accept. Callers POST the payload
+ * base64-encoded inside a JSON body (see `apiMedia.js`), so the express body
+ * limit is the real ceiling — advertising anything larger just produces an
+ * opaque 413. This module itself does no I/O.
*
* Mirror of `MAX_BASE64_UPLOAD_BYTES` in `server/lib/uploadLimits.js`, which
* owns the derivation and the rationale (the client can't import server
diff --git a/docs/API.md b/docs/API.md
index 7e7aced7e9..e8f88ba749 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -19,7 +19,7 @@ Building a native companion client? See [COMPANION_APP_API.md](./COMPANION_APP_A
PortOS is designed for personal/developer use on trusted networks. It implements the following security measures:
- **Network isolation**: By default, access should be restricted to trusted networks (e.g., Tailscale VPN, localhost)
-- **Command allowlist**: Shell command execution is restricted to an approved allowlist (see `server/lib/commandAllowlist.js`)
+- **Command allowlist**: Shell command execution is restricted to an approved allowlist (see `server/lib/commandSecurity.js`)
- **Input validation**: All API inputs are validated using Zod schemas
- **Opt-in authentication**: Off by default (trusting private network/Tailscale), PortOS supports opt-in instance password authentication (enforced by `server/lib/authGate.js`) gating `/api/*`, `/data/*`, and `/sdapi/*` via session cookies, Bearer tokens, or HTTP Basic credentials
@@ -536,6 +536,38 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/openclaw` | OpenClaw operator chat |
| `/api/rounds` | Rounds (music + Morse training) |
| `/api/ask` | Ask (LLM Q&A) |
+| `/api/quota-burn` | Quota-burn plan, catalog, and runs |
+| `/api/timeline` | Human-activity timeline (day + events) |
+| `/api/games` | Game projects |
+| `/api/sprites` | Sprite catalog / export |
+| `/api/threejs-models` | Procedural Three.js models |
+| `/api/image-to-3d` | Image-to-3D conversion |
+| `/api/privacy` | PII vault / trusted-org / broker opt-out |
+| `/api/shell` | Browser PTY shells |
+| `/api/workspace-contexts` | Per-app workspace save/restore |
+| `/api/ports` | Port scan / allocation |
+| `/api/logs` | PM2 process logs |
+| `/api/detect` | App-repo detection |
+| `/api/scaffold` | App scaffolding |
+| `/api/usage` | Provider usage / quota |
+| `/api/daily-driver` | Daily-driver snapshot |
+| `/api/media/sketches` | Media annotation sketches |
+| `/api/attachments` | Task / CoS file attachments |
+| `/api/autofix` | Autofixer metrics |
+| `/api/uploads` | Generic uploads |
+| `/api/agents` | Agent process management (personalities, accounts, schedules, activity, tools) |
+| `/api/cos` | Chief of Staff |
+| `/api/memory` | Memory CRUD / search |
+| `/api/brain` | Brain (second brain) |
+| `/api/media` | Media library |
+| `/api/imessage`, `/api/contacts`, `/api/signal`, `/api/spotify`, `/api/youtube` | Personal-data ingest |
+| `/api/notifications` | Notification stream |
+| `/api/standardize` | App PM2 standardizer |
+| `/api/stacker-news`, `/api/x` | Social integrations |
+| `/api/model-personality` | LLM personality tests |
+| `/api/browser` | Managed Chromium |
+| `/api/creative-commission` | Creative commissions |
+| `/api/midi-runtime` | MIDI runtime |
## WebSocket Events
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index aaefa1688e..fe9401de5c 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -65,6 +65,16 @@ See [VERSIONING.md](./VERSIONING.md) for full details.
3. Push `main` to `release` branch to trigger GitHub Release workflow
4. Push pattern: `git pull --rebase --autostash && git push`
+### Changelog
+
+On every user-visible change, write a fragment — do **not** append to `.changelog/NEXT.md` (that file is assembled at release time; two branches editing it is a guaranteed merge conflict):
+
+```bash
+npm run changelog:add -- <added|changed|fixed|removed> "Daily log no longer double-saves on blur."
+```
+
+See [`.changelog/README.md`](../.changelog/README.md) for the fragment convention.
+
> **Note:** Some older code or automation notes may still reference a `dev` branch workflow. The `main`→`release` workflow described here is the current source of truth.
### Line Endings on Windows
@@ -80,14 +90,12 @@ to re-index files with LF line endings.
### Commit Messages
-Use conventional commit format:
+Use conventional commit prefixes with a human-readable subject — a future reader of `git log --oneline` should understand the change without opening the diff:
```
-feat: add new feature
-fix: resolve bug
-build: version/CI changes
-docs: documentation updates
-refactor: code restructuring
+feat: add a --dry-run flag to changelog:add
+fix: daily log no longer double-saves on blur
+docs: point the API allowlist at commandSecurity.js
```
## Project Structure
diff --git a/docs/README.md b/docs/README.md
index ea4aa8763b..ffe8e4670a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -53,4 +53,5 @@ Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([
- **[themes/](./themes/README.md)** — UI theme specs and the theme integration contract.
- **[examples/](./examples/README.md)** — copy-ready config examples (e.g. Claude Code → Ollama settings).
+- **[`.changelog/README.md`](../.changelog/README.md)** — how to write an unreleased changelog fragment (`npm run changelog:add`).
- **media/** — screenshots and logo used by the root README.
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 26cd25e916..6f48895997 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -363,7 +363,7 @@ max_memory_restart: '500M'
**Symptom**: Frontend changes require manual refresh.
**Solution**:
-- Check Vite is running: `pm2 logs portos-client`
+- Check Vite is running: `pm2 logs portos-ui`
- Ensure file watchers aren't exhausted: `fs.inotify.max_user_watches`
### Tests Failing
@@ -374,7 +374,7 @@ cd server
npm test
# For specific test file
-npm test -- taskParser.test.js
+npm test -- lib/taskParser.test.js
# Watch mode for development
npm run test:watch
diff --git a/docs/VERSIONING.md b/docs/VERSIONING.md
index d435fee120..e31dd5de1d 100644
--- a/docs/VERSIONING.md
+++ b/docs/VERSIONING.md
@@ -44,12 +44,17 @@ CI runs tests and linting. No version changes.
git checkout main
git pull
-# Make changes, commit, push
+# Make changes, then record a changelog fragment (do not edit NEXT.md by hand)
+npm run changelog:add -- fixed "Daily log no longer double-saves on blur."
+
+# Commit, push
git add [changed files]
-git commit -m "fix: resolve issue"
+git commit -m "fix: daily log no longer double-saves on blur"
git pull --rebase --autostash && git push
```
+See [`.changelog/README.md`](../.changelog/README.md) for the fragment convention.
+
### Creating a Release
Use the `/do:release` slash command from `main`. It handles version bumping, changelog finalization, and pushing to the `release` branch.
diff --git a/docs/features/identity-system.md b/docs/features/identity-system.md
index 2fdf487625..41e8b50155 100644
--- a/docs/features/identity-system.md
+++ b/docs/features/identity-system.md
@@ -13,7 +13,7 @@ Four separate workstreams converge on the same vision: a personal digital twin t
| Subsystem | Current State | Location |
|-----------|--------------|----------|
| **Genome** | Fully implemented: 23andMe upload, 117 curated SNP markers across 32 categories, ClinVar integration, epigenetic tracking | `server/services/genome.js`, `GenomeTab.jsx`, `data/meatspace/genome.json` |
-| **Chronotype** | Genetic data ready: 5 sleep/circadian markers (CLOCK rs1801260, DEC2 rs57875989, PER2 rs35333999, CRY1 rs2287161, MTNR1B rs10830963) + `daily_routines` enrichment category. Derivation service not yet built | `curatedGenomeMarkers.js` sleep category, `ENRICHMENT_CATEGORIES.daily_routines` |
+| **Chronotype** | Implemented: `deriveChronotype()` combines the 5 sleep/circadian markers (CLOCK rs1801260, DEC2 rs57875989, PER2 rs35333999, CRY1 rs2287161, MTNR1B rs10830963) with `daily_routines` enrichment and writes `chronotype.json` | `server/services/identity/chronotype.js`, `identity.test.js`, `data/digital-twin/chronotype.json` |
| **Aesthetic Taste** | P2 complete: Taste questionnaire with 5 sections (movies, music, visual_art, architecture, food), conversational Q&A, AI summary generation. Enrichment categories also feed taste data from book/movie/music lists | `TasteTab.jsx`, `taste-questionnaire.js`, `data/digital-twin/taste-profile.json` |
| **Goal Tracking** | Partially exists: `COS-GOALS.md` for CoS missions, `TASKS.md` for user tasks, `EXISTENTIAL.md` soul doc | `data/COS-GOALS.md`, `data/TASKS.md`, `data/digital-twin/EXISTENTIAL.md` |
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index c7fe6d76da..9c5b2eeffb 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -971,19 +971,6 @@ export function getDateString(date = new Date()) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}
-/**
- * Format a duration in milliseconds to a human-readable string.
- * Outputs the most appropriate unit (minutes, hours, days) based on size.
- *
- * @param {number} ms - Duration in milliseconds
- * @returns {string} Formatted duration (e.g., "5m", "2h 30m", "3d 5h")
- *
- * @example
- * formatDuration(30000) // "0m"
- * formatDuration(300000) // "5m"
- * formatDuration(7200000) // "2h 0m"
- * formatDuration(90000000) // "1d 1h"
- */
/**
* UUID v4 regex pattern for validating account/entity IDs.
*/
@@ -1035,6 +1022,19 @@ export function filterBySearch(items, search, fields) {
);
}
+/**
+ * Format a duration in milliseconds to a human-readable string.
+ * Outputs the most appropriate unit (minutes, hours, days) based on size.
+ *
+ * @param {number} ms - Duration in milliseconds
+ * @returns {string} Formatted duration (e.g., "5m", "2h 30m", "3d 5h")
+ *
+ * @example
+ * formatDuration(30000) // "0m"
+ * formatDuration(300000) // "5m"
+ * formatDuration(7200000) // "2h 0m"
+ * formatDuration(90000000) // "1d 1h"
+ */
export function formatDuration(ms) {
if (!ms) return '0m';
const mins = Math.floor(ms / 60000);
diff --git a/server/lib/heavyJobClaim.js b/server/lib/heavyJobClaim.js
index 8edd0152a2..867a49f547 100644
--- a/server/lib/heavyJobClaim.js
+++ b/server/lib/heavyJobClaim.js
@@ -11,7 +11,7 @@ import { randomUUID } from 'crypto';
import { mkdir, readFile, unlink, writeFile } from 'fs/promises';
import { existsSync, readFileSync, unlinkSync } from 'fs';
import { dirname, join } from 'path';
-import { PATHS } from './fileUtils.js';
+import { PATHS, sleep } from './fileUtils.js';
export const HEAVY_LOCAL_JOB_CLAIM_PATH = join(PATHS.data, 'heavy-local-job.claim.json');
export const HEAVY_LOCAL_JOB_STALE_MS = 24 * 60 * 60 * 1000;
@@ -19,8 +19,6 @@ export const HEAVY_LOCAL_JOB_STALE_MS = 24 * 60 * 60 * 1000;
const heldClaims = new Map();
let exitCleanupInstalled = false;
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-
export function isPidAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 73ac6c3464..dadcccac99 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -15,8 +15,7 @@ import { z } from 'zod';
export const MUSIC_VIDEO_MODES = ['director', 'autonomous'];
// Lifecycle. `draft` → has scenes/analysis → `ready` → `rendering` → `complete`
-// (or `failed`). `analyzed` marks "beat map cached but not yet arranged". The
-// render states land with Phase 2; Phase 1 only reaches up to `ready`.
+// (or `failed`). `analyzed` marks "beat map cached but not yet arranged".
export const MUSIC_VIDEO_STATUSES = ['draft', 'analyzed', 'ready', 'rendering', 'complete', 'failed'];
// Optional global visual direction for the whole video.
diff --git a/server/lib/slashdoLoader.js b/server/lib/slashdoLoader.js
index a077a20df1..5e07b6fcb0 100644
--- a/server/lib/slashdoLoader.js
+++ b/server/lib/slashdoLoader.js
@@ -8,10 +8,9 @@
* see `slashdoInvocation.js` for the sibling module covering invocation-style
* resolution (how a workflow is TYPED per host CLI) rather than loading.
*/
-import { readFile } from 'fs/promises';
import { createHash } from 'crypto';
import { join } from 'path';
-import { atomicWrite, PATHS } from './fileUtils.js';
+import { atomicWrite, PATHS, tryReadFile } from './fileUtils.js';
/**
* The include name (`<name>` of `lib/<name>.md`) for a matched `!`cat`` directive,
@@ -43,7 +42,7 @@ async function resolveSlashdoIncludes(content, libDir, { skipInclude = null } =
if (skipInclude?.(name)) {
return { pattern: match[0], content: `_(\`${name}\` omitted — not applicable to this run.)_` };
}
- const libContent = await readFile(join(libDir, match[1]), 'utf-8').catch(() => null);
+ const libContent = await tryReadFile(join(libDir, match[1]));
return { pattern: match[0], content: libContent };
}));
let changed = false;
@@ -126,7 +125,7 @@ export async function loadSlashdoFile(commandName, { stripFrontmatter = false, s
if (slashdoFileCache.has(cacheKey)) return slashdoFileCache.get(cacheKey);
const cmdPath = join(PATHS.slashdo, 'commands/do', `${commandName}.md`);
- let content = await readFile(cmdPath, 'utf-8').catch(() => null);
+ let content = await tryReadFile(cmdPath);
if (!content) return null;
if (stripFrontmatter) {
content = content.replace(/^---[\s\S]*?---\s*/, '');
@@ -207,7 +206,7 @@ export async function loadSlashdoLib(libName, { teams = false } = {}) {
if (slashdoLibCache.has(cacheKey)) return slashdoLibCache.get(cacheKey);
const libDir = join(PATHS.slashdo, 'lib');
- let content = await readFile(join(libDir, `${libName}.md`), 'utf-8').catch(() => null);
+ let content = await tryReadFile(join(libDir, `${libName}.md`));
// Cache the MISS too. An install whose `lib/slashdo` submodule was never
// initialized (`npm run install:all` is what fetches it) would otherwise
// re-attempt the read on every spawn that asks — and since #3733 that is every
diff --git a/server/lib/uploadLimits.test.js b/server/lib/uploadLimits.test.js
index 276763ab4f..6b94ce5958 100644
--- a/server/lib/uploadLimits.test.js
+++ b/server/lib/uploadLimits.test.js
@@ -8,7 +8,7 @@ import {
MAX_BASE64_UPLOAD_BYTES,
MAX_SCREENSHOT_BYTES,
} from './uploadLimits.js';
-import { detectImageFormat } from './fileUtils.js';
+import { ATTACHMENT_ALLOWED_EXTENSIONS, detectImageFormat } from './fileUtils.js';
const HERE = dirname(fileURLToPath(import.meta.url));
const read = (p) => readFileSync(join(HERE, p), 'utf8');
@@ -47,6 +47,14 @@ describe('uploadLimits', () => {
expect(indexSrc).not.toMatch(/express\.(json|urlencoded)\(\{\s*limit:\s*['"]/);
});
+ it('keeps the client attachment-extension list in lockstep with the server', () => {
+ const clientSrc = read('../../client/src/utils/fileUpload.js');
+ const match = clientSrc.match(/export const ALLOWED_ATTACHMENT_EXTENSIONS = \[([\s\S]*?)\];/);
+ expect(match, 'client ALLOWED_ATTACHMENT_EXTENSIONS not found').toBeTruthy();
+ const clientExts = [...match[1].matchAll(/'(\.[a-z0-9]+)'/g)].map((m) => m[1]);
+ expect(new Set(clientExts)).toEqual(ATTACHMENT_ALLOWED_EXTENSIONS);
+ });
+
it('matches the client mirror, which cannot import this module', () => {
// client/src/utils/fileUpload.js hardcodes the same number to size-check
// before uploading. If it drifts high, the user picks a file the parser
diff --git a/server/services/character.js b/server/services/character.js
index 72a3d2224a..8adb26ae02 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -15,7 +15,7 @@
import crypto from 'crypto';
import path from 'path';
-import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, readJSONFile, PATHS, sleep } from '../lib/fileUtils.js';
import * as jiraService from './jira.js';
import * as cosService from './cos.js';
import { getBirthDateStrict } from './meatspace.js';
@@ -376,8 +376,6 @@ export async function addEvent(event) {
return { character: saved, event: logEntry, leveledUp: false };
}
-const delay = ms => new Promise(r => setTimeout(r, ms));
-
export async function syncJiraXP() {
const character = await loadRawCharacter();
const config = await jiraService.getInstances();
@@ -395,7 +393,7 @@ export async function syncJiraXP() {
}
for (let i = 0; i < projects.length; i++) {
- if (i > 0) await delay(500); // Rate-limit JIRA API calls
+ if (i > 0) await sleep(500); // Rate-limit JIRA API calls
const project = projects[i];
let tickets;
try {
diff --git a/server/services/imageGen/frameGuard.js b/server/services/imageGen/frameGuard.js
index a0f9e8e5d1..e186d6a746 100644
--- a/server/services/imageGen/frameGuard.js
+++ b/server/services/imageGen/frameGuard.js
@@ -21,8 +21,9 @@
* PNG lands, so each of them calls the gate from its own completion handler.
*/
-import { readFile, unlink } from 'fs/promises';
+import { unlink } from 'fs/promises';
import { basename } from 'path';
+import { tryReadFile } from '../../lib/fileUtils.js';
import { describeFrameStats, isDegenerateFrame } from '../../lib/imageFrameStats.js';
import { describeDegenerateFrame } from './noImageReason.js';
@@ -34,7 +35,7 @@ export async function degenerateFrameReason(pngPath) {
if (!pngPath) return null;
// A missing file is not this gate's verdict to give — the providers already
// have a "no image was written" path with far better narration.
- const buffer = await readFile(pngPath).catch(() => null);
+ const buffer = await tryReadFile(pngPath, null);
if (!buffer) return null;
const stats = await describeFrameStats(buffer);
if (!isDegenerateFrame(stats)) return null;
diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.js
index caf9517c24..9df4033931 100644
--- a/server/services/meatspacePostDrillCache.js
+++ b/server/services/meatspacePostDrillCache.js
@@ -10,7 +10,7 @@
import { readFile } from 'fs/promises';
import { join } from 'path';
-import { atomicWrite, ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, safeJSONParse, sleep } from '../lib/fileUtils.js';
import { generateLlmDrill } from './meatspacePostLlm.js';
const CACHE_FILE = join(PATHS.data, 'meatspace', 'post-drill-cache.json');
@@ -22,8 +22,6 @@ export const CACHEABLE_TYPES = [
'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',
];
-const delay = ms => new Promise(r => setTimeout(r, ms));
-
let cache = {}; // { type: [drill, drill, ...] }
let replenishing = new Map(); // type -> Promise (in-flight replenishment)
let saveQueued = false;
@@ -92,7 +90,7 @@ function replenishType(type, providerId, model) {
let consecutiveFailures = 0;
try {
for (let i = 0; i < needed; i++) {
- if (i > 0) await delay(2000); // avoid LLM rate limits
+ if (i > 0) await sleep(2000); // avoid LLM rate limits
const drill = await generateLlmDrill(type, { count: 5 }, providerId, model).catch(err => {
console.log(`⚠️ POST cache: failed to generate ${type}: ${err.message}`);
return null;
diff --git a/server/services/meatspacePostDrillCache.test.js b/server/services/meatspacePostDrillCache.test.js
index a4a2325e52..6d9808bdb1 100644
--- a/server/services/meatspacePostDrillCache.test.js
+++ b/server/services/meatspacePostDrillCache.test.js
@@ -13,6 +13,7 @@ vi.mock('../lib/fileUtils.js', () => ({
safeJSONParse: (str, defaultValue) => {
try { return JSON.parse(str); } catch { return defaultValue; }
},
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
}));
vi.mock('./meatspacePostLlm.js', () => ({
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index a19dd46ffa..80bcd82b88 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -42,7 +42,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { atomicWrite, ensureDir, PATHS, readJSONFile, shortId } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile, shortId, tryReadFile } from '../lib/fileUtils.js';
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
@@ -216,7 +216,7 @@ export async function getIngest(videoId) {
export async function getTranscript(videoId) {
const record = await getIngest(videoId);
if (!record?.transcript?.path) return null;
- return readFile(record.transcript.path, 'utf-8').catch(() => null);
+ return tryReadFile(record.transcript.path);
}
/**