# Project export: Lattice

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: Lattice is an open source native macOS project to control coding agents, unifying project context, models, tools, and conversations with transparent permissions and cloud/local control.
- Devpost: https://devpost.com/software/lattice-g2qpbh
- GitHub: https://github.com/edgetr/Lattice
- Video: https://www.youtube.com/embed/0IX7r3ADdXM?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — Gökay Ege Süren (173 commits)

## Devpost submission (written by the team)

### Inspiration

AI coding work is powerful, but the daily experience is fragmented across terminal sessions, provider-specific apps, local runtimes, and incompatible permission systems. Context gets lost, execution becomes opaque, and developers are often asked to trade control for convenience. I built Lattice to make serious agent-assisted development feel like one dependable, inspectable workspace on the Mac.

### What it does

Lattice is a native macOS control plane for AI coding agents. It brings durable project conversations, structured coding harnesses, local models, provider-owned CLIs, permissions, privacy controls, and action history into one SwiftUI app. Every new conversation starts with an explicit route: Code for building, debugging, and shipping with coding harnesses. Work for research, browsing, and tool-assisted tasks. Local for private execution with Apple Intelligence or Ollama models available on the Mac. Lattice discovers providers and models at runtime instead of pretending unavailable integrations work. It never silently switches modes, providers, runtimes, or models. Local-only sessions fail closed for cloud-classified routes. The current product includes durable chats with drafts, queues, continuation, branching, editing, pinning, deletion, and search; project-bound working directories; live run and attention state; connection and model management; import/export with sensitive runtime state removed; recovery for corrupt or unwritable data; typed multimodal input; Git-native Code checkpoints; review notes; and guarded, previewed revert flows. Its safety UI stays deliberately specific. Approvals depend on what each harness protocol can actually forward. Sandboxing is described as write containment—not a promise to prevent reads, network access, prompt injection, or exfiltration. Credentials owned by Lattice live in macOS Keychain, while provider CLIs retain their own authentication stores. How I built it Lattice is an open-source Swift 6 project with a native SwiftUI application and a separate LatticeCore module for testable domain policy, persistence, routing, harness behavior, and safety decisions. Provider integrations sit behind harness boundaries and favor structured protocols over terminal scraping. Code routes include a Lattice-owned Pi-based agent path for Codex and OpenCode, plus provider-owned integrations such as Grok Build ACP. Work routes use an isolated Hermes ACP profile with curated toolsets. Local routes use Apple Foundation Models where supported and Ollama's local HTTP/NDJSON APIs. Persistence uses atomic writes and explicit recovery states. Portable archives strip provider session IDs, live approvals, attachment bytes, and hidden reasoning. Concurrency and process ownership are bounded so stale teardown cannot cancel a replacement run, and model discovery is generation-gated so older refreshes cannot overwrite newer truth. OpenAI Codex with GPT-5.6 was a core development partner during Build Week. I used it for codebase analysis, implementation, adversarial review, debugging race conditions, accessibility audits, and verification. The important product and safety decisions remained human-owned, and each meaningful contribution is recorded in dated commits and the repository's Build Week evidence log. Challenges I ran into The hardest problem was not creating just another chat UI. It was reconciling providers that expose very different capabilities without flattening those differences into misleading promises. Some routes provide structured permission events, resumable sessions, or tool activity; others do not. Lattice therefore models availability and enforceable capabilities explicitly and surfaces actionable unavailable states. Durability was another major challenge. Agent runs stream, fail, request approval, recover, and get replaced asynchronously. Making those transitions survive relaunches without stale state clobbering a new run required careful actor isolation, bounded subprocess behavior, atomic stores, failure-path tests, and visible recovery gates. Finally, security language had to match implementation reality. It was tempting to say “sandboxed” or “private” broadly. Instead, Lattice distinguishes cloud routing, write containment, credential ownership, broker mediation, and provider-controlled tools so developers can make informed choices. Accomplishments that I'm proud of A real native Mac workspace that keeps agent conversations and execution evidence together. Runtime-discovered models with truthful loading, failed, unavailable, and recovery states. Explicit Code, Work, and Local routes with no silent cross-mode fallback. Durable checkpoints, scoped review notes, and conflict-aware reverts without destructive Git shortcuts. Failure-focused verification covering persistence, routing, approvals, stale sessions, cancellation races, local-only enforcement, and provider process limits. Accessible interaction details including keyboard behavior, VoiceOver state, and reduced-motion handling. What I learned A trustworthy agent product is defined as much by what it refuses to claim as by what it can execute. Structured protocols, observable state, narrow capability descriptions, and recoverable persistence matter more than flashy autonomy. GPT-5.6 was especially valuable when used as a rigorous engineering collaborator: exploring cross-cutting code, generating bounded implementations, and independently reviewing assumptions—while deterministic tests and human judgment remained the acceptance gate.

### What's next

The next flagship step is an "Inspectable Agent Mission": a project-scoped goal with an editable typed plan, user-approved parallel child runs, declared write scopes, structured status, independent review, and a final evidence bundle. Near-term work also includes deeper harness integrations, richer extension APIs, improved onboarding and accessibility, broader replay fixtures, and a signed and notarized distribution path. Lattice is early open-source software, but the foundation is real and runnable today. The goal is simple: give developers the power of agentic coding tools without asking them to surrender visibility, continuity, or control.

## README (from the GitHub repository)

# Lattice

**A native macOS control plane for AI coding agents.**

Lattice brings coding harnesses, local models, provider-owned CLIs, permissions, privacy controls, and durable project conversations into one coherent SwiftUI workspace. It is designed for developers who want the power of agentic tools without losing visibility into what is running, where data can go, or which actions require approval.

> [!IMPORTANT]
> Lattice is early open-source software. The repository currently produces an unsigned development build for local testing; it is not yet a notarized production release.

## Why Lattice

AI-assisted development is increasingly split across terminal sessions, provider-specific apps, local runtimes, and incompatible approval systems. That fragmentation makes it difficult to preserve context, compare models, understand tool activity, or enforce consistent privacy boundaries.

Lattice is building a single native workspace where developers can:

- Keep project conversations and action history together.
- Connect provider-owned coding harnesses without scraping terminal output.
- Choose between cloud and local execution explicitly.
- Review tool activity and approve consequential actions.
- Discover models based on the providers and runtimes actually available.
- Extend the workspace with user-owned skills and extensions.

## Current capabilities

### Native workspace

- Durable chats with drafts, queues, continuation, branching, editing, deletion, pinning, and search. The Command-K palette also provides metadata-only quick switching across recent chats with live run/attention state.
- Project-bound working directories and a floating overlay.
- Model and connection management with truthful unavailable states.
- Session import/export with sensitive runtime state removed.
- Recovery surfaces for corrupt or unwritable persistent data.

### Execution routes

Every new chat starts with an explicit user choice:

- **Code** — Build, debug, and ship.
- **Work** — Research, browse, and act.
- **Local** — Private models on this Mac.

The model chooser shows only runtime-discovered models for the selected mode. Lattice never automatically switches modes, providers, runtimes, or models.

| Mode | Provider | Integration |
| --- | --- | --- |
| Code | Codex | Lattice Agent (Pi-based) with a Lattice system-instruction and permission extension |
| Code | OpenCode Go/Zen | Lattice Agent (Pi-based) with an explicitly enabled Keychain credential |
| Code | Grok | Grok Build ACP |
| Code | Antigravity | Transcript-driven `agy --print` |
| Work | Codex / Grok / OpenCode | Unmodified Hermes ACP with an isolated Lattice profile and curated toolsets |
| Local | Apple Intelligence | Foundation Models on supported macOS versions |
| Local | Ollama | Local model catalog, pull/install, and streaming chat |

Lattice Agent (Code) and Hermes (Work) are runtime components, not model providers. Their setup and diagnostics live in a collapsed Connections section. Lattice Agent is Lattice-owned (pinned package under Application Support or a bundled binary) and does not use your personal Pi install or `~/.pi` profile. Direct Codex app-server and OpenCode ACP remain compatibility routes for existing chats and v1 archives, but are not offered for new chats.

Authentication is runtime-owned and isolated: Lattice Agent owns the Code Codex login, while Hermes owns the Work Codex and Grok logins. One OpenCode key may be stored in macOS Keychain, but Code and Work access must be enabled and validated separately. Lattice never copies OAuth sessions between CLIs.

### Safety and privacy

Each session has explicit execution and privacy choices. What they enforce depends on the selected runtime—inspect **Route & safety** in the chat inspector before running:

- **Ask** requests approval for material or non-reversible work when the selected provider protocol can forward permission requests. Antigravity Ask stays plan-only.
- **Smart** may auto-allow scoped reads only after a structured provider request arrives; writes remain approval-gated when reversibility or scope evidence is incomplete.
- **YOLO** is explicitly high-trust and may auto-allow provider permission requests. Legacy direct Codex YOLO uses provider `danger-full-access`. Live provider tools do **not** pass through `LocalToolBroker`.
- **Cloud allowed** permits connected cloud and local routes.
- **Local only** blocks routes classified as cloud and keeps execution on available local backends.

Where Lattice applies `sandbox-exec`, it is a **write-containment control**, not a confidentiality boundary: reads and network remain allowed. Legacy direct Codex sandbox settings are provider-configured, not Lattice `sandbox-exec`. Antigravity only receives a provider sandbox option that Lattice does not independently verify. Local chat has no delegated tool loop. Do not treat Local mode as encryption, YOLO as isolation from secrets, or any route as prompt-injection or exfiltration prevention.

## Requirements

### Run Lattice

- macOS 15 or later
- Apple silicon for the current packaging target
- Optional provider CLIs or local runtimes for the routes you want to use

### Build Lattice

- Swift 6 toolchain
- Xcode 26 or a current Swift 6 toolchain with a complete macOS SDK
- Standard macOS packaging tools used by the build script

## Build and run

Clone the repository and run:

```bash
git clone https://github.com/edgetr/Lattice.git
cd Lattice
./script/build_and_run.sh
```

The packaged development app is written to `dist/Lattice.app` and opened automatically.

Additional build-script actions:

```bash
./script/build_and_run.sh --debug
./script/build_and_run.sh --logs
./script/build_and_run.sh --telemetry
```

## Verify

Use the repository script so SwiftPM and the Command Line Tools fallback follow the same checks:

```bash
# Unit tests, or the core verification fallback
./script/build_and_run.sh --test

# Build and validate the app bundle without launching it
./script/build_and_run.sh --verify

# Tests, bundle verification, and distribution-readiness report
./script/build_and_run.sh --release-check
```

With a full Xcode/SwiftPM environment, you can also run:

```bash
swift test
swift build
```

Provider credentials are not required for core verification.

## Data locations

Lattice stores product data under:

```text
~/Library/Application Support/Lattice/
```

Notable data includes durable sessions, user-managed extensions and skills, and compatible harness session state. Secrets managed directly by Lattice use macOS Keychain. Provider CLIs retain their own credential stores and terms.

Legacy `Nisa` identifiers exist only to migrate data created before the Lattice name. New product data and public interfaces should use `Lattice` naming.

## Project structure

```text
Package.swift                 Swift package definition
Sources/Lattice/              SwiftUI application target
Sources/LatticeCore/          Domain, policy, persistence, and harness logic
Tests/LatticeCoreTests/       Swift Testing coverage
Resources/                    Application artwork
script/build_and_run.sh       Build, test, package, and verification entry point
script/verify_core.swift      Command Line Tools verification fallback
AGENTS.md                     Repository guidance for coding agents
BUILD_WEEK.md                 Build Week contribution and evidence log
```

## Development principles

- Unavailable providers must remain visibly unavailable; never simulate success.
- Prefer structured provider protocols over terminal scraping.
- Keep permission, privacy, and sandbox claims narrower than the implementation.
- Never commit credentials, provider sessions, user transcripts, or generated build products.
- Preserve user control over consequential actions and cloud routing.
- Keep core policy testable without provider accounts.

See [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow and [SECURITY.md](SECURITY.md) for responsible vulnerabili

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 263 recognized source files, 3867 KB.
- Swift (language) — detected in the code
- Ollama (technology) — claimed on Devpost, not found in the code
- OpenAI (technology) — claimed on Devpost, not found in the code
- AI coding agent: Codex — evidence: config files committed to the repository

## Codebase structure (from repository index)

### Files (120 of 266)

```
.github/workflows/ci.yml
.gitignore
AGENTS.md
BUILD_WEEK.md
CONTRIBUTING.md
docs/codex-visual-hierarchy-audit.md
docs/plans/code-quality-remediation.md
docs/research/competitive-backlog.md
docs/research/real-work-and-ui-plan.md
docs/research/session-outbox-fast-switch.md
docs/research/t3-code-comparison.md
LICENSE
Package.swift
README.md
Resources/AppIconLayers/Lattice.icon/icon.json
script/build_and_run.sh
script/test_build_lock.sh
script/test_manual_fallback_cache.sh
script/test_packaging_transaction.sh
script/verify_core.swift
SECURITY.md
Sources/Lattice/AccessibilityIdentifiers.swift
Sources/Lattice/AppState.swift
Sources/Lattice/AppState+Connections.swift
Sources/Lattice/AppState+Messaging.swift
Sources/Lattice/AppState+Persistence.swift
Sources/Lattice/AppState+PortableArchive.swift
Sources/Lattice/AppState+Review.swift
Sources/Lattice/AppState+RunPipeline.swift
Sources/Lattice/AppState+SelfEdit.swift
Sources/Lattice/AppState+WorkspaceTools.swift
Sources/Lattice/AssistantArtifactView.swift
Sources/Lattice/CheckpointReviewView.swift
Sources/Lattice/CommandPaletteView.swift
Sources/Lattice/ComposerController.swift
Sources/Lattice/ContextBudgetView.swift
Sources/Lattice/ConversationComposerViews.swift
Sources/Lattice/ConversationMessageViews.swift
Sources/Lattice/ConversationSelfEditViews.swift
Sources/Lattice/ConversationSupportViews.swift
Sources/Lattice/ConversationTranscriptViews.swift
Sources/Lattice/ConversationView.swift
Sources/Lattice/ConversationWorkDockViews.swift
Sources/Lattice/FileBrowserPanel.swift
Sources/Lattice/GlassStyle.swift
Sources/Lattice/InspectorSessionModel.swift
Sources/Lattice/InspectorView.swift
Sources/Lattice/KeychainStore.swift
Sources/Lattice/LatticeApp.swift
Sources/Lattice/LatticeControls.swift
Sources/Lattice/LatticeExecutionCoordinator.swift
Sources/Lattice/LatticeIdentityView.swift
Sources/Lattice/LatticeStylePresentation.swift
Sources/Lattice/MessageContentView.swift
Sources/Lattice/MessageMetadataViews.swift
Sources/Lattice/MorphingControl.swift
Sources/Lattice/OnboardingView.swift
Sources/Lattice/OpenCodeAuthBridge.swift
Sources/Lattice/OverlayLayoutPolicy.swift
Sources/Lattice/OverlayPanel.swift
Sources/Lattice/PersistenceRecoveryView.swift
Sources/Lattice/ProviderConnectionStore.swift
Sources/Lattice/ProviderIdentityView.swift
Sources/Lattice/RunOrchestrator.swift
Sources/Lattice/RuntimeLaunch.swift
Sources/Lattice/ScreenshotCaptureService.swift
Sources/Lattice/SelfEditDraftStore.swift
Sources/Lattice/SessionArchiveViews.swift
Sources/Lattice/SessionCatalogStore.swift
Sources/Lattice/SessionSaveFailureView.swift
Sources/Lattice/TerminalPanelView.swift
Sources/Lattice/WorkspaceCheckpointClient.swift
Sources/Lattice/WorkspaceCheckpointReviewState.swift
Sources/Lattice/WorkspaceLayoutPersistence.swift
Sources/Lattice/WorkspaceToolsController.swift
Sources/Lattice/WorkspaceView.swift
Sources/LatticeCore/ACPHarness.swift
Sources/LatticeCore/ACPLifecycle.swift
Sources/LatticeCore/AgentEvents.swift
Sources/LatticeCore/AgentTaskScheduler.swift
Sources/LatticeCore/AntigravityCLIHarness.swift
Sources/LatticeCore/AppleIntelligenceClient.swift
Sources/LatticeCore/AssistantArtifact.swift
Sources/LatticeCore/AssistantImageArtifactPolicy.swift
Sources/LatticeCore/AssistantTranscriptMediaPolicy.swift
Sources/LatticeCore/AtomicJSONFileTransaction.swift
Sources/LatticeCore/Attachments.swift
Sources/LatticeCore/AttachmentTransportPolicy.swift
Sources/LatticeCore/AutomaticPermissionResolutionPolicy.swift
Sources/LatticeCore/BackendAvailabilityPolicy.swift
Sources/LatticeCore/BoundedProcessTransport.swift
Sources/LatticeCore/BoundedProtocolReader.swift
Sources/LatticeCore/BoundedSubprocess.swift
Sources/LatticeCore/CaptureStorage.swift
Sources/LatticeCore/CatalogPresentationPolicy.swift
Sources/LatticeCore/ChildProcessEnvironmentPolicy.swift
Sources/LatticeCore/CLIActionStatusPolicy.swift
Sources/LatticeCore/CLIInstallResolver.swift
Sources/LatticeCore/CLIVersionDisplayPolicy.swift
Sources/LatticeCore/CodexExecHarness.swift
Sources/LatticeCore/CodexProviderExecutionRoute.swift
Sources/LatticeCore/CommandPaletteChatNavigation.swift
Sources/LatticeCore/CommandPaletteModels.swift
Sources/LatticeCore/CommandPaletteRouting.swift
Sources/LatticeCore/ComposerPresentation.swift
Sources/LatticeCore/ComputerFrame.swift
Sources/LatticeCore/ContextAttachmentInspection.swift
Sources/LatticeCore/ContextBudget.swift
Sources/LatticeCore/ContextBudgetBreakdown.swift
Sources/LatticeCore/ControlActionState.swift
Sources/LatticeCore/ConversationMessagePresentationPolicy.swift
Sources/LatticeCore/ConversationScrollPolicy.swift
Sources/LatticeCore/CredentialPresencePolicy.swift
Sources/LatticeCore/CredentialReadPolicy.swift
Sources/LatticeCore/Domain.swift
Sources/LatticeCore/DurableStoreRecovery.swift
Sources/LatticeCore/ExecutableDiscovery.swift
Sources/LatticeCore/ExecutionCoordinator.swift
Sources/LatticeCore/ExecutionRoutePolicy.swift
Sources/LatticeCore/ExtensionManifest.swift
[146 more files omitted for size]
```

### Dependencies

No dependency index available.

### Recent commits (newest first)

- Harden Pi-first Code routing and durable store I/O.
- Code mode: Lattice Agent ownership, skills control, Phase 3–4 harness depth.
- ci: make Codex discovery probe machine-local in verify_core
- ci: fix fallback verifier module link on full-Xcode runners
- ci: use fallback core verifier on GitHub Actions
- test: prune oversized native suites that kept GitHub CI red
- fix: clear remaining native suite mismatches for GitHub Actions
- fix: stabilize remaining native Swift Testing assertions on CI
- fix: clear unread activity when a selected lane restarts
- fix: use real temp workspaces in ACP tool classification tests
- fix: align native suite expectations with fail-closed product policy
- fix: correct native suite path, route cancel, and capture age cleanup tests
- refactor(app): complete store ownership for sessions, runs, providers
- fix: nest try inside #require for throwing expressions
- fix: allow WorkspaceWindowLayout deinit to drop observers under Swift 6
- fix: finish Swift 6 native CI compile (WorkspaceView + tests)
- fix: restore native Swift Testing compile for CI
- fix: address re-review residual issues for code quality remediation
- fix: address re-review feedback for code quality remediation
- fix: address review feedback for code quality remediation

## Key source files (fetched from GitHub, selected and truncated for size)

### SECURITY.md

```markdown
# Security Policy

## Supported versions

Lattice is pre-release software. Security fixes are applied to the latest version on the default branch; older snapshots are not currently supported.

## Reporting a vulnerability

Please do not open a public issue for a vulnerability that could expose credentials, user data, arbitrary file writes, or unintended command execution. Instead, use GitHub's private vulnerability reporting feature for `edgetr/Lattice`.

Include the affected version or commit, reproduction steps, impact, and any suggested mitigation. Please avoid accessing data that is not yours and give the project a reasonable opportunity to investigate before public disclosure.

## Security boundaries

Lattice coordinates third-party provider CLIs and local runtimes. Those tools retain their own security models and terms. Lattice's harness sandbox is intended to constrain writes to configured roots where used; it is not a confidentiality boundary and does not generally block reads or network access.

```

### CONTRIBUTING.md

```markdown
# Contributing to Lattice

Thank you for helping build Lattice. Contributions should preserve its central promise: powerful agent workflows with explicit user control and truthful system behavior.

## Set up

Requirements and build instructions are in [README.md](README.md). For the standard verification path, run:

```bash
./script/build_and_run.sh --test
./script/build_and_run.sh --verify
```

## Before opening a pull request

- Keep the change focused and explain the user problem it solves.
- Add or update tests for behavioral changes.
- Verify error and unavailable states, not only success paths.
- Update documentation when setup, security boundaries, or user-visible behavior changes.
- Do not include credentials, personal data, provider sessions, generated apps, or build caches.
- Confirm that any new dependency is necessary and license-compatible with MIT distribution.

For UI changes, include screenshots or a short recording and describe keyboard, accessibility, and reduced-motion behavior where relevant.

## Commit and pull-request guidance

Use concise, imperative commit subjects. Pull requests should describe:

1. The problem and intended user outcome.
2. The implementation and important tradeoffs.
3. Safety, privacy, or compatibility implications.
4. Tests and manual verification performed.

By contributing, you agree that your contribution is licensed under the repository's MIT License.

```

### Package.swift

```swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "Lattice",
    platforms: [.macOS(.v15)],
    products: [
        .library(name: "LatticeCore", targets: ["LatticeCore"]),
        .executable(name: "Lattice", targets: ["Lattice"])
    ],
    targets: [
        .target(name: "LatticeCore"),
        .executableTarget(name: "Lattice", dependencies: ["LatticeCore"], linkerSettings: [
            .linkedFramework("Security"),
            .linkedFramework("LocalAuthentication")
        ]),
        .testTarget(name: "LatticeCoreTests", dependencies: ["LatticeCore"])
    ]
)

```

### script/test_manual_fallback_cache.sh

```shell
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Load build functions without entering build_and_run.sh main dispatch.
source <(sed '/^# --- main ---/,$d' "$SCRIPT_DIR/build_and_run.sh")
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

verify_fallback_test_inventory

TEST_SDK="/fake/macos-sdk"
MANUAL_BUILD="$(mktemp -d "${TMPDIR:-/tmp}/lattice-manual-cache-test.XXXXXX")"
trap 'rm -rf "$MANUAL_BUILD"' EXIT

resolve_manual_sdk() { printf '%s\n' "$TEST_SDK"; }
have_swiftpm() { return 1; }

swiftc() {
  local index
  for ((index = 1; index <= $#; index += 1)); do
    case "${!index}" in
      -emit-module-path|-o)
        index=$((index + 1))
        printf x > "${!index}"
        ;;
    esac
  done
}

mkdir -p "$MANUAL_BUILD"
: > "$MANUAL_BUILD/stale-source-output"
ensure_core_library
[[ ! -e "$MANUAL_BUILD/stale-source-output" ]]
[[ -s "$MANUAL_BUILD/libLatticeCore.a" ]]
[[ -s "$MANUAL_BUILD/LatticeCore.swiftmodule" ]]

: > "$MANUAL_BUILD/stale-toolchain-output"
ensure_core_library
[[ ! -e "$MANUAL_BUILD/stale-toolchain-output" ]]

echo "OK: fallback inventory fail-closed and manual cache clean-rebuild pass"

```

### script/test_packaging_transaction.sh

```shell
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source <(sed '/^# --- main ---/,$d' "$SCRIPT_DIR/build_and_run.sh")

TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/lattice-packaging-transaction.XXXXXX")"
trap 'rm -rf "$TEST_ROOT"' EXIT

DIST_DIR="$TEST_ROOT/dist"
APP_BUNDLE="$DIST_DIR/$APP_NAME.app"
set_bundle_paths "$APP_BUNDLE"
ICON_SOURCE="$TEST_ROOT/missing-icon.png"
COMPANION_SOURCE="$TEST_ROOT/missing-companion.png"

BUILD_BINARY="$TEST_ROOT/Lattice"
printf '#!/bin/sh\nexit 0\n' > "$BUILD_BINARY"
chmod +x "$BUILD_BINARY"

verify_bundle() {
  [[ -x "$APP_BINARY" ]]
  if [[ "${FAIL_VALIDATION:-0}" -eq 1 ]]; then
    return 1
  fi
}

mkdir -p "$APP_BUNDLE/Contents"
printf 'last-good\n' > "$APP_BUNDLE/Contents/last-good.marker"

if (FAIL_VALIDATION=1 package_app); then
  echo "FAIL: invalid staged bundle was promoted" >&2
  exit 1
fi
[[ "$(<"$APP_BUNDLE/Contents/last-good.marker")" == "last-good" ]]
[[ ! -e "$DIST_DIR/.${APP_NAME}.app-staging."* ]]

if (
  mv() {
    if [[ "${FAIL_PROMOTION:-0}" -eq 1 && "$1" == "$PACKAGE_STAGING_ROOT/"* ]]; then
      FAIL_PROMOTION=0
      return 1
    fi
    command mv "$@"
  }
  FAIL_PROMOTION=1
  package_app
); then
  echo "FAIL: promotion failure unexpectedly succeeded" >&2
  exit 1
fi
[[ "$(<"$APP_BUNDLE/Contents/last-good.marker")" == "last-good" ]]
[[ ! -e "$DIST_DIR/.${APP_NAME}.app-staging."* ]]
[[ ! -e "$DIST_DIR/.${APP_NAME}.app-backup."* ]]

package_app
[[ ! -e "$APP_BUNDLE/Contents/last-good.marker" ]]
[[ -x "$APP_BUNDLE/Contents/MacOS/$APP_NAME" ]]
[[ -s "$APP_BUNDLE/Contents/Info.plist" ]]
[[ ! -e "$DIST_DIR/.${APP_NAME}.app-staging."* ]]
[[ ! -e "$DIST_DIR/.${APP_NAME}.app-backup."* ]]

echo "OK: packaging preserves last good app on validation failure and promotes valid app"

```

### script/test_build_lock.sh

```shell
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_SOURCE="$SCRIPT_DIR/build_and_run.sh"

TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/lattice-build-lock-test.XXXXXX")"
TEST_LOCK_FILE="$TEST_ROOT/lock"
CRITICAL_SECTION="$TEST_ROOT/critical-section"
FAILURE_FILE="$TEST_ROOT/failure"
trap 'rm -rf "$TEST_ROOT"' EXIT

# A dead PID must be reclaimed by shlock, without any observer seeing an
# empty/partial PID record while contenders replace it.
printf '%s\n' 999999999 >"$TEST_LOCK_FILE"

worker() {
  LATTICE_LOCK_FILE="$TEST_LOCK_FILE" \
  LATTICE_LOCK_TOOL=/usr/bin/shlock \
  LATTICE_LOCK_WAIT_SECONDS=0.01 \
  LATTICE_LOCK_WAIT_LIMIT=500 \
  LATTICE_TEST_CRITICAL_SECTION="$CRITICAL_SECTION" \
  LATTICE_TEST_FAILURE_FILE="$FAILURE_FILE" \
  bash -c '
    set -euo pipefail
    source <(sed "/^# --- main ---/,\$d" "$1")
    acquire_lock
    trap release_lock EXIT

    owner="$(cat "$LOCK_PID_FILE")"
    if [[ ! "$owner" =~ ^[0-9]+$ || "$owner" != "$$" ]]; then
      printf "bad published owner: %s (process %s)\n" "$owner" "$$" >"$LATTICE_TEST_FAILURE_FILE"
      exit 1
    fi

    if ! mkdir "$LATTICE_TEST_CRITICAL_SECTION" 2>/dev/null; then
      printf "concurrent critical section entry by process %s\n" "$$" >"$LATTICE_TEST_FAILURE_FILE"
      exit 1
    fi
    sleep 0.01
    if [[ "$(cat "$LOCK_PID_FILE")" != "$$" ]]; then
      printf "owner changed while lock held: %s (process %s)\n" "$(cat "$LOCK_PID_FILE")" "$$" >"$LATTICE_TEST_FAILURE_FILE"
      rmdir "$LATTICE_TEST_CRITICAL_SECTION"
      exit 1
    fi
    rmdir "$LATTICE_TEST_CRITICAL_SECTION"
  ' bash "$SCRIPT_SOURCE"
}

# Poll while many independent processes acquire/release the same lock. The
# critical-section mkdir catches two live owners; PID assertions catch
# metadata publication/replacement races.
monitor_lock_metadata() {
  for _ in $(seq 1 20000); do
    if [[ -e "$TEST_LOCK_FILE" ]]; then
      local owner
      if ! owner="$(cat "$TEST_LOCK_FILE" 2>/dev/null)"; then
        continue
      fi
      if [[ ! "$owner" =~ ^[0-9]+$ ]]; then
        printf 'partial lock metadata observed: %q\n' "$owner" >"$FAILURE_FILE"
        return 1
      fi
    fi
  done
}

monitor_lock_metadata &
monitor_pid=$!
worker_pids=()
for _ in $(seq 1 24); do
  worker &
  worker_pids+=("$!")
done

status=0
for pid in "${worker_pids[@]}"; do
  wait "$pid" || status=1
done
wait "$monitor_pid" || status=1
if [[ "$status" -ne 0 || -e "$FAILURE_FILE" ]]; then
  cat "$FAILURE_FILE" 2>/dev/null || true
  exit 1
fi
if [[ -e "$TEST_LOCK_FILE" ]]; then
  echo "lock survived all owners" >&2
  exit 1
fi

# A non-owner release must not delete a live owner's lock record.
source <(sed '/^# --- main ---/,$d' "$SCRIPT_SOURCE")
LOCK_FILE="$TEST_LOCK_FILE"
LOCK_PID_FILE="$TEST_LOCK_FILE"
sleep 2 &
live_pid=$!
printf '%s\n' "$live_pid" >"$TEST_LOCK_FILE"
release_lock
[[ "$(cat "$TEST_LOCK_FILE")" == "$live_pid" ]]
kill "$live_pid" 2>/dev/null || true
wait "$live_pid" 2>/dev/null || true
rm -f "$TEST_LOCK_FILE"

echo "OK: atomic build-lock PID publication and stale-PID contention evidence passed"

```

### script/build_and_run.sh

```shell
#!/usr/bin/env bash
# Lattice local build, package, test, and development release-check helper.
# Produces unsigned development app bundles only. Does not sign, notarize,
# staple, or embed credentials/identities.
set -euo pipefail

MODE="${1:-run}"
APP_NAME="Lattice"
BUNDLE_ID="com.lattice.desktop"
# Development identity only — not a production marketing release.
APP_VERSION="0.1.0-dev"
APP_BUILD="1"
MIN_SYSTEM_VERSION="15.0"
EXPECTED_ARCH="arm64"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DIST_DIR="$ROOT_DIR/dist"
APP_BUNDLE="$DIST_DIR/$APP_NAME.app"
APP_CONTENTS="$APP_BUNDLE/Contents"
APP_MACOS="$APP_CONTENTS/MacOS"
APP_RESOURCES="$APP_CONTENTS/Resources"
APP_BINARY="$APP_MACOS/$APP_NAME"
INFO_PLIST="$APP_CONTENTS/Info.plist"
ICON_NAME="AppIcon"
ICON_SOURCE="$ROOT_DIR/Resources/$ICON_NAME.png"
COMPANION_SOURCE="$ROOT_DIR/Resources/LatticeCompanion.png"
PACKAGE_STAGING_ROOT=""
PACKAGE_BACKUP_ROOT=""
PACKAGE_FINAL_BUNDLE="$APP_BUNDLE"
PACKAGE_PROMOTION_IN_PROGRESS=0
LOCK_FILE="${LATTICE_LOCK_FILE:-${TMPDIR:-/tmp}/lattice-build-and-run.lock}"
LOCK_PID_FILE="$LOCK_FILE"
LOCK_TOOL="${LATTICE_LOCK_TOOL:-/usr/bin/shlock}"
LOCK_WAIT_SECONDS="${LATTICE_LOCK_WAIT_SECONDS:-0.2}"
LOCK_WAIT_LIMIT="${LATTICE_LOCK_WAIT_LIMIT:-600}"
MANUAL_BUILD="$ROOT_DIR/.build/manual"
SDK_CANDIDATES=(
  "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"
  "/Library/Developer/CommandLineTools/SDKs/MacOSX27.0.sdk"
  "/Library/Developer/CommandLineTools/SDKs/MacOSX27.sdk"
  "/Library/Developer/CommandLineTools/SDKs/MacOSX26.5.sdk"
  "/Library/Developer/CommandLineTools/SDKs/MacOSX26.sdk"
  "/Library/Developer/CommandLineTools/SDKs/MacOSX15.sdk"
)

set_bundle_paths() {
  APP_BUNDLE="$1"
  APP_CONTENTS="$APP_BUNDLE/Contents"
  APP_MACOS="$APP_CONTENTS/MacOS"
  APP_RESOURCES="$APP_CONTENTS/Resources"
  APP_BINARY="$APP_MACOS/$APP_NAME"
  INFO_PLIST="$APP_CONTENTS/Info.plist"
}

path_exists() {
  [[ -e "$1" || -L "$1" ]]
}

cleanup_package_artifacts() {
  if [[ -n "$PACKAGE_BACKUP_ROOT" ]]; then
    local backup_bundle="$PACKAGE_BACKUP_ROOT/$APP_NAME.app"
    if path_exists "$backup_bundle"; then
      if [[ "$PACKAGE_PROMOTION_IN_PROGRESS" -eq 1 ]]; then
        rm -rf "$PACKAGE_FINAL_BUNDLE"
      fi
      if ! path_exists "$PACKAGE_FINAL_BUNDLE"; then
        mv "$backup_bundle" "$PACKAGE_FINAL_BUNDLE" || true
      fi
    fi
    rm -rf "$PACKAGE_BACKUP_ROOT"
    PACKAGE_BACKUP_ROOT=""
    PACKAGE_PROMOTION_IN_PROGRESS=0
  fi

  if [[ -n "$PACKAGE_STAGING_ROOT" ]]; then
    rm -rf "$PACKAGE_STAGING_ROOT"
    PACKAGE_STAGING_ROOT=""
  fi
}

set_bundle_paths "$APP_BUNDLE"

usage() {
  cat >&2 <<'USAGE'
usage: script/build_and_run.sh [mode]

Modes:
  run                Build, package, and open the app (default)
  --debug|debug      Build, package, and launch under lldb
  --logs|logs        Build, package, open the app, stream process logs
  --telemetry|telemetry
                     Build, package, open the app, stream subsystem logs
  --test|test        Non-destructive: run unit / core verification tests only
  --verify|verify    Non-destructive: build, package, validate resources + Info.plist
  --release-check|release-check
                     Non-destructive: tests + package validation + signing/notarization report

Notes:
  - Development builds are unsigned and not notarized.
  - This script never embeds signing credentials or notarization identities.
  - --test / --verify / --release-check do not launch Lattice or kill a running instance.
USAGE
  exit 2
}

acquire_lock() {
  if [[ ! -x "$LOCK_TOOL" ]]; then
    echo "Cannot acquire build lock: shlock unavailable at $LOCK_TOOL." >&2
    return 1
  fi

  local waited=0
  # shlock prepares PID record and publishes it with atomic link(2).
  # Stale-PID check/removal stays inside same protocol; shell never splits
  # lock acquisition from PID creation.
  while ! "$LOCK_TOOL" -f "$LOCK_FILE" -p "$$" >/dev/null 2>&1; do
    sleep "$LOCK_WAIT_SECONDS"
    waited=$((waited + 1))
    if [[ "$waited" -ge "$LOCK_WAIT_LIMIT" ]]; then
      echo "Timed out waiting for another Lattice build/run task to finish." >&2
      return 1
    fi
  done
}

release_lock() {
  if [[ -f "$LOCK_PID_FILE" ]] && [[ "$(cat "$LOCK_PID_FILE" 2>/dev/null || true)" == "$$" ]]; then
    rm -f "$LOCK_FILE"
  fi
}

on_exit() {
  cleanup_package_artifacts
  release_lock
}

have_swiftpm() {
  xcodebuild -version >/dev/null 2>&1 && swift package --version >/dev/null 2>&1
}

resolve_manual_sdk() {
  # Prefer the active Xcode/CLT SDK so GitHub-hosted full-Xcode runners work
  # (they often have no /Library/Developer/CommandLineTools/SDKs tree).
  if command -v xcrun >/dev/null 2>&1; then
    local xcode_sdk
    xcode_sdk="$(xcrun --sdk macosx --show-sdk-path 2>/dev/null || true)"
    if [[ -n "$xcode_sdk" && -f "$xcode_sdk/SDKSettings.json" ]]; then
      printf '%s\n' "$xcode_sdk"
      return 0
    fi
  fi

  local candidate
  for candidate in "${SDK_CANDIDATES[@]}"; do
    if [[ -f "$candidate/SDKSettings.json" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  # Prefer the highest-versioned MacOSX*.sdk under CLT if present.
  local newest
  newest="$(ls -1d /Library/Developer/CommandLineTools/SDKs/MacOSX*.sdk 2>/dev/null | sort -V | tail -1 || true)"
  if [[ -n "$newest" && -f "$newest/SDKSettings.json" ]]; then
    printf '%s\n' "$newest"
    return 0
  fi
  return 1
}

build_with_swiftpm() {
  echo "==> Building with Swift Package Manager"
  swift build
  BUILD_BINARY="$(swift build --show-bin-path)/$APP_NAME"
}

build_manual_core() {
  local sdk
  if ! sdk="$(resolve_manual_sdk)"; then
    echo "Lattice requires full Xcode or a complete macOS SDK. Swift Package Manager is unavailable." >&2
    exit 1
  fi
  echo "==> Building manually against SDK: $sdk"
  rm -rf "$MANUAL_BUILD"
  mkdir -p "$MANUAL_BUILD"
  # shellcheck disable=SC2086
  swiftc -sdk "$sdk" -target arm64-apple-macosx15.0 -parse-as-library -enable-testing \
    -module-cache-path "$MANUAL_BUILD/mo
[truncated — 14594 more characters]
```

### Sources/LatticeCore/SelfEditProviderLaunchPolicy.swift

```swift
import Foundation

/// Provider launch restrictions for preview-only Lattice self-edit runs.
/// Prompt instructions are not enforcement; the launch boundary is.
public enum SelfEditProviderLaunchPolicy {
    public static let codexExecutionPolicy: ExecutionPolicy = .ask
    public static let codexWorkspaceWrite = false
}

```

### Sources/LatticeCore/Domain.swift

```swift
import Foundation

// Domain types previously lived in this single file. Ownership is now split:
// - SessionModels.swift — sessions, messages, routes, backends, actions
// - AgentEvents.swift — AgentEvent and related activity types
// - Attachments.swift — ContextAttachment* multimodal types
// - CommandPaletteModels.swift — command palette models/matcher
// - ComposerPresentation.swift — MorphingControlState and catalog descriptors
//
// SwiftPM compiles all files in the LatticeCore target; no re-export is required.

```

### Sources/LatticeCore/ExtensionRuntime.swift

```swift
import Foundation

// Extension runtime types previously lived in this single file. Ownership is now split:
// - ExtensionManifest.swift — permissions, manifests, change review
// - ExtensionPatches.swift — style/layout/copy/prompt/operation patches and self-map
// - ExtensionRecords.swift — extension/job/preview records and enablement policy
// - ExtensionStores.swift — durable extension and job stores
// - ExtensionPreviewEditor.swift — preview editor + preview store
//
// SwiftPM compiles all files in the LatticeCore target; no re-export is required.

```

[238 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]