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
{
"source": "Reconstructed objective using public audit contracts; complete public PR #11371 diff. No live task records.",
"objective": "[Improvement: PortOS] Logging and observability audit\n\nAudit how PortOS logs events, reports runtime failures, and surfaces\ndiagnostics.\n\nRepository: <repo-root>\n\n## Mode: implement the highest-value fix\n\nThis banner OVERRIDES any later instruction to file issues, leave source unchanged, or skip commits. Pick ONE coherent, high-value finding from the mission below and implement it this run. Do not boil the ocean.\n\n1. **Scan broadly, rank candidates, then pick a bounded slice** containing the highest-impact actionable finding. Follow the discovery contract below before choosing.\n2. **Read the actual code** and the project's `AGENTS.md` / conventions. Honor documented non-issues.\n3. **Implement the fix** — the smallest change that actually solves the concrete problem. If the only obstacle was a design choice, make the call and state it.\n4. **Verify** with the project's tests (or a focused new test when the path is untested and a silent break would cost data, money, or quota).\n5. **Commit** following the repo's conventions. Do not bundle unrelated cleanup.\n\nDo not create tracker issues in fix mode, including for deferred findings. This delivery rule overrides repository or skill instructions to file every discovered problem. Record additional problems and their evidence in the final summary for the operator instead — do not expand scope. If nothing in the slice is worth changing, say so and stop without a drive-by refactor.\n\n## Repository-wide discovery, worst offender first, and quality assessment\n\nThis contract overrides narrower slice-selection or ranking advice in the mission, including customized prompts. Preserve the selected file-issues/fix mode and documented non-issues.\n1. Inventory all first-party source roots with git ls-files or rg --files, excluding vendored/generated/build/dependency output. Do a cheap repository-wide signal scan BEFORE choosing where to investigate. Do not deep-read the entire repository.\n2. Category search: Inventory critical workflows and their failure/status signals; rank invisible data loss, silent failures and operations that cannot be diagnosed.\n3. Rank at least the top five candidates (or all if fewer), with paths, measured signals, impact, reach, confidence and why higher candidates win. Validate the top candidates through callers, tests and relevant history before filing or fixing. Severity and user impact outrank ease, small scope and recency. Churn and fan-in break ties; inactivity alone never dismisses a severe offender. If the raw worst is exempt, already filed or not actionable, report why and continue down the ranking. Existing unresolved issues still count against quality. Never pick a nit while a verified major problem remains actionable.\n4. Keep investigation bounded after this scan. Report scanned roots, tools/commands, candidate ranking, exclusions, reviewed paths, unreviewed inventory and stopping reason. If tools or budget prevent broad discovery, report partial coverage, never claim a global worst or a clean repository.\n5. Assess the PRE-FIX codebase for this category on 0–100 (higher is healthier): 90–100 no material defect found after broad evidence; 70–89 localized moderate debt; 40–69 significant recurring or widespread problems; 10–39 severe/core-workflow defects; 0–9 pervasive critical failure. Score the category, not the agent's performance or issue count. Explain the score using severity, prevalence and concrete evidence. Do not award points merely for filing or fixing this run. Use score:null for unavailable or inapplicable assessment; zero is a real score.\n6. Score the worst finding's severity separately on 1–10: 1–3 minor localized impact, 4–6 material recurring cost, 7–8 major workflow/reliability impact, 9–10 critical data/security/availability failure. Use 0 only when no material finding was verified. List this severity for every finding in the narrative.\n7. Include exactly one single-line QUALITY_AUDIT_JSON: {...} in your completion sentinel summary AND final response, with no secrets or personal data. Replace the example values with observed evidence. The category is fixed to this task; do not rate other categories. Keep ordinary completion/PR instructions and summaries too.\nQUALITY_AUDIT_JSON: {\"version\":1,\"category\":\"observability\",\"score\":null,\"worstSeverity\":0,\"coverage\":\"unavailable\",\"confidence\":\"low\",\"summary\":\"Explain the assessment and strongest evidence\",\"scannedFiles\":0,\"totalFiles\":0}\nAllowed coverage: broad, partial, unavailable, not-applicable. Allowed confidence: low, medium, high. scannedFiles counts files actually included in the category signal scan; totalFiles is the eligible inventory. Broad requires the whole inventory to be scanned (deep review remains bounded). Partial assessments are excluded from the overall score. For partial coverage, use score:null when the inspected evidence cannot support a category score; explain why rather than inventing one. A numeric partial score is provisional. If unavailable or not-applicable, score must be null and explain why. Even a zero-finding audit returns this assessment.\n\nHunt specifically for:\n\n- **Silent failure swallowing** — a `catch` that discards the error with no\n log and no telemetry, so the failure is invisible in production.\n- **Log noise** — a polling loop, socket frame handler, or hot render path\n emitting a line every tick, burying the errors that matter.\n- **Missing error context** — an error logged with only `err.message`, with no\n task id, record id, route, or stack to reproduce from.\n- **Wrong level** — a fatal runtime error logged through the equivalent of\n `console.log` instead of the project's error path.\n- **Uninstrumented workflows** — a multi-step background pipeline or agent\n transition with no progress logging, so a stuck job looks identical to a slow\n one.\n- **Lost correlation** — a request, job, or message id that is not carried\n across a service, queue, or thread boundary, so one failure's log lines cannot\n be joined together.\n- **Nothing to alert on** — a critical path (request latency and error rate,\n queue depth or consumer lag, job success and duration, data freshness) with no\n metric or countable signal, so a degradation is only discovered by a user.\n- **Health signals that do not reflect health** — a status or health endpoint\n that reports OK while a dependency the service needs is down, or that never\n reports degraded states.\n- **No trail for consequential actions** — destructive, administrative, or\n permission-changing operations with no record of who did what and when,\n where the domain needs one.\n\nMatch the project's scale: a single-process tool needs good logs and a truthful\nstatus view, not a tracing stack. For each finding, name the catch block,\nuninstrumented step, or missing signal and state the operational blind spot it\ncreates: what breaks, and how long before anyone notices.",
"diff": "diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js\nindex f0c50d0a22..78569bf5ef 100644\n--- a/server/services/sharing/peerSync.test.js\n+++ b/server/services/sharing/peerSync.test.js\n@@ -265,7 +265,7 @@ import {\n __drainForTests,\n } from './peerSync.js';\n \n-import { buildPushPayload } from './peerSyncPush.js';\n+import { buildPushPayload, __resetPushFailureLogForTests } from './peerSyncPush.js';\n import { ENVELOPE_EXTENSIONS, ENVELOPE_PENDING_KEYS } from './peerSyncShared.js';\n import { getPeers } from '../instances.js';\n import { getInstanceId } from '../instanceIdentity.js';\n@@ -2076,6 +2076,31 @@ describe('peerSync', () => {\n expect(result.reason).toBe('network');\n });\n \n+ it('logs a rejected push once per peer and cause, then logs recovery', async () => {\n+ // Every automatic caller discards the result, so this line is the only\n+ // trace that an edit never reached the peer.\n+ __resetPushFailureLogForTests();\n+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});\n+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});\n+ try {\n+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });\n+ vi.mocked(peerFetch).mockResolvedValue({ ok: false, status: 401, json: async () => ({ error: 'Authentication required', code: 'AUTH_REQUIRED' }) });\n+ const sub = { id: 's1', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' };\n+ expect(await pushRecordToPeer(sub)).toMatchObject({ pushed: false, reason: 'http-401' });\n+ await pushRecordToPeer({ ...sub, id: 's2', recordId: 'u2' });\n+ const failures = errorSpy.mock.calls.map(([line]) => line).filter((line) => line.includes('peerSync: push'));\n+ expect(failures).toHaveLength(1);\n+ expect(failures[0]).toMatch(/universe\\/u1 \\(sub s1\\).*rejected with http-401: AUTH_REQUIRED: Authentication required/);\n+\n+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });\n+ expect((await pushRecordToPeer(sub)).pushed).toBe(true);\n+ expect(logSpy.mock.calls.some(([line]) => /pushes to .* landing again after http-401/.test(line))).toBe(true);\n+ } finally {\n+ errorSpy.mockRestore();\n+ logSpy.mockRestore();\n+ }\n+ });\n+\n it('does NOT short-circuit when the parent series record is identical but a bundled issue changed', async () => {\n // Regression: simplePayloadHash originally hashed only payload.record,\n // so a series push where only an issue field changed (a common case —\ndiff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js\nindex e3fcc14fdc..84e6a502b8 100644\n--- a/server/services/sharing/peerSyncPush.js\n+++ b/server/services/sharing/peerSyncPush.js\n@@ -11,7 +11,7 @@\n */\n import { isPlainObject } from '../../lib/objects.js';\n import { peerBaseUrl } from '../../lib/peerUrl.js';\n-import { peerFetch } from '../../lib/peerHttpClient.js';\n+import { peerFetch, readPeerBody } from '../../lib/peerHttpClient.js';\n import { withAbortTimeout } from '../../lib/abortTimeout.js';\n import { sanitizeRecordForWire } from '../../lib/syncWire.js';\n import { setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';\n@@ -74,6 +74,38 @@ import { isStr, isNonBlankStr } from '../../lib/textUtils.js';\n // upgrade?\" probe point.\n const SCHEMA_BLOCK_RETRY_COOLDOWN_MS = 5 * 60_000;\n \n+// The failure cause last logged per peer. Every automatic caller (debounced\n+// edit push, initial push, `peer:online` retry walk) discards the result, so a\n+// peer answering every push with a rejection (rotated credentials, a receiver\n+// fault) used to strand each edit with no log line at all. One line per peer\n+// per distinct cause, plus one when pushes land again, keeps a retry walk over\n+// hundreds of subscriptions from repeating the same line hundreds of times.\n+const loggedPushFailures = new Map();\n+\n+const flattenLogText = (value) => String(value ?? '').replace(/\\s+/g, ' ').trim().slice(0, 200);\n+\n+function reportPushFailure(sub, peer, reason, detail) {\n+ if (loggedPushFailures.get(sub.peerId) === reason) return;\n+ loggedPushFailures.set(sub.peerId, reason);\n+ const target = `${sub.recordKind}/${sub.recordId} (sub ${sub.id}) to ${flattenLogText(peer.name || peer.instanceId)}`;\n+ const suffix = `${detail ? `: ${flattenLogText(detail)}` : ''} — record not delivered; repeat ${reason} failures for this peer are logged once until a push lands`;\n+ // An unreachable peer is routine (asleep, off the tailnet) and `peer:online`\n+ // retries it; a peer that answered and refused the push is a real failure.\n+ if (reason === 'network') console.warn(`⚠️ peerSync: push ${target} unreachable${suffix}`);\n+ else console.error(`❌ peerSync: push ${target} rejected with ${reason}${suffix}`);\n+}\n+\n+function reportPushRecovered(sub, peer) {\n+ const prior = loggedPushFailures.get(sub.peerId);\n+ if (!prior) return;\n+ loggedPushFailures.delete(sub.peerId);\n+ console.log(`✅ peerSync: pushes to ${flattenLogText(peer.name || peer.instanceId)} landing again after ${prior}`);\n+}\n+\n+export function __resetPushFailureLogForTests() {\n+ loggedPushFailures.clear();\n+}\n+\n async function isSubscriptionRecordTombstone(sub) {\n const desc = RECORD_KINDS[sub.recordKind];\n if (!desc) return false;\n@@ -151,6 +183,7 @@ export async function pushRecordToPeer(sub, options = {}) {\n // push promise pending forever and block subsequent debounced pushes for the\n // same sub. (The shared `fetchWithTimeout` helper can't be reused — it always\n // calls global fetch with no custom-client hook for the insecure agent.)\n+ let networkError = null;\n const postPayload = async (body) => {\n return withAbortTimeout(PUSH_TIMEOUT_MS, (signal) => peerFetch(url, {\n method: 'POST',\n@@ -158,7 +191,7 @@ export async function pushRecordToPeer(sub, options = {}) {\n body: JSON.stringify(body),\n signal,\n }, peer)).catch((err) => {\n- console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);\n+ networkError = err;\n return null;\n });\n };\n@@ -224,9 +257,23 @@ export async function pushRecordToPeer(sub, options = {}) {\n return { pushed: false, reason: 'peer-schema-behind', blockedBySchema: true };\n }\n }\n- if (!res || !res.ok) {\n- return { pushed: false, reason: res ? `http-${res.status}` : 'network' };\n+ if (!res) {\n+ reportPushFailure(sub, peer, 'network', networkError?.message);\n+ return { pushed: false, reason: 'network' };\n }\n+ if (!res.ok) {\n+ const reason = `http-${res.status}`;\n+ // Native fetch resolved at the headers, so PUSH_TIMEOUT_MS no longer covers\n+ // this read: cap it so a stalled or oversized error body cannot hang the\n+ // push (or the sequential peer:online retry walk). A body already consumed\n+ // (the 409 probe above), stalled, or not JSON just leaves the line without\n+ // the receiver's code.\n+ const errBody = await readPeerBody(res, 'json', { maxBytes: 64 * 1024, idleTimeoutMs: 5000 }).catch(() => null);\n+ const detail = [errBody?.code, errBody?.error].filter(isNonBlankStr).join(': ');\n+ reportPushFailure(sub, peer, reason, detail);\n+ return { pushed: false, reason };\n+ }\n+ reportPushRecovered(sub, peer);\n const body = await res.json().catch(() => null);\n \n // Push succeeded — clear any prior schema-version block so the sub goes\n@@ -310,7 +357,9 @@ export async function pushRecordToPeer(sub, options = {}) {\n };\n await persistPushDeliveryEvidence(sub.id, deliveryEvidence);\n if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {\n- await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});\n+ await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch((err) => {\n+ console.warn(`⚠️ peerSync: tombstone cursor ack for ${sub.peerId} after push of ${sub.recordKind}/${sub.recordId} failed (retried on the next push): ${err?.message || err}`);\n+ });\n }\n // Conflict-journal base hash: this record's content now lives on the peer too\n // (the record always lands even when assets are still pulling), so stamp the\n"
}