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
move submodule management onto the managed-app page and commit pointer bumps
[._.]/ Adam Eivy3a6f22fd76ce
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8a596a0380..6e9f41cc28 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@## 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, files one GitHub issue to fix the drain, and records per-run duration so the burst is visible as a metric.+- Git submodules are now managed per app instead of on one global Dev Tools page. Any managed app whose repo has a `.gitmodules` gets a Submodules tab showing each submodule against its remote, so PortOS's own bundled slashdo is maintained from the PortOS app page alongside its git, processes and update controls. Updating a submodule can now also commit the pointer bump for you: leave "Commit the pointer bump" on and the update stages just that submodule and commits it on the repo's default branch. It refuses to commit — and says why — when the repo is checked out on some other branch, so the bump can't land in the middle of unrelated work. The old `/devtools/submodules` link redirects to PortOS's own tab.- The Usage page can now record what you pay each month for your AI subscriptions (Claude, Codex, Antigravity, Grok) and shows what those plans saved against the estimated API cost. Each plan's price is prorated across whatever report window is selected, so both sides of the comparison cover the same days, and every plan gets its own row: monthly price, cost for this window, the API-rate cost its usage ran up, and the difference. Usage no subscription covers — pay-as-you-go API providers and pre-breakdown legacy rows — is reported separately instead of being credited to a plan.## Fixeddiff --git a/README.md b/README.mdindex a68354f64f..b3656bbef9 100644--- a/README.md+++ b/README.md@@ -69,6 +69,7 @@ Bring your entire portfolio of projects under one roof.- **Smart Import** — Point to a directory and auto-detect project config from `package.json`, `vite.config`, and `ecosystem.config` ([App Wizard docs](./docs/features/app-wizard.md))- **App Templates** — Scaffold new projects from pre-built templates with AI provider integration- **Real-time Logs** — Stream PM2 logs via Socket.IO with tail length control+- **Submodules** — Per-app tab (on repos with a `.gitmodules`) that tracks each git submodule against its remote and updates it, optionally committing the pointer bump on the repo's default branch- **JIRA Integration** — Per-app board config, active sprint resolution, epic search, and ticket creation from the UI ([Sprint Manager docs](./docs/features/jira-sprint-manager.md))- **Autofixer** — Autonomous crash detection and repair: polls PM2 for errored processes, invokes AI to diagnose and fix, tracks attempts with cooldowns ([Autofixer docs](./docs/features/autofixer.md))@@ -223,7 +224,6 @@ Everything you need to manage your dev environment without leaving the browser.- **Feature Agents** — Long-running, scoped agents that own a feature area and pick up work autonomously- **Process Monitor** — View all PM2 processes with live memory, CPU, uptime, and restart controls- **GitHub** — Per-repo branch/PR status, release workflows, and PR creation from the dashboard-- **Submodules** — Track and update git submodules across all registered apps- **JIRA + JIRA Reports** — Per-app sprint board, ticket creation, and weekly/monthly reporting ([Sprint Manager docs](./docs/features/jira-sprint-manager.md))- **DataDog** — Wire in a DataDog API key to surface logs/metrics from monitored apps- **Loops** — Schedule recurring work (cron-style) for any PortOS action or agent taskdiff --git a/client/src/App.jsx b/client/src/App.jsxindex 74e6f6e35e..f5591e5cd0 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -1,7 +1,7 @@import { Suspense, useEffect } from 'react';import { Routes, Route, Navigate, useLocation } from 'react-router';import Layout from './components/Layout';-import { getSettings, updateSettings, getSelfInstance } from './services/api';+import { getSettings, updateSettings, getSelfInstance, PORTOS_APP_ID } from './services/api';import BrailleSpinner from './components/BrailleSpinner';import { CatalogTypesProvider } from './hooks/useCatalogTypes.jsx';import Dashboard from './pages/Dashboard';@@ -37,7 +37,6 @@ const Tribe = lazyWithReload(() => import('./pages/Tribe'));const Timeline = lazyWithReload(() => import('./pages/Timeline'));const Goals = lazyWithReload(() => import('./pages/Goals'));const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));-const Submodules = lazyWithReload(() => import('./pages/Submodules'));const ImageClean = lazyWithReload(() => import('./pages/ImageClean'));const QuotaBurn = lazyWithReload(() => import('./pages/QuotaBurn'));const VideoDownloaderPage = lazyWithReload(() => import('./pages/VideoDownloaderPage'));@@ -262,7 +261,9 @@ export default function App() {<Route path="devtools/quota-burn/:familyId" element={<QuotaBurn />} /><Route path="devtools/runs" element={<RunsHistoryPage />} /><Route path="devtools/runner" element={<RunnerPage />} />- <Route path="devtools/submodules" element={<Submodules />} />+ {/* Submodules moved onto the managed-app detail page (one tab per repo).+ Keeps old links/bookmarks working by landing on PortOS's own tab. */}+ <Route path="devtools/submodules" element={<Navigate to={`/apps/${PORTOS_APP_ID}/submodules`} replace />} /><Route path="devtools/usage" element={<UsagePage />} /><Route path="devtools/video-download" element={<VideoDownloaderPage />} /><Route path="devtools/processes" element={<ProcessesPage />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 3094cfd39f..7d0ec1a652 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -274,7 +274,6 @@ const navItems = [{ to: '/devtools/quota-burn', label: 'Quota Burn', icon: Flame },{ to: '/security', label: 'Security', icon: Camera },{ to: '/shell', label: 'Shell', icon: SquareTerminal },- { to: '/devtools/submodules', label: 'Submodules', icon: GitBranch },{ to: '/system-health', label: 'System Health', icon: Activity },{ to: '/uploads', label: 'Uploads', icon: Upload },{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 },diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 73bf5f4670..c38b60e6a8 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -21,6 +21,7 @@ import IssuesTab from './tabs/IssuesTab';import JiraTab from './tabs/JiraTab';import ProcessesTab from './tabs/ProcessesTab';import ReferencesTab from './tabs/ReferencesTab';+import SubmodulesTab from './tabs/SubmodulesTab';import DatadogTab from './tabs/DatadogTab';import UpdateTab from './tabs/UpdateTab';@@ -209,12 +210,8 @@ export default function AppDetailView() {};const visibleTabs = useMemo(() =>- APP_DETAIL_TABS.filter(t => {- if (t.id === 'update') return app?.id === api.PORTOS_APP_ID;- if (t.id === 'datadog') return app?.datadog?.enabled;- return true;- }),- [app?.id, app?.datadog?.enabled]+ APP_DETAIL_TABS.filter(t => (t.visibleWhen ? t.visibleWhen(app) : true)),+ [app]);if (loading) {@@ -260,6 +257,8 @@ export default function AppDetailView() {return <ProcessesTab appId={app.id} pm2ProcessNames={app.pm2ProcessNames} />;case 'references':return <ReferencesTab appId={appId} appName={app.name} />;+ case 'submodules':+ return <SubmodulesTab repoPath={app.repoPath} />;case 'update':if (app.id !== api.PORTOS_APP_ID) {return (diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex 283e184b6c..4db0c407e4 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -1,3 +1,5 @@+import { PORTOS_APP_ID } from '../../services/apiCore.js';+export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);// The app-config text input / select styling. Shared so a restyle of these forms@@ -66,10 +68,14 @@ export const workItemNoun = (tracker) =>// Overview first, then alphabetical. Every id is a real route segment// (`/apps/:appId/:tab`) so each tab is linkable, bookmarkable, and reachable// from ⌘K — see the routing rules in client/src/CLAUDE.md.+//+// `visibleWhen(app)` gates a tab that only some apps earn; omit it for the tabs+// every app gets. Keeping the predicate on the entry means adding a conditional+// tab is one edit here rather than a second id-string case in the detail view.export const APP_DETAIL_TABS = [{ id: 'overview', label: 'Overview' },{ id: 'automation', label: 'Automation' },- { id: 'datadog', label: 'DataDog' },+ { id: 'datadog', label: 'DataDog', visibleWhen: (app) => !!app?.datadog?.enabled },{ id: 'documents', label: 'Documents' },{ id: 'git', label: 'Git' },{ id: 'gsd', label: 'GSD' },@@ -77,6 +83,9 @@ export const APP_DETAIL_TABS = [{ id: 'jira', label: 'JIRA' },{ id: 'processes', label: 'Processes' },{ id: 'references', label: 'References' },+ // Only repos that declare submodules (a .gitmodules file) get the tab — most+ // managed apps have none, and an always-empty tab is just noise.+ { id: 'submodules', label: 'Submodules', visibleWhen: (app) => !!app?.hasSubmodules },{ id: 'tasks', label: 'Tasks' },- { id: 'update', label: 'Update' },+ { id: 'update', label: 'Update', visibleWhen: (app) => app?.id === PORTOS_APP_ID },];diff --git a/client/src/pages/Submodules.jsx b/client/src/components/apps/tabs/SubmodulesTab.jsxsimilarity index 51%rename from client/src/pages/Submodules.jsxrename to client/src/components/apps/tabs/SubmodulesTab.jsxindex ea9092b567..b24c95449c 100644--- a/client/src/pages/Submodules.jsx+++ b/client/src/components/apps/tabs/SubmodulesTab.jsx@@ -1,32 +1,79 @@-import { useState, useEffect, useRef } from 'react';-import { RefreshCw, ArrowUpCircle, GitBranch, ExternalLink, Check } from 'lucide-react';-import toast from '../components/ui/Toast';-import * as api from '../services/api';-import PageSkeleton from '../components/ui/PageSkeleton';+import { useState, useEffect, useCallback, useRef } from 'react';+import { RefreshCw, ArrowUpCircle, GitBranch, ExternalLink, Check, GitCommit } from 'lucide-react';+import toast from '../../ui/Toast';+import Pill from '../../ui/Pill';+import ToggleSwitch from '../../ToggleSwitch';+import BrailleSpinner from '../../BrailleSpinner';+import * as api from '../../../services/api';+import { parseGitHubUrl } from '../../../lib/githubRepoUrl';-export default function Submodules() {+/** Whether a submodule's pointer differs from what its remote default branch has. */+const needsUpdate = (sub) => sub.behind > 0 || sub.outOfSync || !sub.initialized || sub.conflicted;++/**+ * Browsable URL for a submodule's remote. `.gitmodules` commonly declares the+ * scp-style SSH form (`[email protected]:owner/repo`), which is not a link a+ * browser can follow — normalize it rather than href-ing it raw.+ */+function repoHref(url) {+ const parsed = parseGitHubUrl(url || '');+ if (parsed) return `https://github.com/${parsed.owner}/${parsed.repo}`;+ return /^https?:\/\//i.test(url || '') ? url.replace(/\.git$/, '') : null;+}++/** The status badge a submodule's pointer state earns. `Pill` has no error tone. */+function StatusPill({ sub }) {+ if (!sub.initialized) return <Pill className="shrink-0">not initialized</Pill>;+ if (sub.conflicted) {+ return (+ <Pill tone="bare" className="shrink-0 text-port-error bg-port-error/10 border-port-error/20">+ merge conflict+ </Pill>+ );+ }+ if (sub.outOfSync) return <Pill tone="warning" className="shrink-0">out of sync</Pill>;+ if (sub.behind > 0) return <Pill tone="warning" className="shrink-0">{sub.behind} behind</Pill>;+ return <Pill tone="success" icon={Check} className="shrink-0">up to date</Pill>;+}++/**+ * Git submodules for one managed app's repo. Lists each submodule's pointer vs+ * its remote default branch, updates it, and (when "Commit after update" is on)+ * has the server commit the pointer bump on the repo's default branch.+ */+export default function SubmodulesTab({ repoPath }) {const [submodules, setSubmodules] = useState([]);+ const [defaultBranch, setDefaultBranch] = useState('main');const [loading, setLoading] = useState(true);const [refreshing, setRefreshing] = useState(false);const [updating, setUpdating] = useState(null);+ const [commitAfterUpdate, setCommitAfterUpdate] = useState(true);const batchUpdating = useRef(false);- const loadSubmodules = async (showSpinner = true) => {+ const loadSubmodules = useCallback(async (showSpinner = true) => {+ if (!repoPath) return;if (showSpinner) setLoading(true);else setRefreshing(true);- const data = await api.getSubmodules().catch(() => []);- setSubmodules(data);+ // One call carries both the list and the branch a commit would land on, so+ // the toggle names the same branch the server's commit guard checks.+ const data = await api.getSubmodules(repoPath, { silent: true }).catch(() => null);+ setSubmodules(data?.submodules || []);+ if (data?.defaultBranch) setDefaultBranch(data.defaultBranch);setLoading(false);setRefreshing(false);- };+ }, [repoPath]);- useEffect(() => { loadSubmodules(); }, []);+ useEffect(() => { loadSubmodules(); }, [loadSubmodules]);const handleUpdate = async (subPath) => {setUpdating(subPath);- const result = await api.updateSubmodule(subPath).catch(() => null);+ const result = await api+ .updateSubmodule(subPath, { repoPath, commit: commitAfterUpdate, silent: true })+ .catch(() => null);if (result?.success) {- toast.success(`Updated ${subPath} to ${result.newCommit}`);+ // The note comes from the server's own outcome, not from the toggle — the+ // toggle can be flipped mid-batch, and only the server knows what it did.+ toast.success(`Updated ${subPath} to ${result.newCommit}${result.commitNote ? ` — ${result.commitNote}` : ''}`);setSubmodules(prev => prev.map(s =>s.path === subPath? { ...s, currentCommit: result.newCommit, behind: 0, outOfSync: false, initialized: true, conflicted: false }@@ -39,7 +86,7 @@ export default function Submodules() {};const handleUpdateAll = async () => {- const outdated = submodules.filter(s => s.behind > 0 || s.outOfSync || !s.initialized);+ const outdated = submodules.filter(needsUpdate);if (outdated.length === 0) {toast.success('All submodules are up to date');return;@@ -52,22 +99,45 @@ export default function Submodules() {setUpdating(null);};+ if (!repoPath) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400">+ This app has no repo path configured.+ </div>+ );+ }+if (loading) {- return <PageSkeleton label="Loading submodules" titleWidthClass="w-40" cards={3} sidebar={false} />;+ return (+ <div className="flex items-center justify-center h-40">+ <BrailleSpinner text="Loading submodules" />+ </div>+ );}- const hasUpdates = submodules.some(s => s.behind > 0 || s.outOfSync || !s.initialized);+ const hasUpdates = submodules.some(needsUpdate);return (- <div className="space-y-6">- <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">- <h1 className="text-2xl font-bold text-white">Submodules</h1>+ <div className="space-y-4">+ <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">+ <div className="flex items-center gap-2 text-sm text-gray-300">+ <ToggleSwitch+ size="sm"+ enabled={commitAfterUpdate}+ onChange={() => setCommitAfterUpdate(v => !v)}+ ariaLabel={`Commit submodule updates on ${defaultBranch}`}+ />+ <GitCommit size={14} className="text-port-accent shrink-0" />+ <span>+ Commit the pointer bump on <span className="font-mono text-gray-400">{defaultBranch}</span> after updating+ </span>+ </div><div className="flex gap-2">{hasUpdates && (<buttononClick={handleUpdateAll}disabled={!!updating}- className="px-3 sm:px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm sm:text-base"+ className="px-3 sm:px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm min-h-[40px]"><ArrowUpCircle size={16} /><span className="hidden sm:inline">Update All</span>@@ -77,7 +147,7 @@ export default function Submodules() {<buttononClick={() => loadSubmodules(false)}disabled={refreshing}- className="px-3 sm:px-4 py-2 bg-port-card hover:bg-port-border text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm sm:text-base border border-port-border"+ className="px-3 sm:px-4 py-2 bg-port-card hover:bg-port-border text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm border border-port-border min-h-[40px]"><RefreshCw size={16} className={refreshing ? 'animate-spin' : ''} /><span className="hidden sm:inline">Refresh</span>@@ -98,27 +168,7 @@ export default function Submodules() {<div className="flex items-center gap-2 mb-1"><GitBranch size={16} className="text-port-accent shrink-0" /><h3 className="text-lg font-semibold text-white truncate">{sub.name}</h3>- {!sub.initialized ? (- <span className="px-2 py-0.5 text-xs rounded-full bg-gray-500/20 text-gray-400 shrink-0">- not initialized- </span>- ) : sub.conflicted ? (- <span className="px-2 py-0.5 text-xs rounded-full bg-port-error/20 text-port-error shrink-0">- merge conflict- </span>- ) : sub.outOfSync ? (- <span className="px-2 py-0.5 text-xs rounded-full bg-port-warning/20 text-port-warning shrink-0">- out of sync- </span>- ) : sub.behind > 0 ? (- <span className="px-2 py-0.5 text-xs rounded-full bg-port-warning/20 text-port-warning shrink-0">- {sub.behind} behind- </span>- ) : (- <span className="px-2 py-0.5 text-xs rounded-full bg-port-success/20 text-port-success shrink-0 flex items-center gap-1">- <Check size={10} /> up to date- </span>- )}+ <StatusPill sub={sub} /></div><p className="text-sm text-gray-400 font-mono truncate">{sub.path}</p><div className="flex flex-wrap gap-x-4 gap-y-1 mt-2 text-xs text-gray-500">@@ -130,9 +180,9 @@ export default function Submodules() {{sub.latestMessage && (<p className="text-sm text-gray-400 mt-1 truncate">{sub.latestMessage}</p>)}- {sub.url && (+ {repoHref(sub.url) && (<a- href={sub.url.replace(/\.git$/, '')}+ href={repoHref(sub.url)}target="_blank"rel="noopener noreferrer"className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline mt-1"@@ -143,7 +193,7 @@ export default function Submodules() {</div><buttononClick={() => handleUpdate(sub.path)}- disabled={!!updating || (!sub.behind && !sub.outOfSync && sub.initialized && !sub.conflicted)}+ disabled={!!updating || !needsUpdate(sub)}className="px-3 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm shrink-0 min-h-[40px]">{updating === sub.path ? (diff --git a/client/src/components/apps/tabs/SubmodulesTab.test.jsx b/client/src/components/apps/tabs/SubmodulesTab.test.jsxnew file mode 100644index 0000000000..34103472b9--- /dev/null+++ b/client/src/components/apps/tabs/SubmodulesTab.test.jsx@@ -0,0 +1,78 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++const mockToast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));+vi.mock('../../ui/Toast', () => ({ default: mockToast }));++const mockGetSubmodules = vi.fn();+const mockUpdateSubmodule = vi.fn();+vi.mock('../../../services/api', () => ({+ getSubmodules: (...a) => mockGetSubmodules(...a),+ updateSubmodule: (...a) => mockUpdateSubmodule(...a),+}));++const SubmodulesTab = (await import('./SubmodulesTab')).default;++const REPO = '/Users/me/project';+const BEHIND = { name: 'dep', path: 'lib/dep', currentCommit: 'aaaaaaa', latestCommit: 'bbbbbbb', behind: 3, initialized: true };++describe('SubmodulesTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetSubmodules.mockResolvedValue({ submodules: [BEHIND], defaultBranch: 'trunk' });+ mockUpdateSubmodule.mockResolvedValue({+ success: true, newCommit: 'bbbbbbb', committed: true,+ commitNote: 'committed on trunk', defaultBranch: 'trunk', currentBranch: 'trunk',+ });+ });++ it('scopes the submodule read to the app repo and names its default branch', async () => {+ render(<SubmodulesTab repoPath={REPO} />);++ expect(await screen.findByText('dep')).toBeInTheDocument();+ expect(mockGetSubmodules).toHaveBeenCalledWith(REPO, { silent: true });+ expect(screen.getByText('trunk')).toBeInTheDocument();+ });++ it('requests a commit with the update while the toggle is on', async () => {+ render(<SubmodulesTab repoPath={REPO} />);+ fireEvent.click(await screen.findByRole('button', { name: 'Update' }));++ await waitFor(() => expect(mockUpdateSubmodule).toHaveBeenCalled());+ expect(mockUpdateSubmodule).toHaveBeenCalledWith('lib/dep', { repoPath: REPO, commit: true, silent: true });+ await waitFor(() => expect(mockToast.success).toHaveBeenCalledWith(expect.stringContaining('committed on trunk')));+ });++ it('updates without a commit once the toggle is off', async () => {+ render(<SubmodulesTab repoPath={REPO} />);+ await screen.findByText('dep');+ fireEvent.click(screen.getByRole('switch'));+ fireEvent.click(screen.getByRole('button', { name: 'Update' }));++ await waitFor(() => expect(mockUpdateSubmodule).toHaveBeenCalled());+ expect(mockUpdateSubmodule).toHaveBeenCalledWith('lib/dep', { repoPath: REPO, commit: false, silent: true });+ });++ it('reports the server outcome, not the toggle, after an update', async () => {+ mockUpdateSubmodule.mockResolvedValue({+ success: true, newCommit: 'bbbbbbb', committed: false,+ commitSkipped: 'not-on-default-branch',+ commitNote: 'not committed — repo is on feature/wip, not trunk',+ defaultBranch: 'trunk', currentBranch: 'feature/wip',+ });++ render(<SubmodulesTab repoPath={REPO} />);+ fireEvent.click(await screen.findByRole('button', { name: 'Update' }));++ await waitFor(() => expect(mockToast.success).toHaveBeenCalledWith(expect.stringContaining('not committed — repo is on feature/wip')));+ });++ it('disables Update for a submodule that is already current', async () => {+ mockGetSubmodules.mockResolvedValue({ submodules: [{ ...BEHIND, behind: 0 }], defaultBranch: 'trunk' });++ render(<SubmodulesTab repoPath={REPO} />);++ expect(await screen.findByRole('button', { name: 'Update' })).toBeDisabled();+ expect(screen.queryByRole('button', { name: /Update All/ })).not.toBeInTheDocument();+ });+});diff --git a/client/src/services/apiGit.js b/client/src/services/apiGit.jsindex 3be57e56c2..c6517dab6e 100644--- a/client/src/services/apiGit.js+++ b/client/src/services/apiGit.js@@ -88,8 +88,14 @@ export const checkoutRemoteBranch = (path, branch, options = {}) => request('/gibody: JSON.stringify({ path, branch }),...options});-export const getSubmodules = () => request('/git/submodules/status');-export const updateSubmodule = (path) => request('/git/submodules/update', {- method: 'POST',- body: JSON.stringify({ path })+// repoPath is optional — omitted, the server reports the PortOS checkout's+// submodules. Resolves to `{ submodules, defaultBranch }`.+export const getSubmodules = (repoPath, options = {}) => request(+ `/git/submodules/status${repoPath ? `?${new URLSearchParams({ repoPath })}` : ''}`,+ options+);+export const updateSubmodule = (path, { repoPath, commit, ...options } = {}) => request('/git/submodules/update', {+ method: 'POST',+ body: JSON.stringify({ path, repoPath, commit }),+ ...options});diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 699e7bcc1e..46d7226521 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -6,7 +6,7 @@ PortOS is a local-first operating system for a developer's machines, work, and p- **Dashboard, Apps, and Templates** — Register projects, inspect process health, launch or stop services, and scaffold a new app. See [App Wizard](./app-wizard.md).- **Shell, processes, logs, and system health** — Work with terminal sessions, PM2 processes, action history, and host-level operational signals from the browser.-- **GitHub, JIRA, DataDog, Submodules, and Loops** — Bring project status, issue planning, observability, repository maintenance, and recurring work into DevTools. See [JIRA Sprint Manager](./jira-sprint-manager.md).+- **GitHub, JIRA, DataDog, and Loops** — Bring project status, issue planning, observability, and recurring work into DevTools. See [JIRA Sprint Manager](./jira-sprint-manager.md). Repository maintenance that is inherently per-repo (git branches, submodules) lives on the app's own detail page instead.- **Browser control** — Connect a managed Chrome instance for automated or assisted browser work. See [Browser Management](./browser.md).- **Settings, providers, local models, and usage** — Configure CLI/API/local AI providers, choose models, inspect quota and usage information, and manage local model runtimes.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f43441fb23..a943f9131e 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -3,12 +3,18 @@// Entry: { id, path, label, section, aliases?, keywords? }. See CLAUDE.md// "Command Palette & Voice Nav" for the contract.+import { PORTOS_APP_ID } from './appIdentity.js';+export const NAV_COMMANDS = [{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },{ id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },{ id: 'nav.cybercity', path: '/city', label: 'City', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization', 'cybercity'] },{ id: 'nav.cybercity.settings', path: '/city/settings', label: 'City Settings', section: 'Main', aliases: ['city settings', 'cybercity settings', 'city-settings', 'cybercity-config'], keywords: ['cybercity', 'settings', '3d', 'configure'] },{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },+ // Submodules are per-app (a tab on the app detail page), so this entry is+ // explicitly PortOS's own — the only repo whose app id is a fixed constant.+ // Every other app reaches its tab from /apps/<id>/submodules.+ { id: 'nav.apps.submodules', path: `/apps/${PORTOS_APP_ID}/submodules`, label: 'PortOS Submodules', section: 'Apps', aliases: ['submodules', 'devtools-submodules', 'portos-submodules'], keywords: ['git', 'slashdo', 'vendored', 'update submodule'] },{ id: 'nav.templates', path: '/templates', label: 'Templates', section: 'Main', aliases: ['templates', 'app-templates'], keywords: ['app template', 'create app', 'pre-configured', 'starter'] },{ id: 'nav.catalog', path: '/catalog', label: 'Catalog', section: 'Create', aliases: ['catalog', 'ingredients', 'cast', 'creative-catalog'], keywords: ['character', 'place', 'object', 'idea', 'scene', 'concept', 'inventory', 'reference', 'creative'] },@@ -124,7 +130,6 @@ export const NAV_COMMANDS = [{ id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },{ id: 'nav.devtools.quota-burn', path: '/devtools/quota-burn', label: 'Quota Burn', section: 'Dev Tools', aliases: ['quota-burn', 'burn-quota', 'quota'], keywords: ['subscription', 'usage', 'reset window', 'spend quota', 'claude', 'codex', 'grok', 'agy', 'burn'] },{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },- { id: 'nav.devtools.submodules', path: '/devtools/submodules', label: 'Submodules', section: 'Dev Tools', aliases: ['devtools-submodules'] },{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },{ id: 'nav.devtools.video-download', path: '/devtools/video-download', label: 'Video Downloader', section: 'Dev Tools', aliases: ['video-download', 'video-downloader', 'download-video'], keywords: ['youtube', 'x.com', 'twitter', 'yt-dlp', 'download', 'clip'] },{ id: 'nav.workspace-contexts', path: '/workspace-contexts', label: 'Workspaces', section: 'Dev Tools', aliases: ['workspaces', 'workspace-contexts', 'project-contexts', 'project-switcher'], keywords: ['project', 'context', 'switch project', 'branch', 'shell', 'tasks', 'restore', 'working context'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 18af784bc1..7ff0abb255 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1244,6 +1244,21 @@ export const videoDownloadSchema = z.object({url: z.string().url().max(2048)});+// Git submodules. `repoPath` is the repo ROOT (omitted = the PortOS checkout,+// and it is separately checked against the workspace allowlist); `path` is the+// repo-relative submodule path, matching `git submodule status` output.+const optionalRepoPath = z.string().trim().min(1).max(4096).nullish();++export const submoduleStatusQuerySchema = z.object({+ repoPath: optionalRepoPath+});++export const submoduleUpdateSchema = z.object({+ path: z.string().trim().min(1).max(4096),+ repoPath: optionalRepoPath,+ commit: z.boolean().optional().default(false)+});+// =============================================================================// TRANSITIONAL RE-EXPORTS (issue #1151 split)// =============================================================================diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.jsindex 0654e73fe9..8458fe550b 100644--- a/server/routes/apps/crud.js+++ b/server/routes/apps/crud.js@@ -74,14 +74,21 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {// Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly setconst { uiPort, apiPort, devUiPort } = deriveAppPorts(app, app.processes || []);- // Read version from app's package.json if available+ // Read version from app's package.json if available, and flag whether the+ // repo declares git submodules — the detail view only shows its Submodules+ // tab for repos that actually have any.let appVersion = null;+ let hasSubmodules = false;if (app.repoPath) {- const pkg = await readJSONFile(join(app.repoPath, 'package.json'), null, { logError: false });+ const [pkg, gitmodules] = await Promise.all([+ readJSONFile(join(app.repoPath, 'package.json'), null, { logError: false }),+ pathExists(join(app.repoPath, '.gitmodules')),+ ]);appVersion = pkg?.version || null;+ hasSubmodules = gitmodules;}- res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });+ res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasSubmodules, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });}));// POST /api/apps - Create new appdiff --git a/server/routes/git.js b/server/routes/git.jsindex 2dba715104..b42234f711 100644--- a/server/routes/git.js+++ b/server/routes/git.js@@ -6,6 +6,7 @@ import * as appsService from '../services/apps.js';import { getAgents } from '../services/cosAgentLifecycle.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';+import { validateRequest, submoduleStatusQuerySchema, submoduleUpdateSchema } from '../lib/validation.js';/*** Assert that a caller-supplied workspace path exists, is a directory, and@@ -51,29 +52,23 @@ async function getActiveAgentBranches() {const router = Router();-// GET /api/git/submodules/status - Get all submodule statuses+// GET /api/git/submodules/status?repoPath=… - Submodule statuses for a repo,+// plus the branch a pointer bump would commit to (defaults to the PortOS+// checkout when repoPath is omitted).router.get('/submodules/status', asyncHandler(async (req, res) => {- const submodules = await git.getSubmodules();- res.json(submodules);+ const { repoPath } = validateRequest(submoduleStatusQuerySchema, req.query);+ if (repoPath) assertAllowedWorkspace(repoPath);+ res.json(await git.getSubmoduleOverview(repoPath));}));// POST /api/git/submodules/update - Update a specific submodulerouter.post('/submodules/update', asyncHandler(async (req, res) => {- const rawPath = req.body?.path;- if (!rawPath || typeof rawPath !== 'string') {- throw new ServerError('path must be a non-empty string', { status: 400, code: 'VALIDATION_ERROR' });- }- const path = rawPath.trim();- if (!path) {- throw new ServerError('path must be a non-empty string', { status: 400, code: 'VALIDATION_ERROR' });- }- // Validate that this is a known submodule path (cheap check, no remote fetches)- const knownPaths = await git.getSubmodulePaths();- if (!knownPaths.includes(path)) {- throw new ServerError(`Unknown submodule path: ${path}`, { status: 400, code: 'VALIDATION_ERROR' });- }- const newCommit = await git.updateSubmodule(path);- res.json({ success: true, newCommit });+ const { path, repoPath, commit } = validateRequest(submoduleUpdateSchema, req.body);+ if (repoPath) assertAllowedWorkspace(repoPath);+ // The service owns the "is this a real submodule of that repo?" check and+ // throws a 400 ServerError — re-listing them here would just spawn git twice.+ const result = await git.updateSubmodule(path, { repoPath, commit });+ res.json({ success: true, ...result });}));// GET /api/git/:appId - Get git info for an appdiff --git a/server/routes/git.test.js b/server/routes/git.test.jsindex 259916dd97..c3cb8f556f 100644--- a/server/routes/git.test.js+++ b/server/routes/git.test.js@@ -15,8 +15,9 @@ vi.mock('../services/git.js', () => ({getGitInfo: vi.fn().mockResolvedValue({}),getBranches: vi.fn().mockResolvedValue([]),getSubmodules: vi.fn().mockResolvedValue([]),+ getSubmoduleOverview: vi.fn().mockResolvedValue({ submodules: [], defaultBranch: 'main' }),getSubmodulePaths: vi.fn().mockResolvedValue([]),- updateSubmodule: vi.fn().mockResolvedValue('abc'),+ updateSubmodule: vi.fn().mockResolvedValue({ newCommit: 'abc', committed: false }),getAppById: vi.fn(),updateBranches: vi.fn().mockResolvedValue({}),getBranchComparison: vi.fn().mockResolvedValue({}),@@ -282,3 +283,123 @@ describe('git routes — active agent branch exclusion', () => {});});});++describe('git routes — submodules', () => {+ const WORKSPACE = '/Users/me/project';++ beforeEach(() => {+ vi.clearAllMocks();+ allowWorkspace(WORKSPACE);+ });++ it('GET /submodules/status without repoPath reads the PortOS checkout', async () => {+ gitService.getSubmoduleOverview.mockResolvedValue({+ submodules: [{ path: 'lib/dep', name: 'dep' }],+ defaultBranch: 'main'+ });++ const app = makeApp();+ const res = await request(app).get('/api/git/submodules/status');++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ submodules: [{ path: 'lib/dep', name: 'dep' }], defaultBranch: 'main' });+ // Undefined, not a string — the service falls back to the PortOS checkout.+ expect(gitService.getSubmoduleOverview).toHaveBeenCalledWith(undefined);+ });++ it('GET /submodules/status?repoPath scopes the read to that repo', async () => {+ const app = makeApp();+ const res = await request(app)+ .get(`/api/git/submodules/status?repoPath=${encodeURIComponent(WORKSPACE)}`);++ expect(res.status).toBe(200);+ expect(gitService.getSubmoduleOverview).toHaveBeenCalledWith(WORKSPACE);+ });++ it('GET /submodules/status rejects a repoPath outside allowed roots', async () => {+ isWithinAllowedRoots.mockReturnValue(false);+ realpathSync.mockReturnValue('/etc');++ const app = makeApp();+ const res = await request(app)+ .get('/api/git/submodules/status?repoPath=%2Fetc');++ expect(res.status).toBe(403);+ expect(gitService.getSubmoduleOverview).not.toHaveBeenCalled();+ });++ it('POST /submodules/update forwards repoPath + commit and echoes the commit result', async () => {+ gitService.updateSubmodule.mockResolvedValue({+ newCommit: 'def4567',+ committed: true,+ commitSha: 'aaa1111',+ commitNote: 'committed on main',+ defaultBranch: 'main',+ currentBranch: 'main'+ });++ const app = makeApp();+ const res = await request(app)+ .post('/api/git/submodules/update')+ .send({ path: 'lib/dep', repoPath: WORKSPACE, commit: true });++ expect(res.status).toBe(200);+ expect(gitService.updateSubmodule).toHaveBeenCalledWith('lib/dep', { repoPath: WORKSPACE, commit: true });+ expect(res.body).toEqual({+ success: true,+ newCommit: 'def4567',+ committed: true,+ commitSha: 'aaa1111',+ commitNote: 'committed on main',+ defaultBranch: 'main',+ currentBranch: 'main'+ });+ // The service owns the known-submodule check; the route must not re-list.+ expect(gitService.getSubmodulePaths).not.toHaveBeenCalled();+ });++ it('POST /submodules/update defaults commit to false when the flag is absent', async () => {+ const app = makeApp();+ const res = await request(app)+ .post('/api/git/submodules/update')+ .send({ path: 'lib/dep' });++ expect(res.status).toBe(200);+ expect(gitService.updateSubmodule).toHaveBeenCalledWith('lib/dep', { repoPath: undefined, commit: false });+ });++ it('POST /submodules/update rejects a missing path with a 400', async () => {+ const app = makeApp();+ const res = await request(app).post('/api/git/submodules/update').send({});++ expect(res.status).toBe(400);+ expect(gitService.updateSubmodule).not.toHaveBeenCalled();+ });++ it('POST /submodules/update surfaces the service 400 for an unknown submodule path', async () => {+ gitService.updateSubmodule.mockRejectedValue(+ Object.assign(new Error('Unknown submodule path: lib/other'), { status: 400, code: 'VALIDATION_ERROR' })+ );++ const app = makeApp();+ const res = await request(app)+ .post('/api/git/submodules/update')+ .send({ path: 'lib/other', repoPath: WORKSPACE });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('POST /submodules/update rejects a repoPath outside allowed roots', async () => {+ isWithinAllowedRoots.mockReturnValue(false);+ realpathSync.mockReturnValue('/etc');++ const app = makeApp();+ const res = await request(app)+ .post('/api/git/submodules/update')+ .send({ path: 'lib/dep', repoPath: '/etc' });++ expect(res.status).toBe(403);+ expect(gitService.updateSubmodule).not.toHaveBeenCalled();+ });+});diff --git a/server/services/git.js b/server/services/git.jsindex a983d61257..399ed89905 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -19,6 +19,7 @@ import {parsePullRequestUrl} from '../lib/gitForge.js';import { PROTECTED_BRANCHES, validateFilePaths, toLiteralPathspec } from '../lib/gitArgs.js';+import { ServerError } from '../lib/errorHandler.js';// Re-export so callers that used to import from services/git.js keep working.export { execGit };@@ -1198,10 +1199,11 @@ export async function getGitInfo(dir) {}/**- * Get submodule status for the PortOS repo+ * Get submodule status for a repo.+ * @param {string} [repoPath] - Repo root; defaults to the PortOS checkout.*/-export async function getSubmodules() {- const root = PATHS.root;+export async function getSubmodules(repoPath) {+ const root = repoPath || PATHS.root;const result = await execGit(['submodule', 'status'], root);// Split before trimming — the leading space is a status character (means "up to date")const lines = result.stdout.split('\n').filter(l => l.trimEnd());@@ -1282,30 +1284,126 @@ async function fetchRemoteInfo(fullPath, currentCommit) {};}+/**+ * Submodule statuses plus the branch a pointer bump would be committed on, so+ * a caller that needs both doesn't pay for the whole `getGitInfo` fan-out+ * (status + log + diffstat + remote) to read one branch name.+ * @param {string} [repoPath] - Repo root; defaults to the PortOS checkout.+ * @returns {Promise<{submodules: object[], defaultBranch: string}>}+ */+export async function getSubmoduleOverview(repoPath) {+ const root = repoPath || PATHS.root;+ const [submodules, { baseBranch }] = await Promise.all([+ getSubmodules(root),+ getRepoBranches(root)+ ]);+ return { submodules, defaultBranch: baseBranch || 'main' };+}+/*** Get known submodule paths+ * @param {string} [repoPath] - Repo root; defaults to the PortOS checkout.*/-export async function getSubmodulePaths() {- const root = PATHS.root;+export async function getSubmodulePaths(repoPath) {+ const root = repoPath || PATHS.root;const result = await execGit(['submodule', 'status'], root);return result.stdout.split('\n').filter(l => l.trimEnd()).map(parseSubmoduleStatusLine).filter(Boolean).map(s => s.path);}/**- * Update a specific submodule to the latest remote version+ * @typedef {object} SubmoduleCommitResult+ * @property {boolean} committed - Whether a commit was written.+ * @property {string} [commitSha] - Sha of the commit, when one was written.+ * @property {string} [commitMessage] - Subject of the commit, when one was written.+ * @property {'not-on-default-branch'|'no-changes'} [commitSkipped] - Why nothing was committed.+ * @property {string} commitNote - One-phrase rendering of the outcome, for the UI.+ * @property {string} defaultBranch - Branch a pointer bump commits to.+ * @property {string} currentBranch - Branch the repo is actually checked out on.+ */++/**+ * Commit a submodule pointer bump on the repo's default branch.+ *+ * Stages ONLY the submodule path — a repo mid-edit keeps its other dirty files+ * out of the commit. Refuses to commit when the checkout is on any other branch:+ * "we updated the submodule" belongs on the default branch, and silently landing+ * it on whatever feature branch happens to be checked out would pollute unrelated+ * work. The caller gets a reason back instead of a silent no-op.+ *+ * The skip reason ships as both a code and a rendered `commitNote`, so the UI+ * reports what happened without keeping its own copy of the reason table.+ *+ * @param {string} root - Repo root+ * @param {string} subPath - Repo-relative submodule path+ * @param {string|null} newCommit - Short sha the submodule now points at (message detail)+ * @returns {Promise<SubmoduleCommitResult>}+ */+async function commitSubmoduleBump(root, subPath, newCommit) {+ const [{ baseBranch }, currentBranch] = await Promise.all([+ getRepoBranches(root),+ getBranch(root)+ ]);+ const defaultBranch = baseBranch || 'main';+ if (currentBranch !== defaultBranch) {+ console.log(`⏭️ Skipping submodule commit — ${root} is on ${currentBranch}, not ${defaultBranch}`);+ return {+ committed: false,+ commitSkipped: 'not-on-default-branch',+ commitNote: `not committed — repo is on ${currentBranch}, not ${defaultBranch}`,+ defaultBranch,+ currentBranch+ };+ }++ await stageFiles(root, [subPath]);+ const staged = await execGitSafe(['diff', '--cached', '--name-only', '--', toLiteralPathspec(subPath)], root);+ if (!staged.stdout.trim()) {+ return {+ committed: false,+ commitSkipped: 'no-changes',+ commitNote: 'pointer already committed',+ defaultBranch,+ currentBranch+ };+ }++ const message = `chore: update ${subPath} submodule${newCommit ? ` to ${newCommit}` : ''}`;+ const { hash } = await commit(root, message);+ console.log(`📝 Committed submodule bump ${subPath} on ${defaultBranch} (${hash || 'unknown sha'})`);+ return {+ committed: true,+ commitSha: hash,+ commitMessage: message,+ commitNote: `committed on ${defaultBranch}`,+ defaultBranch,+ currentBranch+ };+}++/**+ * Update a specific submodule to the latest remote version.+ * @param {string} subPath - Repo-relative submodule path+ * @param {object} [options]+ * @param {string} [options.repoPath] - Repo root; defaults to the PortOS checkout.+ * @param {boolean} [options.commit] - Commit the pointer bump on the default branch.+ * @returns {Promise<{newCommit: string|null} & SubmoduleCommitResult>}*/-export async function updateSubmodule(subPath) {- const root = PATHS.root;- // Validate subPath is a known submodule- const knownPaths = await getSubmodulePaths();+export async function updateSubmodule(subPath, { repoPath, commit: shouldCommit = false } = {}) {+ const root = repoPath || PATHS.root;+ // Owns the known-submodule invariant for every caller — thrown as a ServerError+ // so the route doesn't have to re-list the submodules just to answer with a 400.+ const knownPaths = await getSubmodulePaths(root);if (!knownPaths.includes(subPath)) {- throw new Error(`Unknown submodule path: ${subPath}`);+ throw new ServerError(`Unknown submodule path: ${subPath}`, { status: 400, code: 'VALIDATION_ERROR' });}console.log(`📦 Updating submodule ${subPath}...`);await execGit(['submodule', 'update', '--init', '--recursive', '--remote', subPath], root, { timeout: 60000 });console.log(`✅ Submodule ${subPath} updated`);const statusResult = await execGit(['submodule', 'status', subPath], root);const parsed = parseSubmoduleStatusLine(statusResult.stdout);- return parsed ? parsed.commit.substring(0, 7) : null;+ const newCommit = parsed ? parsed.commit.substring(0, 7) : null;++ if (!shouldCommit) return { newCommit, committed: false };+ return { newCommit, ...(await commitSubmoduleBump(root, subPath, newCommit)) };}diff --git a/server/services/git.submodules.test.js b/server/services/git.submodules.test.jsnew file mode 100644index 0000000000..d4e8c830f7--- /dev/null+++ b/server/services/git.submodules.test.js@@ -0,0 +1,106 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Drive updateSubmodule off a scripted git, so the test asserts the exact+// command sequence (and the commit guard) rather than re-implementing it.+vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));++import { execGit } from '../lib/execGit.js';++const REPO = '/Users/me/project';+const SUB = 'lib/dep';++const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });++/**+ * Scripted git: submodule status reports `lib/dep`, origin/HEAD points at+ * `defaultBranch`, HEAD is on `currentBranch`, and `git diff --cached` reports+ * the submodule as staged unless `stagedPointer` is false.+ */+function scriptGit({ defaultBranch = 'main', currentBranch = defaultBranch, stagedPointer = true } = {}) {+ execGit.mockImplementation(async (args) => {+ const [a, b] = args;+ if (a === 'submodule' && b === 'status') return ok(' 1111111222222233333334444444555555566 lib/dep (heads/main)\n');+ if (a === 'submodule' && b === 'update') return ok('');+ if (a === 'symbolic-ref') return ok(`origin/${defaultBranch}\n`);+ if (a === 'rev-parse' && b === '--verify') return ok('ref\n');+ if (a === 'rev-parse' && b === '--abbrev-ref') return ok(`${currentBranch}\n`);+ if (a === 'branch' && b === '--list') return ok(`* ${currentBranch}\n ${defaultBranch}\n`);+ if (a === 'add') return ok('');+ if (a === 'diff') return ok(stagedPointer ? `${SUB}\n` : '');+ if (a === 'commit') return ok(`[${defaultBranch} abc1234] chore\n`);+ return ok('');+ });+}++const callsFor = (verb) => execGit.mock.calls.filter(([args]) => args[0] === verb);++describe('updateSubmodule', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('updates without committing when commit is not requested', async () => {+ scriptGit();+ const { updateSubmodule } = await import('./git.js');++ const result = await updateSubmodule(SUB, { repoPath: REPO });++ expect(result).toEqual({ newCommit: '1111111', committed: false });+ expect(callsFor('commit')).toHaveLength(0);+ // Every command ran against the caller's repo, not the PortOS checkout.+ for (const [, cwd] of execGit.mock.calls) expect(cwd).toBe(REPO);+ });++ it('commits the pointer bump on the default branch when commit is requested', async () => {+ scriptGit();+ const { updateSubmodule } = await import('./git.js');++ const result = await updateSubmodule(SUB, { repoPath: REPO, commit: true });++ expect(result).toMatchObject({+ newCommit: '1111111',+ committed: true,+ commitSha: 'abc1234',+ defaultBranch: 'main',+ currentBranch: 'main'+ });+ expect(result.commitMessage).toContain(SUB);+ // Only the submodule pointer is staged — never the rest of a dirty tree.+ expect(callsFor('add')[0][0]).toEqual(['add', '--', `:(literal)${SUB}`]);+ expect(callsFor('commit')).toHaveLength(1);+ });++ it('refuses to commit when the repo is checked out on another branch', async () => {+ scriptGit({ defaultBranch: 'main', currentBranch: 'feature/wip' });+ const { updateSubmodule } = await import('./git.js');++ const result = await updateSubmodule(SUB, { repoPath: REPO, commit: true });++ expect(result).toMatchObject({+ committed: false,+ commitSkipped: 'not-on-default-branch',+ defaultBranch: 'main',+ currentBranch: 'feature/wip'+ });+ expect(callsFor('add')).toHaveLength(0);+ expect(callsFor('commit')).toHaveLength(0);+ });++ it('reports no-changes instead of creating an empty commit', async () => {+ scriptGit({ stagedPointer: false });+ const { updateSubmodule } = await import('./git.js');++ const result = await updateSubmodule(SUB, { repoPath: REPO, commit: true });++ expect(result).toMatchObject({ committed: false, commitSkipped: 'no-changes' });+ expect(callsFor('commit')).toHaveLength(0);+ });++ it('rejects a path that is not a submodule of the repo', async () => {+ scriptGit();+ const { updateSubmodule } = await import('./git.js');++ await expect(updateSubmodule('lib/other', { repoPath: REPO })).rejects.toThrow(/Unknown submodule path/);+ expect(callsFor('submodule').filter(([args]) => args[1] === 'update')).toHaveLength(0);+ });+});