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

fix: repair stale submodules during git updates

Adam Eivyc69f61352814
diff --git a/docs/MANAGED_APP_UPDATES.md b/docs/MANAGED_APP_UPDATES.md
index 50fd26f492..41bfff3ca8 100644
--- a/docs/MANAGED_APP_UPDATES.md
+++ b/docs/MANAGED_APP_UPDATES.md
@@ -13,6 +13,14 @@ non-conflicting changes can also carry across the branch switch. Commit work
before updating if you need a durable recovery point, and preserve untracked
files separately — `--autostash` is not an untracked-file backup.
+Repositories with submodules receive `git submodule sync --recursive` and
+`git submodule update --init --recursive` before and after the parent pull. The
+pre-pull pass repairs a checkout left halfway through an earlier update, while
+the post-pull pass checks out the commits pinned by the newly pulled parent.
+PortOS does not use `--remote` here: the parent repository's reviewed gitlinks
+are the update contract. A submodule with local file changes that Git refuses
+to overwrite still blocks the update and is reported as a conflict.
+
A blocked checkout, failed rebase, or conflict while reapplying the autostash
stops the update before lifecycle commands or process restart. PortOS attempts
to abort a failed rebase and queues a CoS conflict-resolution task. An autostash
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.md
index da7f1210e1..f3cecb4583 100644
--- a/docs/SELF_UPDATE.md
+++ b/docs/SELF_UPDATE.md
@@ -16,26 +16,43 @@ The release-notification poll **always queries the upstream `atomantic/PortOS`**
## Pulling: origin, not upstream
-`update.sh` / `update.ps1` always `git pull --rebase --autostash` from **origin**. A fork user who has not merged upstream into their fork gets a silent no-op pull.
+`update.sh` / `update.ps1` always `git pull --rebase` from **origin**. They are
+stash-free; a dirty checkout is refused before the pull. A fork user who has
+not merged upstream into their fork gets a silent no-op pull.
### The update always lands on `main` first
Before pulling, both scripts check the current branch and **switch to `main` if you are anywhere else** — a feature branch or a detached HEAD. This is deliberate: the rest of the script (install, build, restart) has to run on the revision the app will boot from, and pulling on a feature branch would leave the running app on a version the update never advanced.
-If the working tree is dirty when switching off a non-`main` branch or detached HEAD (unstaged, staged, or untracked files), the scripts perform explicit pre-checkout stashing via **`git stash push -u`** so the checkout can proceed, tagging the entry `portos-update-<timestamp>`. The stash is intentionally **not** popped afterwards — the remaining steps need `main`'s contents on disk. On completion the scripts print how to get back:
+If the working tree is dirty when switching off a non-`main` branch or detached
+HEAD — including unstaged, staged, or untracked files — the scripts refuse the
+update before changing branches. They are intentionally stash-free: a hidden
+stash is not an unattended recovery contract, and the operator must commit or
+restore the work before retrying. A clean feature branch or detached checkout
+is still moved to `main` before the pull.
+
+A previous run can be killed after the parent repository advances but before
+its submodule checkout finishes. That leaves the submodule gitlink looking like
+an uncommitted change and would otherwise make the next run fail at `git-pull`.
+Before the dirty-tree guard, both scripts inspect recursive submodule status and
+repair any checkout that is not at the parent commit with:
```bash
-git checkout <your-branch> # or the recorded SHA, if you were on a detached HEAD
-git stash pop
+git submodule sync --recursive
+git submodule update --init --recursive
```
-The entry is at the top of `git stash list`. When already on `main`, pre-checkout stashing is skipped and dirty working trees rely instead on `git pull --autostash` during the pull. Nothing is stashed when the tree is clean, and no checkout occurs when already on `main`. Note that `git stash pop` restores file contents but not the index — anything you had staged comes back unstaged, so re-`git add` it (or pop with `--index`).
-
-**So: an in-app or CLI update run from a feature branch will leave your checkout on `main` with your work parked in the stash.** Commit your work before updating if you would rather not deal with that — pushing alone does not help, since the stash covers uncommitted changes.
+The same pinned update runs after switching to `main` and again after the pull.
+It does not use `--remote`; the parent gitlink is the reviewed release
+contract. Git still refuses to overwrite local files changed inside a
+submodule, so those changes remain a visible update blocker.
### Submodules follow the pulled parent revision
-After pulling `main`, both platform scripts run:
+Before pulling, both platform scripts repair any recursive submodule checkout
+that is not at the commit pinned by the current parent tree. After switching to
+`main` they repeat that repair, then after pulling `main` both platform scripts
+run:
```bash
git submodule sync --recursive
@@ -164,10 +181,12 @@ updater that simply never runs is otherwise indistinguishable from a broken one.
### Checkout readiness: repair mechanically, escalate judgement
-Both update paths MOVE the checkout (`update.sh` switches to `main` and stashes;
-`updateDefaultBranch` checks out, fast-forwards, then falls back to `pull --rebase
---autostash`). Unattended, a stash nobody is told about reads as lost work. So the updater
-refuses until the checkout is on the default branch and clean.
+Both update paths MOVE the checkout. `update.sh` switches to `main` only from a
+clean branch and refuses dirty work; the manual managed-app path
+(`updateDefaultBranch`) can fall back to `pull --rebase --autostash` for
+non-conflicting local changes. The unattended readiness gate refuses until the
+checkout is on the default branch and clean, because a stash nobody is told
+about reads as lost work.
Two remedies run without asking, because neither can destroy work:
diff --git a/scripts/update-submodules.test.js b/scripts/update-submodules.test.js
index c8e4b8861e..a5a1c1470a 100644
--- a/scripts/update-submodules.test.js
+++ b/scripts/update-submodules.test.js
@@ -16,28 +16,43 @@ const SCRIPT_COMMANDS = [
pull: 'run git pull --rebase',
sync: 'run git submodule sync --recursive',
update: 'run git submodule update --init --recursive',
+ preflight: 'if ! repair_stale_submodules; then',
+ dirtyGuard: 'if has_local_changes; then',
},
{
path: 'update.ps1',
pull: 'Invoke-Logged git pull --rebase',
sync: 'Invoke-Logged git submodule sync --recursive',
update: 'Invoke-Logged git submodule update --init --recursive',
+ preflight: 'if (-not (Repair-StaleSubmodules)) {',
+ dirtyGuard: 'if ($hasChanges) {',
},
];
-describe.each(SCRIPT_COMMANDS)('$path submodule update contract', ({ path, pull, sync, update }) => {
+describe.each(SCRIPT_COMMANDS)('$path submodule update contract', ({ path, pull, sync, update, preflight, dirtyGuard }) => {
const source = readFileSync(join(REPO_ROOT, path), 'utf8');
it('syncs recursive metadata and then checks out pinned commits after pulling', () => {
const pullIndex = source.indexOf(pull);
- const syncIndex = source.indexOf(sync);
- const updateIndex = source.indexOf(update);
+ const syncIndex = source.lastIndexOf(sync);
+ const updateIndex = source.lastIndexOf(update);
expect(pullIndex).toBeGreaterThanOrEqual(0);
expect(syncIndex).toBeGreaterThan(pullIndex);
expect(updateIndex).toBeGreaterThan(syncIndex);
});
+ it('repairs an interrupted submodule checkout before the dirty-tree guard', () => {
+ const preflightIndex = source.indexOf(preflight);
+ const dirtyIndex = source.indexOf(dirtyGuard);
+ const pullIndex = source.indexOf(pull);
+
+ expect(preflightIndex).toBeGreaterThanOrEqual(0);
+ expect(dirtyIndex).toBeGreaterThan(preflightIndex);
+ expect(preflightIndex).toBeLessThan(pullIndex);
+ expect(source.indexOf(preflight, preflightIndex + preflight.length)).toBeGreaterThan(dirtyIndex);
+ });
+
it('does not advance submodules past the commits reviewed by PortOS', () => {
expect(source).not.toMatch(/git submodule update[^\n]*--remote/);
});
diff --git a/server/services/git.js b/server/services/git.js
index 7039f5c14c..66e6b75244 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -198,6 +198,7 @@ export async function getRemote(dir) {
const FETCH_MAX_ATTEMPTS = 4;
const FETCH_RETRY_DELAY_MS = 250;
const FETCH_FRESHNESS_MS = 15000;
+const SUBMODULE_UPDATE_TIMEOUT_MS = 60000;
const lastFetchTimes = new Map();
const activeFetches = new Map();
@@ -730,6 +731,57 @@ export async function pull(dir) {
return { success: true, output: result.stdout + result.stderr };
}
+function gitResultOutput(result) {
+ return `${result.stdout || ''}${result.stderr || ''}`;
+}
+
+function gitResultError(result, fallback) {
+ return [result.stdout, result.stderr]
+ .map(stream => (stream || '').trim())
+ .filter(Boolean)
+ .join('\n') || fallback;
+}
+
+/**
+ * Run a pinned-submodule command, retrying once when Git names an abandoned
+ * lock. `git submodule update` is safe to retry after that specific rescue:
+ * unlike a pull/rebase, it has no partially-applied history operation to stack
+ * on top of.
+ */
+async function runPinnedSubmoduleCommand(args, dir) {
+ let result = await execGitSafe(args, dir, { timeout: SUBMODULE_UPDATE_TIMEOUT_MS });
+ if (result.exitCode === 0 || !clearStaleGitLock(result.stderr)) return result;
+ result = await execGitSafe(args, dir, { timeout: SUBMODULE_UPDATE_TIMEOUT_MS });
+ return result;
+}
+
+/**
+ * Synchronize submodule URLs and check out the commits pinned by the parent.
+ * The parent gitlink is the version contract; `--remote` is intentionally not
+ * used because a managed-app update must not consume an unreviewed submodule
+ * head. Kept private because callers need the parent update transaction, not
+ * an independently exposed submodule workflow.
+ */
+async function updatePinnedSubmodules(dir) {
+ const sync = await runPinnedSubmoduleCommand(['submodule', 'sync', '--recursive'], dir);
+ if (sync.exitCode !== 0) {
+ return {
+ success: false,
+ output: gitResultOutput(sync),
+ error: gitResultError(sync, 'could not synchronize submodule metadata')
+ };
+ }
+
+ const update = await runPinnedSubmoduleCommand(['submodule', 'update', '--init', '--recursive'], dir);
+ return {
+ success: update.exitCode === 0,
+ output: gitResultOutput(update),
+ ...(update.exitCode === 0
+ ? {}
+ : { error: gitResultError(update, 'could not update pinned submodules') })
+ };
+}
+
/**
* Move a managed application's primary checkout onto origin's default branch
* and bring it up to date. Non-destructive: nothing is discarded, and local
@@ -737,11 +789,15 @@ export async function pull(dir) {
* `--autostash` (which re-applies it after the rebase).
*
* Order of attempts:
- * 1. `pull --ff-only` — the common case, no rewrite, no stash.
- * 2. `pull --rebase --autostash` — the checkout is dirty and/or the local
+ * 1. Reconcile submodules to the current parent gitlinks, so an interrupted
+ * earlier update cannot make the pull fail on a stale submodule checkout.
+ * 2. `pull --ff-only` — the common case, no rewrite, no stash.
+ * 3. `pull --rebase --autostash` — the checkout is dirty and/or the local
* branch has diverged from origin. This is what "Update App" used to
* refuse outright with DIRTY_WORKTREE.
- * 3. On conflict, abort any in-progress rebase and report `conflict: true`
+ * 4. Reconcile submodules again after the parent pull, because a new commit
+ * can advance a gitlink while leaving its worktree at the old commit.
+ * 5. On conflict, abort any in-progress rebase and report `conflict: true`
* rather than throwing, so the caller can hand the mess to a CoS agent.
*
* A zero exit status is NOT enough to call the rebase clean. `--autostash`
@@ -780,6 +836,21 @@ export async function updateDefaultBranch(dir) {
const currentBranch = await getBranch(dir);
let output = '';
+ const reconcileSubmodules = async () => {
+ const submodules = await updatePinnedSubmodules(dir);
+ output += submodules.output;
+ return submodules.success ? null : {
+ success: false,
+ branch,
+ output,
+ conflict: true,
+ error: `pinned submodule update failed: ${submodules.error}`
+ };
+ };
+
+ const currentSubmoduleError = await reconcileSubmodules();
+ if (currentSubmoduleError) return currentSubmoduleError;
+
if (currentBranch !== branch) {
// Uncommitted changes ride along when they don't collide with the target
// branch; when they do, git refuses and we route that to the conflict path
@@ -801,11 +872,21 @@ export async function updateDefaultBranch(dir) {
: bothStreams(checkout, `could not check out ${branch}`)
};
}
+
+ // Checking out the target branch can change the gitlinks without moving
+ // the submodule worktrees. Reconcile that target tree before pulling so a
+ // previous branch's submodule checkout cannot make the pull fail.
+ const targetSubmoduleError = await reconcileSubmodules();
+ if (targetSubmoduleError) return targetSubmoduleError;
}
const fastForward = await execGit(['pull', '--ff-only', 'origin', branch], dir, { ignoreExitCode: true });
output += fastForward.stdout + fastForward.stderr;
- if (fastForward.exitCode === 0) return { success: true, branch, output, conflict: false };
+ if (fastForward.exitCode === 0) {
+ const submoduleError = await reconcileSubmodules();
+ if (submoduleError) return submoduleError;
+ return { success: true, branch, output, conflict: false };
+ }
const fastForwardLock = clearStaleGitLock(fastForward.stderr);
if (fastForwardLock) {
@@ -823,7 +904,11 @@ export async function updateDefaultBranch(dir) {
if (rebase.exitCode === 0) {
const unmerged = await execGit(['diff', '--name-only', '--diff-filter=U'], dir, { ignoreExitCode: true });
const conflicted = unmerged.stdout.trim().split('\n').filter(Boolean);
- if (!conflicted.length) return { success: true, branch, output, conflict: false, rebased: true };
+ if (!conflicted.length) {
+ const submoduleError = await reconcileSubmodules();
+ if (submoduleError) return submoduleError;
+ return { success: true, branch, output, conflict: false, rebased: true };
+ }
return {
success: false,
branch,
diff --git a/server/services/git.updateDefaultBranch.test.js b/server/services/git.updateDefaultBranch.test.js
index 354e5cc948..0b60ec42b2 100644
--- a/server/services/git.updateDefaultBranch.test.js
+++ b/server/services/git.updateDefaultBranch.test.js
@@ -60,6 +60,34 @@ describe('updateDefaultBranch', () => {
expect(commands().some(command => command.includes('rebase'))).toBe(false);
});
+ it('repairs pinned submodules before and after pulling the parent repository', async () => {
+ withGit({ 'rev-parse --abbrev-ref HEAD': ok('main') });
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: true, branch: 'main', conflict: false });
+ const pulls = commands().map((command, index) => ({ command, index }))
+ .filter(({ command }) => command === 'pull --ff-only origin main');
+ const updates = commands().map((command, index) => ({ command, index }))
+ .filter(({ command }) => command === 'submodule update --init --recursive');
+
+ expect(updates).toHaveLength(2);
+ expect(pulls).toHaveLength(1);
+ expect(updates[0].index).toBeLessThan(pulls[0].index);
+ expect(updates[1].index).toBeGreaterThan(pulls[0].index);
+ });
+
+ it('stops before pulling when pinned submodules cannot be reconciled', async () => {
+ withGit({
+ 'submodule update --init --recursive': fail('fatal: local submodule changes would be overwritten')
+ });
+
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });
+ expect(result.error).toContain('local submodule changes would be overwritten');
+ expect(commands()).not.toContain('pull --ff-only origin main');
+ });
+
it('rebases with --autostash when the checkout is dirty or diverged', async () => {
withGit({
'status --porcelain': ok(' M package-lock.json'),
diff --git a/update.ps1 b/update.ps1
index 7dce74b80c..bd80e395ed 100644
--- a/update.ps1
+++ b/update.ps1
@@ -244,6 +244,25 @@ function Safe-Install {
Stop-UpdateScript 1
}
+# A previous update can advance the superproject and be killed before its
+# submodule step runs. Git then reports the still-old submodule checkout as a
+# dirty gitlink, so the next update would fail at this step forever before it
+# could reach the existing post-pull repair. Reconcile that state first. Git's
+# normal submodule update refuses to overwrite local submodule edits; a user
+# change therefore still reaches the dirty-checkout guard rather than being
+# discarded.
+function Repair-StaleSubmodules {
+ $status = @(git submodule status --recursive 2>$null)
+ $hasDrift = $status | Where-Object { $_ -match '^[+U-]' }
+ if (-not $hasDrift) { return $true }
+
+ Write-SafeHost "🔧 Repairing submodules that are not at the parent checkout's pinned commits..." -ForegroundColor Yellow
+ Invoke-Logged git submodule sync --recursive
+ if ($LASTEXITCODE -ne 0) { return $false }
+ Invoke-Logged git submodule update --init --recursive
+ return $LASTEXITCODE -eq 0
+}
+
# Pull latest — always switch to main (detached HEAD or feature branch both
# need to land on main before pulling, or the version won't advance). The
# rest of the script (install, build, restart) runs on main so the app
@@ -262,6 +281,11 @@ if ($originUrl) {
}
$headRef = git symbolic-ref -q HEAD 2>$null
$currentBranch = if ($headRef) { $headRef -replace "refs/heads/", "" } else { "" }
+if (-not (Repair-StaleSubmodules)) {
+ Write-SafeHost "❌ Could not repair the checkout's pinned submodules" -ForegroundColor Red
+ Step "git-pull" "failed" "Pinned submodule checkout could not be synchronized"
+ Stop-UpdateScript 1
+}
$hasChanges = $false
git diff --quiet 2>$null
if ($LASTEXITCODE -ne 0) { $hasChanges = $true }
@@ -288,6 +312,11 @@ if ($currentBranch -ne "main") {
Invoke-Logged git checkout main
if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
}
+if (-not (Repair-StaleSubmodules)) {
+ Write-SafeHost "❌ Could not repair the main checkout's pinned submodules" -ForegroundColor Red
+ Step "git-pull" "failed" "Pinned submodule checkout could not be synchronized"
+ Stop-UpdateScript 1
+}
# Record main's pre-pull HEAD — captured AFTER any checkout so it's the commit
# the installed node_modules was built from (main, which the rest of this script
# installs/builds), not a feature branch we just left. Diffing this against
diff --git a/update.sh b/update.sh
index 5c9b68a655..c4cba1170c 100755
--- a/update.sh
+++ b/update.sh
@@ -107,6 +107,27 @@ safe_install() {
return 1
}
+# A previous update can advance the superproject and be killed before its
+# submodule step runs. Git then reports the still-old submodule checkout as a
+# dirty gitlink, so the next update would fail at this step forever before it
+# could reach the existing post-pull repair. Reconcile that state first. Git's
+# normal submodule update refuses to overwrite local submodule edits; a user
+# change therefore still reaches the dirty-checkout guard rather than being
+# discarded.
+repair_stale_submodules() {
+ local status
+ status=$(git submodule status --recursive 2>/dev/null || true)
+ if ! printf '%s\n' "$status" | grep -qE '^[+U-]'; then
+ return 0
+ fi
+
+ log "🔧 Repairing submodules that are not at the parent checkout's pinned commits..."
+ if ! run git submodule sync --recursive; then
+ return 1
+ fi
+ run git submodule update --init --recursive
+}
+
# Pull latest — always switch to main (detached HEAD or feature branch both
# need to land on main before pulling, or the version won't advance). The
# rest of the script (install, build, restart) runs on main so the app
@@ -124,6 +145,11 @@ if [ -n "$origin_url" ]; then
echo "🌐 Pulling from origin: $origin_url_safe" >> "$UPDATE_LOG"
fi
current_branch=$(git symbolic-ref -q --short HEAD 2>/dev/null || echo "")
+if ! repair_stale_submodules; then
+ log "❌ Could not repair the checkout's pinned submodules"
+ step "git-pull" "failed" "Pinned submodule checkout could not be synchronized"
+ exit 1
+fi
has_local_changes() {
! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]
}
@@ -136,6 +162,11 @@ if [ "$current_branch" != "main" ]; then
log "⚠️ On branch '${current_branch:-detached HEAD}' — switching to main for update"
run git checkout main
fi
+if ! repair_stale_submodules; then
+ log "❌ Could not repair the main checkout's pinned submodules"
+ step "git-pull" "failed" "Pinned submodule checkout could not be synchronized"
+ exit 1
+fi
# Record main's pre-pull HEAD — captured AFTER any checkout so it's the commit
# the installed node_modules was built from (main, which the rest of this script
# installs/builds), not a feature branch we just left. Diffing this against