Skip to content

Remaining application barrel completion ​

Status: proposal, awaiting maintainer approval. This document does not implement a move. It does not approve itself. P1K is a working label for this planning slice, not an approved roadmap milestone. The packages plan already uses P1A through P1J. A maintainer may keep P1K, rename it, or reject the sequence. No slice below is approved for implementation.

Selected recommendation for the Approved Apply barrel edge: Option B only. Move synchronizeGeneratedFiles unchanged onto packages/application/src/generated-file/synchronize-generated-files.ts. Retarget every index.ts import in approved-apply-engine.ts onto canonical leaf owners. Preserve the exact existing ApprovedApplyEngineOptions public contract. Do not add an optional dispatcher override or any new public callback. Do not replace the dispatcher with direct transaction calls.

1. Executive summary ​

P1J implementation is merged. packages/application/src/index.ts is still an implementation module: 1,804 effective lines and 1,953 physical lines, measured with measureProductionSource. The P1 gate is 400 effective lines and 700 physical lines, with the Approved Apply re-export component no longer containing index.ts. Neither gate is met. This design does not weaken either gate and does not request an exception.

The file still owns forty-two functions and seven local types or classes. Most of them are persistence or composition, not the public barrel. The re-export hub is a separate problem: index.ts re-exports modules that import it back, so one 27-file re-export component still contains both index.ts and approved-apply-engine.ts.

The safe sequence is seventeen small pull requests. The first is the profile store. Security-adapter execution and bounded project context are decomposed inside their own slices before the large functions move. The Approved Apply edge is a later slice (P1K.14). It keeps the current dispatcher and execution order: gate evaluation, declared-path scope check, baseline capture or validation, then the unchanged dispatcher call with existing transaction stages, rollback, and diagnostics. Option C, an optional public dispatcher injection on ApprovedApplyEngineOptions, is explicitly rejected as unnecessary for SCC removal and as a new transaction-control surface.

After the last slice, the central size forecast is about 381 effective lines and about 465 physical lines. That meets both limits. The upper band can miss 400 effective lines if forwarding wrappers are left on the barrel. Completion is a later measurement, not a claim this document can make. Undo U4, Desktop Undo U5, Neutron topology, and P2 through P6 stay untouched.

2. Verified baseline ​

Verified origin/main and local HEAD before this design:

5efc30a0ae21525312425e69ef82ccd30e138c8a

That commit is the merge of P1J implementation PR #626, refactor(application): extract legacy subagent task records (P1J), merged at 2026-11-14 19:32 Europe/Berlin. No later main commit was present when this design was written. The table below is that snapshot only.

FactEvidence
P1I.3 design, adoption extraction, and type-import retarget are mergedPR #620 e93f6b9efdba11d1dd1cd98ed7072a801595320b, PR #621 527ab7f14fc199bc77d21c7e823b4cc2d5c3d926, PR #622 d6b7d4955f2e58780c1ea2afe134f3217ad3fe86
P1J design is mergedPR #623 8a44e342f4001bbdc7d7196f66200269af0689b7
P1J implementation is mergedPR #626 5efc30a0ae21525312425e69ef82ccd30e138c8a
Legacy task-record leaf existspackages/application/src/workspace/legacy-subagent-task-record.ts
No open pull request plans the remaining barrelOpen pull requests on 2026-11-14 are dependency bumps only
Undo U4 and Desktop Undo U5 have not startedPROJECT_STATE.md and DUTY_WATCH.md; no implementation slice exists
index.ts1,804 effective, 1,953 physical, 148 blank, 1 comment-only
Import-only SCC sizes[3]
Re-export-inclusive SCC sizes[4, 27, 3]

Before this change, PROJECT_STATE.md, the Duty Watch status, docs/README.md, and the packages plan said PR #626 was still open. Those current-state passages now record the merge. Historical Duty Watch entries that described the open review stay as history.

P1K.7 review baseline ​

The P1K.7 Design First review uses a later commit. It does not replace the snapshot above.

Reviewed on 2026-11-24 against origin/maindbea5baf79af002a203e62ba9609c8a67c87662c, the merge of P1K.6 implementation PR #636. P1K.1 through P1K.6 are merged. P1K.7 implementation has not started.

measureProductionSource on packages/application/src/index.ts at that commit: 1,180 effective lines, 1,250 physical lines, 69 blank, 1 comment-only. Import-only SCC sizes stay [3]. Re-export-inclusive SCC sizes stay [4, 27, 3]. Section 3.8 line spans are from this commit. Sections 3.1 through 3.7 and 3.9 through 3.11 keep the P1J inventory spans from the snapshot above.

Section 14 of the packages plan remains the completion gate:

  1. index.ts is a compatibility barrel of at most 400 effective and 700 physical lines, unless the maintainer later accepts a named exception.
  2. No new source dependency cycles.
  3. The Approved Apply re-export component no longer includes index.ts.
  4. Neutron topology stays unchanged.
  5. CLI, daemon, and MCP imports of the package root stay compatible.
  6. pnpm verify passes for each implementation slice.
  7. No structural extraction changes behavior.
  8. Undo U4 and Desktop Undo U5 stay outside P1.

P1A section 5 still describes an older four-file Approved Apply cycle. The measured components in section 16 of this document are the current baseline. Later slices must not grow those components.

Canonical constraints used here, without restating them:

  • docs/architecture/ARCHITECTURE.md and docs/architecture/PACKAGES_STABILIZATION_PLAN.md
  • docs/governance/DESIGN_FIRST_POLICY.md
  • docs/governance/CODE_QUALITY_STANDARDS.md: 250 preferred file lines, 400 hard file lines, 40 preferred function lines, 80 hard function lines
  • docs/governance/DOMAIN_MODELING.md: Agent Memory, Agent Workspace, Synchronization, and Mutation Governance are existing context candidates
  • ADR-0053 for the Approved Apply gate and transactional rollback
  • P1H.1 through P1H.7, P1I.1 through P1I.3, and P1J designs for seams that already exist
  • R4A through R4D for the frozen Neutron topology

Function spans use the same brace slice as tests/legacy-subagent-task-record-p1j-structure.test.ts, then measureProductionSource on each slice. A function at 80 effective lines sits on the hard ceiling. A function above 80 must be split before it is treated as extracted.

3. Current declaration inventory ​

Local declarations are the functions, types, interfaces, and class defined in index.ts. Re-export clauses are compatibility surface. They are not implementation to move. The forty-two functions measure 1,304 effective lines. The other 500 effective lines are imports, re-exports, and the local types below.

index.ts also re-exports protocol types, validators, lifecycle operations, skill and memory leaves, security leaves, and the star exports at the bottom of the file. Those stay public. Implementation slices re-export moved names from their new modules so CLI, daemon, and MCP keep importing @intentloom/application.

3.1 Local types and class ​

NameLinesEffPhysExportedProposed ownerStays in the final barrel as
ProjectTimelineOptions294–30188yesproject-lifecycle/project-root.tsre-export
ProjectTimeline303–30644yessamere-export
ProjectRootError308–31699yessamere-export
TransactionMetadata387–39044privategenerated-file/synchronize-generated-files.tsno; it is an internal parameter
PlanPackUpdateOptions375–38066yesproject-adoption/plan-pack-update.tsre-export
InteractiveWorkspaceState1635–16531919yesworkspace/interactive-workspace-composition.tsre-export
WorkspaceProposalReviewResult1852–185988yesworkspace/workspace-proposal-lifecycle.tsre-export

3.2 Project root, timeline, and generated-file composition ​

NameLinesEffPhysExportSeam requiredFinal barrel
assertCanonicalProjectRoot318–3311414yesnore-export
timelineProject333–3532121yesnore-export
synchronizeGeneratedFiles392–4031212yesnore-export
syncProject405–4161212yesnore-export
adoptProject418–42477yesnore-export

assertCanonicalProjectRoot resolves the root, rejects a missing directory with ProjectRootError("invalid_root"), and rejects a symbolic-link root with ProjectRootError("stale_root"). Runtime dependencies: node:pathresolve, FileSystem, nodeFileSystem. Callers: timelineProject, engineering-quality/specialized-pack-external-apply.ts, and the daemon specialized-pack and engineering-quality handlers through the package root. Filesystem reads are exists and isSymbolicLink on the root only.

timelineProject calls assertCanonicalProjectRoot, then collectGitEvidence and createReleaseTimeline from @intentloom/evidence-git. Daemon bin.ts and neutron/tools/neutron-tool-dispatch.ts call it through the barrel. No project write.

synchronizeGeneratedFiles is the dispatcher. If isDeclaredPathsOnlySyncMode(options.syncMode) it calls synchronizeDeclaredProjectPaths. Otherwise it calls commitOwnedGeneratedFiles and forwards validatedMetadata. Direct callers: syncProject, approved-apply-engine.ts, and harness/harness-benchmark-sample.ts. Indirect callers: adoptProject, existing-project adoption, workspace proposal operations, bounded execution, and Neutron mutation apply, all through the engine or syncProject. This function writes only by calling those two existing transactions. It belongs on a generated-file leaf, then on the barrel only as a re-export.

syncProject passes that dispatcher into executeProjectSync. adoptProject passes syncProject into adoptGeneratedFiles. Both are composition bindings. They must not move into a leaf that imports index.ts. They can move once the dispatcher is a leaf that does not import the barrel. CLI sync-command.ts and adopt-command.ts call them through the package root. Existing-project adoption calls them from index.ts today, which is a cycle edge.

3.3 Planning wrappers ​

NameLinesEffPhysExportSeamFinal barrel
planFeatureleaf feature-intent/plan-feature.ts6666yesnore-export from barrel after P1K.11
planPackUpdate382–4223841yesnore-export; section 27

planFeature builds a fixed draft feature brief and context pack, optionally validates both with the injected ArtifactValidator, and returns pretty JSON. It does not read or write the project. Over the preferred 40-line function budget and under the 80-line hard limit. It is a stub. Extraction must not turn it into planning. Callers: cli/plan-command.ts and cli/update-command.ts. Tests: tests/cli-plan.test.ts. Remeasured on 39ee6e847c3c0053710f9726519b1769b458bd80: the function occupies lines 367–432 and is still 66 effective and 66 physical lines. The extraction contract is section 26.

planPackUpdate rejects a symbolic-link root, calls planProjectAdoption, and returns that plan with packVersion set to targetPackVersion or "1.1.0". The operation map returns every operation unchanged, including both branches. Preserve that no-op map. Callers: cli/update-command.ts. Tests: tests/cli-pack-update.test.ts and tests/cli-update.test.ts.

3.4 Task and session summaries ​

NameLinesEffPhysExportSeamFinal barrel
recordTaskSummary550–5883639yesnore-export
listTaskSummaries590–6364347yesnore-export
getTaskSummary638–6521515yesnore-export
recordSessionSummary654–6842931yesnore-export
listSessionSummaries686–7182933yesnore-export

One Agent Memory persistence style and two record types. Task summaries drop affectedPaths entries for which secretLikePath is true before validation. Session summaries do not run that filter and do not redact summaryNotes. Listing scans fs.list(root), keeps .aif/memory/tasks/*.json or .aif/memory/sessions/*.json, ignores unreadable and invalid JSON, and sorts createdAt descending. Task listing also filters trustClass and retentionState when those options are set. Bytes are JSON.stringify(value, null, 2) plus a trailing newline. Paths go through inside.

Runtime dependencies: FileSystem, nodeFileSystem, inside, secretLikePath for tasks only, dirname, relative, protocol validators. No import of index.ts is required. Neutron neutron-context-state-collectors.ts calls getTaskSummary through the barrel. Leave that import on the barrel. CLI summary-command.ts covers task summaries. Tests: tests/controlled-learning-l1.test.ts and tests/memory-security-m4.test.ts.

listTaskSummaries is 43 effective lines, three over the preferred function size and under the hard limit. It is one scan, filter, and sort. Splitting it would hide that sequence. Move it intact.

These are not one store with one schema. They are one cohesive boundary with two directories and two validators. One module under 250 effective lines can own both. A second module is not required.

3.5 Task checkpoints and control ​

NameLinesEffPhysExportSeamFinal barrel
createTaskCheckpoint748–7823335yesnore-export
getTaskCheckpoint784–7971414yesnore-export
listTaskCheckpoints799–8312933yesnore-export
pauseTask833–8531921yesnore-export
cancelTask855–8751921yesnore-export
redirectTask877–9052629yesnore-export
resumeTask907–9382832yesnore-export
deleteTaskCheckpoint940–9491010yesnore-export

This store is .aif/memory/checkpoints/{id}.json. It is not a Neutron task graph, not a mutation checkpoint, and not Undo. Create sets state to active, uses chk-${taskId}-${Date.now()} as the id, and hashes `${id}:${taskId}:${options.root}:${Date.now()}`. Those are separate clock reads. Preserve both. Pause, cancel, and redirect load the checkpoint, set paused, cancelled, or redirected, and write it. They do not reject a prior state. Redirect appends `Redirected: ${newIntent}` to unresolvedWork and plan-invalidated-${Date.now()} to invalidatedPlans. The reason option is accepted and unused. Resume rejects only cancelled, with `Cannot resume cancelled task checkpoint: ${checkpointId}`, writes resumed, and returns a TaskResumeResult whose invalidatedCount is the count from before the write. verifiedRoot is the caller root string. Delete returns false when the file is absent. List sorts updatedAt descending and can filter taskId. Corrupt files are ignored by get and list.

Callers: cli/checkpoint-command.ts, and neutron-context-state-collectors.ts for listTaskCheckpoints through the barrel. Tests: tests/controlled-learning-l6.test.ts and tests/cli-checkpoint.test.ts. No new seam. The leaf imports host-file-system.ts, project-path.ts, and protocol validators.

3.6 Semantic ranking, profiles, and delegation ​

NameLinesEffPhysExportSeamFinal barrel
getSemanticRankingConfig951–9732323yesnore-export
updateSemanticRankingConfig975–9881414yesnore-export
rankProceduralMemory990–10768087yesnore-export
createProfile1078–10941717yesnore-export
getProfile1096–11091414yesnore-export
listProfiles1111–11412731yesnore-export
delegateTaskRole1143–12166574yesnore-export

These are two bounded contexts inside Agent Memory.

Semantic ranking owns .aif/memory/semantic_config.json and a read-only score over skill proposals and evaluations. A missing or invalid config returns enabled: false and provider: "local-tf-idf". Ranking still scores when enabled is false. It records that flag on the result and does not return early. Proposal terms add 0.5, capped at 1. Evaluation terms add 0.4, capped at 1. Sort is score descending. maxResults defaults to 10. rankingLatencyMs is Date.now() after scoring minus Date.now() before. The ranker calls listSkillProposals and listSkillEvaluations, which already live on skill leaves imported by the barrel. A ranking module can import those leaves directly. rankProceduralMemory is 80 effective lines, the hard ceiling. The extraction splits proposal scoring, evaluation scoring, and orchestration. It does not move the 80-line function intact.

Profiles own .aif/memory/profiles/{name}.json. List sorts name ascending and ignores invalid files. Delegation reads one profile, rejects a missing profile or a role outside activeRoles, clamps capabilities, and writes .aif/memory/delegations/{id}.json. Read-only roles are context-scout and reviewer. Network and budget clamps are profile ceilings. Delegation is not ranking and is not Approved Apply. It depends on getProfile, so the profile leaf comes first. delegateTaskRole is 65 effective lines. The slice splits the pure clamp from the write so policy and storage can change separately. Results stay the same.

Callers: cli/rank-command.ts, cli/profile-command.ts, cli/delegate-command.ts, and getProfile from Neutron state collectors through the barrel. Tests: tests/controlled-learning-l7.test.ts, tests/controlled-learning-l8.test.ts, tests/cli-rank.test.ts.

3.7 Bounded project context ​

NameLinesEffPhysExportSeamFinal barrel
getBoundedProjectContext1218–1333101116yesnore-export

This exceeds the hard function limit. Extraction starts by splitting it:

  1. Path exclusion for the current secret and skip patterns.
  2. Classification of docs/specs/, docs/decisions/, other docs/, PROJECT_STATE.md, DUTY_WATCH.md, and .aif/memory/ into the current source type and trust class.
  3. Candidate collection in fs.list order, including the query test, the 150-character summary, and Math.ceil(content.length / 4) tokens.
  4. Budget selection. The first item is kept even when it exceeds maxTokens. Later items stop when the next token total would exceed the budget or maxItems is reached.
  5. A thin function that validates ContextRetrievalResult.

Defaults stay maxTokens 4000 and maxItems 20. Omitted request input becomes { schemaVersion: "1" }. Unreadable files are skipped and are not counted in excludedPathsCount. Exclusion is by path pattern, not by rewriting file bytes. The patterns are not secretLikePath. Do not merge them in this program.

The only in-repo production caller is neutron/context/neutron-context-collectors.ts, which imports the barrel. That Neutron file stays. CLI context-command.ts uses the package root. Tests: tests/memory-security-m1.test.ts. No new dependency seam. The leaf must not import index.ts or src/neutron/.

3.8 Security adapter execution ​

NameLinesEffPhysExportSeamFinal barrel
correlateSecurityFindings688–7122525yesnore-export
runLocalSecurityAdapters714–912188199yesnore-export

Line spans below are the P1K.7 review baseline in section 2 (dbea5baf79af002a203e62ba9609c8a67c87662c). The six-file decomposition in section 22 is unchanged. Section 22 is the Design First acceptance record for P1K.7 implementation. Section 23 is the diagram index.

Verified current behavior (production packages/application/src/index.ts, not the proposed layout):

Correlation keys ruleId plus the first evidence path, or "unknown". Equal keys keep the earlier finding unless the new severity rank is strictly higher; equal severity keeps the earlier finding. Severity rank is critical 5, high 4, medium 3, low 2, info 1. The result is sorted lexicographically by id. Correlation runs once per category on that category's raw findings only.

The runner is over both the preferred and hard function limits. Moving it unchanged into security/ would shrink index.ts and leave an illegal function. The slice decomposes it first.

Category ordering: default order is dependency, secret, config, source, extension, mcp, hook, agentic. When options.categories?.length is truthy, that array replaces the default order exactly (preserving duplicates; no deduplication). A zero-length categories array is falsy for .length, so all eight defaults run.

Finding IDs: findingCounter starts at 1 once per runner invocation and is shared across all categories. Prefixes stay sec-dep-, sec-secret-, sec-cfg-, and sec-mcp- for findings those scanners emit. Each category, including source, extension, hook, and agentic, still produces exactly one SecurityAdapterResult with zero findings today. P1K.7 does not implement scanners for those four categories.

Per-category scanner behavior to preserve (verified):

  • Dependency: reads inside(root, "package.json") when present; merges dependencies and devDependencies; flags string versions "*", "latest", or any value starting with >= as dep/unpinned-wildcard at medium severity. Caret (^) and other ranges are not flagged. fs.exists is outside the try and propagates. fs.read, JSON.parse, and validateSecurityFinding share one try around the whole manifest. A caught failure keeps findings already pushed, keeps every findingCounter increment already evaluated (the id expression runs before validation, so a validation throw consumes an id that is not stored), stops the rest of that manifest, and does not throw. Correlation and persistence still run for the partial list. Later categories still run.
  • Secret: fs.list(root); skips relative paths containing node_modules, starting with .git, or ending in .png or .jpg; flags paths where secretLikePath(rel) is true (.env segment, .env.* segment, or segment ending in .key, .pem, .p12, .pfx). No file bytes are read. Evidence path is always "[REDACTED]" when the finding is emitted. Description still interpolates the relative path (existing behavior; possible future hardening, not changed in P1K.7). validateSecurityFinding is outside any try. A validation throw aborts the runner before this category is correlated or persisted. Findings already pushed for this category are not written. Earlier categories stay on disk. The shared counter is not rewound: the throwing call has already incremented it. fs.list failure propagates before this category is correlated or persisted.
  • Config: fs.list(root); when some listed path contains .aif/ and none contains .aif/policy, emits config/missing-security-policy at low severity with evidence path .aif. Validation is outside any try and propagates the same way as the secret scanner. Listing failure propagates before any config finding is built.
  • MCP: fs.list(root) is outside any try and propagates. For each normalized path that includes .aif/mcp/ and ends in .json, one try covers fs.read, JSON.parse, and validateSecurityFinding. A caught failure skips the rest of that file only. Findings already pushed from earlier files stay in rawFindings. A validation throw consumes the next id and does not push that finding. Later matching files still run, and the category still correlates and persists the partial list. When allowGenericShell === true, the finding is mcp/unrestricted-shell-permission at critical severity with the relative config path as evidence.

Persistence: after per-category correlation, each finding is written to securityFindingPath(root, id) → .aif/security/findings/{id}.json via JSON.stringify(finding, null, 2) plus trailing newline. Parent directory is created with fs.mkdir only when absent. Writes are sequential. There is no transaction, rollback, or retry. Persistence, directory checks, and mkdir are outside every scanner try. fs.exists on the parent, fs.mkdir, and fs.write propagate. A failure there leaves findings already written in this run on disk, including earlier findings in the same category, and skips the rest of the runner. validateSecurityAdapterMetadata and validateSecurityAdapterResult run after that category's writes. If either throws, those finding files are already stored and later categories do not run.

Adapter metadata: each result uses validateSecurityAdapterMetadata with readOnly: true, networkAccess: false, version: "1.0.0", and name built-in:{category}-adapter. One executedAt ISO timestamp is captured before the category loop and reused for every finding timestamp and every adapter result. Metadata describes adapter capability; the runner still persists finding records regardless.

Proposed files (structural only; behavior identical), under packages/application/src/security/:

ModuleOwnership
security-adapter-correlation.tsduplicate-key handling, severity precedence, sort by id
security-adapter-dependency.tsdependency scanner logic
security-adapter-secret.tssecret scanner logic
security-adapter-config.tsconfig scanner logic
security-adapter-mcp.tsMCP scanner logic
security-adapter-run.tscategory order, shared counter, correlation invocation, persistence, result assembly

No new security scanners or public APIs. No file or function may exceed hard budgets (250 / 400 file, 40 / 80 function). The runner imports securityFindingPath from security-finding-store.ts. No extracted leaf imports index.ts. Callers stay on the package root: packages/cli/src/security-operations-command.ts. Tests: tests/memory-security-s2.test.ts, tests/security-finding-store-p1h4a.test.ts, and CLI security scan coverage. Known filesystem weaknesses in section 12 and section 22 are not patched in this slice.

3.9 Interactive workspace conversations ​

NameLinesEffPhysExportSeamFinal barrel
getInteractiveWorkspaceState1655–16762222yesexistsre-export
workspaceConversationPath1678–168366privatenono
startWorkspaceConversation1685–17122628yesnore-export
getWorkspaceConversation1714–17261313yesnore-export
redactWorkspaceSecrets1728–17421515privatenono
appendWorkspaceMessage1744–17783135yesnore-export
listWorkspaceConversations1780–18092930yesnore-export
syncLocalWorkspaceState1927–19371111yesexistsre-export

P1H.7 already injected ports into assembleInteractiveWorkspaceState and assembleLocalWorkspaceSyncState. getInteractiveWorkspaceState passes inspectProject, doctorProject, diffProject, and timelineProject. syncLocalWorkspaceState passes inspectProject, doctorProject, listWorkspaceConversations, and listNeutronSubagentTasks. The read model calls getSecurityAuditReport itself and does not import the barrel.

Conversation records live at .aif/workspace/conversations/{id}.json. Ids and message ids use Date.now() and Math.random().toString(36).slice(2, 8). Append redacts, then validates, then writes. Redaction patterns are the current GitHub token shapes, sk- tokens, assignment-style key or password text, and PEM private keys. List sorts by updatedAt descending using Date parsing. Invalid records are omitted. Get returns null on a missing or invalid file.

Extracting the conversation store lets syncLocalWorkspaceState move later into workspace/local-workspace-sync.ts, which imports the conversation leaf, the lifecycle leaves, and the legacy task-record leaf. That module does not import index.ts. The same is true for interactive state after timelineProject has a leaf. Neither move is part of the conversation slice. Callers: cli/workspace-command.ts, cli/ui-command.ts, and cli/neutron-command.ts. Tests: tests/workspace-agent.test.ts, tests/cli-workspace.test.ts, and the P1H.7 read-model tests.

3.10 Workspace proposal lifecycle ​

NameLinesEffPhysExportSeamFinal barrel
workspaceProposalPath1811–181333privateyesno
promoteWorkspaceConversationToProposal1815–18503336yesyesre-export
reviewWorkspaceProposal1861–19003840yesyesre-export
applyWorkspaceProposal1902–19252324yesyesre-export

These operations are not the conversation store. Promote checks that the conversation exists, calls adoptProject with profile: "generic", adapters: ["codex"], and dryRun: true, and writes that proposal under .aif/proposals/{id}.json. It does not write the conversation body. Review reads that file when present and otherwise calls the same dry-run adoptProject. It then calls evaluateProposalAgainstSandbox and sets readyToApply from sandboxEval.allowed. Apply does not read readyToApply, does not read the proposal file, and does not call executeApprovedApplyPlan. It rejects a missing or blank approvedBy with "human approval required (--approved-by USER)", then calls adoptProject with dryRun defaulting to false.

Creating a proposal is not authorization. A non-empty approvedBy string is not the Approved Apply gate. The extraction preserves that separation. It does not "correct" apply by sending it through ADR-0053.

The seam is required because a leaf that imports adoptProject from index.ts would cycle once the barrel re-exports the leaf. The slice passes adoptProject in as a port, matching P1H.7 and P1I.2. Public signatures on the barrel stay. When adoptProject later lives on a binding module that does not import the barrel, the port can become a direct import and the barrel wrappers become re-exports. Callers: cli/workspace-command.ts. Tests: tests/workspace-apply.test.ts and tests/cli-workspace.test.ts.

3.11 What remains a package-root concern ​

The final index.ts is a compatibility barrel. It re-exports the names above and the names already re-exported today. It does not own filesystem logic.

These bindings are package-root composition until their dependencies are leaves, and then they move to binding modules that the barrel re-exports:

  • synchronizeGeneratedFiles, after it is the generated-file leaf
  • syncProject and adoptProject
  • getInteractiveWorkspaceState
  • syncLocalWorkspaceState

They must not be pushed into a leaf that needs to import index.ts to call them. That is the cycle this program is removing. Section 28 is the Design First gate for the two workspace bindings. Their callees are already leaves, and the proposed leaves do not import index.ts.

4. Current dependency graph ​

mermaid
flowchart TB
  subgraph barrel ["index.ts local surface"]
    dispatcher["synchronizeGeneratedFiles"]
    sync["syncProject"]
    adopt["adoptProject"]
    rootFn["assertCanonicalProjectRoot"]
    timeline["timelineProject"]
    summaries["task and session summaries"]
    checkpoints["task checkpoints"]
    ranking["semantic ranking"]
    profiles["profiles and delegation"]
    context["getBoundedProjectContext"]
    adapters["security adapter runner"]
    conversations["workspace conversations"]
    proposals["workspace proposals"]
    interactive["getInteractiveWorkspaceState"]
    localSync["syncLocalWorkspaceState"]
    planFeature["planFeature"]
    packUpdate["planPackUpdate"]
  end

  cli["CLI daemon and MCP package root"]
  engine["approved-apply-engine.ts"]
  harness["harness-benchmark-sample.ts"]
  quality["specialized-pack-external-apply.ts"]
  adoption["existing-project adoption modules"]
  declared["synchronizeDeclaredProjectPaths"]
  commit["commitOwnedGeneratedFiles"]
  readModel["interactive-workspace-read-model.ts"]
  neutronCtx["neutron context collectors"]
  skills["skill proposal and evaluation leaves"]
  sandbox["evaluateProposalAgainstSandbox"]

  cli --> barrel
  engine -->|"value and type import"| dispatcher
  engine -->|"nodeFileSystem and types"| barrel
  harness -->|"value import"| dispatcher
  quality -->|"value import"| rootFn
  adoption -->|"adopt sync inspect doctor diff"| barrel
  dispatcher --> declared
  dispatcher --> commit
  sync --> dispatcher
  adopt --> sync
  proposals --> adopt
  proposals --> sandbox
  interactive --> timeline
  interactive --> readModel
  localSync --> conversations
  localSync --> readModel
  ranking --> skills
  neutronCtx --> context
  neutronCtx --> profiles
  neutronCtx --> summaries
  neutronCtx --> checkpoints

Source: current-barrel-dependencies.mmd.

Runtime edges from local functions to existing leaves are one-way: project-path.ts, host-file-system.ts, lifecycle modules, generated-file-sync-declared.ts, generated-file/generated-file-transaction.ts, skill leaves, security/security-finding-store.ts, security/sandbox-proposal-evaluation.ts, and workspace/interactive-workspace-read-model.ts. None of those leaves import index.ts except the four back-edges in section 8.

Neutron imports of getBoundedProjectContext, getProfile, getTaskSummary, listTaskCheckpoints, timelineProject, and FileSystem are one-way. index.ts does not import src/neutron/. Leaving those imports aimed at the barrel does not create a cycle and does not require a Neutron edit.

5. Bounded-context ownership ​

mermaid
flowchart LR
  subgraph memory ["Agent Memory"]
    summaryStore["task and session summaries"]
    checkpointStore["task checkpoints"]
    rankStore["semantic ranking"]
    profileStore["profiles"]
    delegation["role delegation"]
  end

  subgraph contextCtx ["Context retrieval"]
    bounded["bounded project context"]
  end

  subgraph security ["Security findings"]
    adapterRun["local adapter execution"]
    correlation["finding correlation"]
  end

  subgraph workspace ["Agent Workspace"]
    conversationStore["conversation store"]
    proposalLife["proposal lifecycle"]
    composition["interactive and local sync bindings"]
  end

  subgraph project ["Project lifecycle and adoption"]
    root["canonical project root and timeline"]
    syncBind["sync and adopt bindings"]
    dispatcher["generated-file dispatcher"]
    featurePlan["feature-brief stub"]
    packPlan["pack-update plan"]
  end

  subgraph apply ["Mutation governance"]
    gate["Approved Apply gate and engine"]
  end

  delegation --> profileStore
  proposalLife --> syncBind
  composition --> conversationStore
  composition --> root
  syncBind --> dispatcher
  gate --> dispatcher

Source: bounded-context-ownership.mmd.

Ownership follows invariants, not filename prefixes.

  • Task summaries, session summaries, checkpoints, ranking config, profiles, and delegations share .aif/memory/ and the validate-then-write pattern. Ranking and delegation still differ: ranking reads skill records and does not authorize a write; delegation clamps a role and writes a grant record.
  • Bounded context is a read model over docs, decisions, duty files, and memory paths. It is not the summary store and not the Neutron context assembler. The assembler may call it.
  • Security adapter execution writes finding records. It is not the Approved Apply gate and not sandbox evaluation. Sandbox evaluation is already a leaf used by proposal review.
  • Conversations and proposals share the workspace CLI and must not share a module. Proposals call adoption. Conversations do not.
  • synchronizeGeneratedFiles is Synchronization. The Approved Apply engine is Mutation Governance. The engine may call the dispatcher. The dispatcher does not evaluate approval.

No new bounded context is declared. The directories memory/, security/, workspace/, project-lifecycle/, project-adoption/, feature-intent/, and generated-file/ already match these owners. This plan adds files there. It does not add a package, a barrel under those directories, or a package export-map key.

6. Candidate extraction families ​

Section 3 is the family audit. The extraction consequences are:

FamilyMove intactDecomposition firstNew seam
Profilesyesnono
Role delegationnosplit clamp from persistenceno, after profiles exist
Task and session summariesyesno; keep the 43-line list functionno
Task checkpointsyesnono
Semantic rankingnosplit the 80-line rankerno; import skill leaves directly
Bounded project contextnosplit the 101-line functionno
Security adaptersnosplit the 188-line runnerno
Conversationsyesnono
Proposal lifecyclebehavior yes, module nono function is over 80inject adoptProject
Root and timelineyesnono
planFeature and pack updateyesnono
Interactive and local syncyesnoseams already exist
Dispatcheryesno; do not inline the transactionsno; engine calls the leaf directly

Families that are not extracted: protocol re-exports, validator re-exports, lifecycle leaves already moved in P1I.2, adoption leaves already moved in P1I.3, skill and memory leaves from P1H, the legacy subagent store from P1J, and the Neutron mutation trio.

7. Architecture alternatives ​

Three shapes were compared for the whole barrel.

Keep the remaining functions on index.ts and document an exception. This misses the 400-line gate unless the maintainer names every leftover declaration. The measured remainder after deleting only the easy families would still include the 188-line runner, the 101-line context function, and the Approved Apply hub. An exception written into this design would not be approval. This shape is rejected as the plan.

One implementation pull request that moves every declaration. This can describe the end state and cannot review behavior preservation. The runner, the context function, proposal apply, and the dispatcher would change modules together. This shape is rejected.

Seventeen dependency-ordered structural slices. Each slice has one owner, existing tests, and a predicted SCC effect. Oversized functions are split inside the slice that moves them, with characterization tests, and without a product change. This is the recommended shape. Slices do not start until this design is approved. A slice that would change a public signature, an error string, or ADR-0053 behavior stops and comes back for design review.

The target module layout, after every slice:

mermaid
flowchart TB
  barrel["index.ts re-export barrel"]

  barrel --> profiles["memory/profile-store.ts"]
  barrel --> roles["memory/role-delegation.ts"]
  barrel --> summaries["memory/task-session-summary-store.ts"]
  barrel --> checkpoints["memory/task-checkpoint-store.ts"]
  barrel --> ranking["memory/semantic-ranking.ts"]
  barrel --> bounded["memory/bounded-project-context.ts"]
  barrel --> adapters["security/security-adapter-run.ts"]
  barrel --> conversations["workspace/workspace-conversation-store.ts"]
  barrel --> proposals["workspace/workspace-proposal-lifecycle.ts"]
  barrel --> interactive["workspace/interactive-workspace-composition.ts"]
  barrel --> localSync["workspace/local-workspace-sync.ts"]
  barrel --> root["project-lifecycle/project-root.ts"]
  barrel --> feature["feature-intent/plan-feature.ts"]
  barrel --> pack["project-adoption/plan-pack-update.ts"]
  barrel --> syncBind["project-lifecycle/project-sync-binding.ts"]
  barrel --> adoptBind["project-adoption/generated-file-adoption-binding.ts"]
  barrel --> dispatcher["generated-file/synchronize-generated-files.ts"]

  adapters --> correlation["security/security-adapter-correlation.ts"]
  adapters --> dependency["security/security-adapter-dependency.ts"]
  adapters --> secret["security/security-adapter-secret.ts"]
  adapters --> config["security/security-adapter-config.ts"]
  adapters --> mcp["security/security-adapter-mcp.ts"]
  ranking --> skills["skills proposal and evaluation leaves"]
  proposals --> adoptBind
  syncBind --> dispatcher
  adoptBind --> syncBind
  interactive --> root
  localSync --> conversations

Source: future-module-layout.mmd. This is the end state. P1K.9 may inject adoptProject before generated-file-adoption-binding.ts exists. P1K.16 removes that injection once the binding module is the owner.

8. Approved Apply SCC analysis ​

Measured with applicationCycles from tests/application-source-cycles.ts on 5efc30a0ae21525312425e69ef82ccd30e138c8a. The detector treats import, import type, and export ... from as edges. A type-only import from index.ts is enough to keep a file in the component.

8.1 Current membership ​

Import-only, size 3:

  • neutron/mutation/apply/neutron-mutation-apply-durable-record.ts
  • neutron/mutation/apply/neutron-mutation-apply-store.ts
  • neutron/mutation/verification/neutron-mutation-verification-retry-eligibility.ts

Re-export-inclusive, size 4:

  • apply-extension-update.ts
  • discover-and-apply-extension-update.ts
  • extension-update-files.ts
  • propose-and-apply-extension-adoption.ts

Re-export-inclusive, size 27:

  • approved-apply-engine.ts
  • bounded-execution-apply.ts
  • bounded-execution-w11.ts
  • bounded-execution-workspace-cli.ts
  • bounded-execution-workspace.ts
  • engineering-quality-entry.ts
  • engineering-quality/cli-specialized-packs-external.ts
  • engineering-quality/index.ts
  • engineering-quality/specialized-pack-external-apply.ts
  • engineering-quality/specialized-pack-external-viewmodel.ts
  • existing-project-adoption-apply-gates.ts
  • existing-project-adoption-apply-health.ts
  • existing-project-adoption-apply.ts
  • existing-project-adoption-approval.ts
  • existing-project-adoption-decisions.ts
  • existing-project-adoption-plan.ts
  • existing-project-adoption-prepared-plan-revalidate.ts
  • existing-project-adoption-prepared-plan.ts
  • existing-project-w9.ts
  • existing-project-workspace-cli.ts
  • existing-project-workspace.ts
  • foundation-flow.ts
  • harness/harness-benchmark-sample.ts
  • harness/harness-benchmark.ts
  • harness/harness.ts
  • inception-flow.ts
  • index.ts

Re-export-inclusive, size 3: the same Neutron mutation trio. No other component exists. approved-apply-baseline.ts and generated-file-sync-declared.ts are outside every component.

mermaid
flowchart LR
  index["index.ts"]
  engine["approved-apply-engine.ts"]
  inception["inception-flow.ts"]
  foundation["foundation-flow.ts"]
  w11["bounded-execution-w11.ts"]
  applyBe["bounded-execution-apply.ts"]
  w9["existing-project-w9.ts"]
  adoption["existing-project adoption modules"]
  harness["harness.ts and benchmark sample"]
  qualityEntry["engineering-quality-entry.ts"]
  qualityApply["specialized-pack-external-apply.ts"]

  index -->|"export star"| engine
  index -->|"export star"| inception
  index -->|"export star"| harness
  index -->|"export star"| qualityEntry
  inception -->|"export star"| foundation
  foundation -->|"export star"| w11
  foundation -->|"export star"| w9
  w11 -->|"export star"| applyBe
  applyBe -->|"executeApprovedApplyPlan"| engine
  w9 -->|"export star"| adoption
  engine -->|"synchronizeGeneratedFiles nodeFileSystem types"| index
  harness -->|"synchronizeGeneratedFiles"| index
  adoption -->|"adopt sync inspect doctor diff types"| index
  qualityEntry -->|"export star"| qualityApply
  qualityApply -->|"assertCanonicalProjectRoot"| index

Source: approved-apply-cycle.mmd.

index.ts is the hub. It reaches the engine, harness, quality, and adoption families by export *. Those families reach index.ts again through four back-edges:

  1. approved-apply-engine.ts value-imports synchronizeGeneratedFiles and nodeFileSystem, and type-imports FileSystem and TransactionOptions.
  2. harness/harness-benchmark-sample.ts value-imports synchronizeGeneratedFiles. The file comment already records the cycle. The call is inside a function, not at module evaluation.
  3. engineering-quality/specialized-pack-external-apply.ts value-imports assertCanonicalProjectRoot and ProjectRootError.
  4. Existing-project modules value-import adoptProject, syncProject, inspectProject, doctorProject, diffProject, or planProjectAdoption, and type-import ProjectMapping, InitOptions, or TransactionOptions.

bounded-execution-apply.ts value-imports executeApprovedApplyPlan from the engine, not from the barrel. It stays in the component because the engine imports the barrel and the barrel re-exports the foundation flow that re-exports bounded execution.

P1I.3b removed the baseline and declared-sync imports of the barrel and deliberately left the engine import. This design closes that edge without editing Neutron.

8.2 How index.ts leaves the Approved Apply component ​

The engine leaves the component when it has no import from index.ts at all, including types, and no other path from the engine back to the barrel. The gate, baseline, declared-path sync, owned-file transaction, and host filesystem modules do not import the barrel today. A dispatcher leaf that imports only those modules does not recreate the edge.

Detaching the engine also drops bounded execution out of the component, because its only path back to the barrel is engine to barrel. It does not drop the barrel out of the remaining component. Harness, quality, and adoption still import the barrel. The literal gate, "the Approved Apply component no longer includes index.ts", is met when the engine is gone. The architectural end state, a barrel that implementation modules do not import, needs the other three back-edges removed as well. This plan does both. It does not call P1 complete at the engine-only step.

The Neutron trio is not on these paths. No slice rewrites it.

8.3 Options ​

mermaid
flowchart TB
  subgraph optionA ["Option A keep dispatcher on the barrel"]
    aEngine["engine imports index.ts"]
    aBarrel["synchronizeGeneratedFiles stays in index.ts"]
    aEngine --> aBarrel
  end

  subgraph optionB ["Option B leaf dispatcher recommended"]
    bEngine["engine imports the leaf"]
    bLeaf["generated-file/synchronize-generated-files.ts"]
    bDeclared["declared-path sync"]
    bCommit["owned generated-file commit"]
    bEngine --> bLeaf
    bLeaf --> bDeclared
    bLeaf --> bCommit
  end

  subgraph optionC ["Option C optional injection rejected"]
    cRejected["rejected for P1K"]
    cOverride["would add options.synchronizeGeneratedFiles"]
    cRisk["could report applied true without a real write"]
    cRejected --> cOverride
    cOverride --> cRisk
  end

  subgraph optionD ["Option D composition module viable not necessary"]
    dIndex["index re-exports composition"]
    dComp["approved-apply-composition.ts"]
    dEngine["engine without an index import"]
    dLeaf["leaf dispatcher"]
    dIndex --> dComp
    dComp --> dEngine
    dComp --> dLeaf
  end

Source: approved-apply-alternatives.mmd.

Option A. Keep the dispatcher on the barrel. Edges stay engine to index.ts for the function, nodeFileSystem, FileSystem, and TransactionOptions. The 27-file component continues to contain both files. Public signatures stay. Authorization, before-write failure, stages, diagnostics, and rollback stay because nothing moves. Tests stay as they are. Migration cost is zero. The P1 gate cannot be met. Option A is the honest description of today's code, not a completion plan.

Option B. Leaf-owned dispatcher. New module generated-file/synchronize-generated-files.ts contains the current function body and the private TransactionMetadata type. Runtime edges: isDeclaredPathsOnlySyncMode, synchronizeDeclaredProjectPaths, commitOwnedGeneratedFiles. Type edges: GeneratedFile, FileSystem, TransactionOptions, TransactionResult, Plan is not required if the metadata type moves with the function. No edge to index.ts. The engine retargets synchronizeGeneratedFiles to the leaf, nodeFileSystem and FileSystem to host-file-system.ts, and TransactionOptions to generated-file/transaction-contracts.ts. The barrel re-exports the dispatcher, a one-way edge. SCC: the engine and bounded execution leave the index component. Harness leaves only if its import is retargeted in the same slice. Quality and adoption stay until their slices. Public executeApprovedApplyPlan(request, files, options) stays. Authorization stays in evaluateApprovedApplyPlan, still before the dispatcher. Failure diagnostics and rollback stay because the same function is called with the same arguments. Tests: tests/approved-apply-engine.test.ts, declared-path and generated-file transaction tests, and the harness benchmark test. Migration cost is one small module and import edits. Risk: a retarget that still imports a type from the barrel leaves the SCC edge in place. The slice is done only when the engine source has no index.js specifier.

Option C. Optional dispatcher injection on the engine. This would add ApprovedApplyEngineOptions.synchronizeGeneratedFiles, allowing a caller to substitute the synchronization function. A substitute could return status: "success" without executing the real transaction, yielding applied: true without a successful write. That is a new public transaction-control surface. SCC removal does not require it: Option B alone removes the engine's index.ts import and breaks the Approved Apply edge from the 27-file component. Existing injected FileSystem, failAt, and rollbackFailPaths are sufficient for current transaction test scenarios. Option C is explicitly rejected for P1K.14. No new dependency-injection framework is introduced.

Option D. Composition module. approved-apply-composition.ts would import the engine and the leaf and export the wired function. The barrel would re-export the composition module instead of owning the wiring. This matches syncProject calling executeProjectSync, and it avoids an options field. It also moves the public function's home. Every current importer of executeApprovedApplyPlan from the engine file, including bounded-execution-apply.ts, would have to follow the move or keep a re-export from the engine file. That re-export is safe only if the engine file does not import the composition module. SCC impact can match Option B. Authorization and rollback can match today. Migration cost is higher than Option B because the public function changes modules even when the signature does not. The extra module does not remove a cycle that Option B already removes. Option D is a viable alternative but not necessary for P1 completion.

Recommendation: Option B only. The dispatcher stays one function with the current branch inside the extracted leaf. The engine stops importing the barrel and calls the real leaf dispatcher directly. Public function signatures stay unchanged. The Approved Apply authorization boundary, transaction stages, rollback, and diagnostics stay unchanged. No new public option is added. Option A is rejected for P1 completion because it preserves the barrel dependency. Option C is rejected as unnecessary for SCC removal and as an unsafe injection point. Option D remains acceptable but optional. No option may inline commitOwnedGeneratedFiles or synchronizeDeclaredProjectPaths inside the engine unless a later design proves the diagnostics, stages, and rollback match the dispatcher exactly. This design does not make that proof and does not recommend the inline.

Harness retarget belongs in the same slice as the leaf, because it is the second value importer of the same function. It is not an Apply behavior change.

mermaid
flowchart TB
  design["this design approved"]
  s1["P1K.1 profile store"]
  s2["P1K.2 role delegation"]
  s3["P1K.3 summaries"]
  s4["P1K.4 checkpoints"]
  s5["P1K.5 semantic ranking"]
  s6["P1K.6 bounded context"]
  s7["P1K.7 security adapters"]
  s8["P1K.8 conversations"]
  s9["P1K.9 proposal lifecycle"]
  s10["P1K.10 project root and timeline"]
  s11["P1K.11 planFeature"]
  s12["P1K.12 planPackUpdate"]
  s13["P1K.13 workspace composition"]
  s14["P1K.14 dispatcher and Apply retarget"]
  s15["P1K.15 quality root retarget"]
  s16["P1K.16 adoption retarget"]
  s17["P1K.17 export-from barrel"]

  design --> s1
  s1 --> s2
  design --> s3
  design --> s4
  s3 --> s5
  design --> s6
  design --> s7
  design --> s8
  s8 --> s9
  design --> s10
  design --> s11
  design --> s12
  s8 --> s13
  s10 --> s13
  design --> s14
  s10 --> s15
  s14 --> s16
  s9 --> s16
  s12 --> s16
  s15 --> s17
  s16 --> s17
  s13 --> s17

Source: phased-implementation.mmd.

Prioritization uses cohesion, security and transaction sensitivity, regression risk, independent tests, current coverage, effective lines removed, file and function budgets, SCC impact, dependence on earlier slices, and implementation complexity. Low sensitivity and no seam outrank larger line removal. That is why the security runner and the Apply dispatcher are not first.

The smallest safe next implementation slice is P1K.1, the profile store. It is one directory, three functions, 58 effective lines, existing CLI and L8 tests, no redaction policy, no transaction, no index.ts import from the leaf, and no SCC change.

Working ids are proposals. They are not permission to open implementation pull requests.

10. Per-slice implementation boundaries ​

Every slice: no behavior change, no Neutron file edit, no package export-map change, no quality-exceptions.json change, no new directory barrel, public names re-exported from index.ts, and pnpm verify before the pull request is opened.

Design First gates for implementation ​

This document is an architectural roadmap and a proposed implementation sequence. It does not automatically authorize unlimited architectural changes across all seventeen future pull requests.

  • Mechanical extractions fully described in this design may proceed after explicit maintainer approval, one implementation pull request at a time. Each slice keeps the boundaries in this section.
  • Significant deviations from the described move, module owner, public surface, or behavior require renewed design review before implementation.
  • Security-sensitive, transaction-sensitive, public-contract, and cross-boundary slices require explicit confirmation that this approved design covers all relevant interfaces, errors, security rules, and testing requirements. When coverage is insufficient, open a focused Design First pull request before implementation. This correction does not open those follow-on design pull requests.

Pay particular attention before implementation:

  • P1K.7 — security adapter decomposition (section 22 Design First gate; documentation pull request required before implementation).
  • P1K.9 — workspace proposal lifecycle and adoption binding.
  • P1K.14 — Approved Apply dispatcher extraction (Option B only; no public dispatcher override).
  • P1K.16 — adoption bindings and final SCC hub removal.

P1K.7 and P1K.14 also require the maintainer to accept the decomposition and the Option B recommendation in sections 6 and 8.

P1K.1 Profile store ​

  • Responsibility: profile create, get, and list.
  • Declarations: createProfile, getProfile, listProfiles.
  • Target: packages/application/src/memory/profile-store.ts.
  • Files: that module, barrel re-exports, characterization or existing tests.
  • Preserve: tests/controlled-learning-l8.test.ts, profile CLI tests.
  • Lines removed: 58 effective. Glue added: about 4. Net about 54.
  • SCC: unchanged.
  • Prerequisites: this design approved.
  • Non-goals: delegation, ranking, Neutron import retarget.
  • Acceptance: leaf does not import index.ts; functions stay at 17, 14, and 27 effective lines; list order stays name ascending; invalid files stay ignored.

P1K.2 Role delegation ​

  • Responsibility: role grant clamp and delegation record.
  • Declarations: delegateTaskRole, split into clamp and persist.
  • Target: packages/application/src/memory/role-delegation.ts.
  • Files: that module. It imports getProfile from the profile leaf.
  • Preserve: L8 delegation cases and cli/delegate-command.ts behavior.
  • Lines removed: 65 effective. Glue about 3. Net about 62.
  • SCC: unchanged.
  • Prerequisites: P1K.1.
  • Non-goals: changing which roles are read-only, network policy, or id format del-${role}-${Date.now()}.
  • Acceptance: both new functions are at or below 40 effective lines; missing profile and disallowed role errors stay byte-for-byte.

P1K.3 Task and session summaries ​

  • Responsibility: both summary stores.
  • Declarations: the five summary functions in section 3.4.
  • Target: packages/application/src/memory/task-session-summary-store.ts.
  • Preserve: tests/controlled-learning-l1.test.ts, tests/memory-security-m4.test.ts, summary CLI.
  • Lines removed: 152 effective. Glue about 6. Net about 146.
  • SCC: unchanged.
  • Prerequisites: this design approved. Independent of P1K.1.
  • Non-goals: redacting session notes, sorting by another field, Neutron retarget of getTaskSummary.
  • Acceptance: task path filtering still uses secretLikePath only; session writes do not gain that filter; corrupt files stay ignored.

P1K.4 Task checkpoints ​

  • Responsibility: checkpoint store and state writes.
  • Declarations: the eight checkpoint functions in section 3.5.
  • Target: packages/application/src/memory/task-checkpoint-store.ts.
  • Preserve: tests/controlled-learning-l6.test.ts, tests/cli-checkpoint.test.ts.
  • Lines removed: 178 effective. Glue about 8. Net about 170.
  • SCC: unchanged.
  • Prerequisites: this design approved.
  • Non-goals: a stricter state machine, Neutron graph checkpoints, Undo.
  • Acceptance: resume error string stays; reason stays unused; checksum still reads Date.now separately from the id.

P1K.5 Semantic ranking ​

  • Responsibility: ranking config and procedural ranking.
  • Declarations: getSemanticRankingConfig, updateSemanticRankingConfig, rankProceduralMemory.
  • Target: packages/application/src/memory/semantic-ranking.ts, with proposal scoring and evaluation scoring extracted.
  • The module imports skill leaves, not the barrel.
  • Preserve: tests/controlled-learning-l7.test.ts, tests/cli-rank.test.ts.
  • Lines removed: 117 effective. Glue about 5. Net about 112.
  • SCC: unchanged.
  • Prerequisites: sequenced after P1K.3 so two slices do not edit memory/ at once. Ranking does not call the summary store.
  • Non-goals: a real embedding provider, skipping work when enabled is false, changing weights 0.5 and 0.4.
  • Acceptance: no function exceeds 40 effective lines; disabled config still returns scored items.

P1K.6 Bounded project context ​

  • Responsibility: bounded context read model.
  • Declaration: getBoundedProjectContext, split as section 3.7.
  • Target: packages/application/src/memory/bounded-project-context.ts.
  • Preserve: tests/memory-security-m1.test.ts, context CLI.
  • Lines removed: 101 effective. Glue about 3. Net about 98.
  • SCC: unchanged. Neutron collector keeps importing the barrel.
  • Prerequisites: this design approved.
  • Non-goals: aligning exclusion patterns with secretLikePath, sorting candidates, changing the first-item budget exception.
  • Acceptance: no function exceeds 80 effective lines; the module stays at or below 250; inclusion order matches fs.list order.

P1K.7 Security adapter execution ​

  • Responsibility: correlation and the local adapter runner.
  • Declarations: correlateSecurityFindings, runLocalSecurityAdapters.
  • Targets: the six security/security-adapter-*.ts files in section 3.8.
  • Design First gate: section 22. Implementation does not start until that section is explicitly approved after this documentation pull request.
  • Preserve: tests/memory-security-s2.test.ts, tests/security-finding-store-p1h4a.test.ts, and security CLI coverage. Add characterization tests listed in section 22 before moving code.
  • Lines removed: 213 effective (remeasured after P1K.6). Glue about 4. Net about 209.
  • SCC: unchanged — import-only [3], re-export-inclusive [4, 27, 3]; new leaves stay outside every component.
  • Prerequisites: merged P1K design (PR #627), P1K.6 merged, and maintainer approval of section 22.
  • Non-goals: new scanners, symlink hardening, secret description redaction, transactions, caching, concurrency, protocol or export-map changes.
  • Acceptance: section 22 implementation acceptance matrix; no function above 80 effective lines in new modules; barrel re-exports only.

P1K.8 Workspace conversations ​

  • Responsibility: conversation persistence and redaction.
  • Declarations: path helper, start, get, redact, append, list.
  • Target: packages/application/src/workspace/workspace-conversation-store.ts.
  • syncLocalWorkspaceState stays on the barrel and imports list from the leaf, as P1J did for task records.
  • Preserve: tests/workspace-agent.test.ts, workspace CLI tests.
  • Lines removed: 120 effective. Glue about 6. Net about 114.
  • SCC: unchanged.
  • Prerequisites: this design approved.
  • Non-goals: proposal promote, review, apply, or moving local sync.
  • Acceptance: redaction patterns stay; list order stays updatedAt descending.

P1K.9 Workspace proposal lifecycle ​

  • Responsibility: promote, review, and apply of workspace proposals.
  • Declarations: path helper, the three operations, and WorkspaceProposalReviewResult.
  • Target: packages/application/src/workspace/workspace-proposal-lifecycle.ts.
  • The leaf receives adoptProject as a port. Barrel wrappers keep today's signatures and pass the local adoptProject.
  • Preserve: tests/workspace-apply.test.ts, workspace CLI tests.
  • Lines removed: about 70 effective while wrappers remain. The wrappers leave in P1K.16.
  • SCC: unchanged, because the leaf does not import the barrel.
  • Prerequisites: P1K.8, so conversation reads come from the conversation leaf rather than from the barrel.
  • Non-goals: routing apply through executeApprovedApplyPlan, honoring readyToApply, or treating approvedBy as an ADR-0053 capability.
  • Acceptance: promote and the review fallback stay dryRun: true; apply default stays dryRun: false; the approval error string stays.
  • Design First gate: section 24. Implementation is not authorized until a maintainer approves that section.

P1K.10 Project root and timeline ​

  • Responsibility: canonical root check and release timeline.
  • Declarations: ProjectRootError, assertCanonicalProjectRoot, ProjectTimelineOptions, ProjectTimeline, timelineProject.
  • Target: packages/application/src/project-lifecycle/project-root.ts.
  • Preserve: daemon timeline and root callers through the package root. Quality still imports the barrel until P1K.15.
  • Lines removed: about 56 effective. Glue about 5. Net about 51.
  • SCC: unchanged until P1K.15 retargets quality.
  • Prerequisites: P1K.9 implementation merged (PR #643).
  • Non-goals: realpath hardening beyond the current symbolic-link root check.
  • Acceptance: error codes stay invalid_root and stale_root.
  • Design First gate: section 25. Implementation is not authorized until a maintainer approves that section.

P1K.11 Feature planning stub ​

  • Responsibility: planFeature only.
  • Target: packages/application/src/feature-intent/plan-feature.ts.
  • Preserve: tests/cli-plan.test.ts.
  • Lines removed: 66 effective. Glue about 3. Net about 63.
  • SCC: unchanged.
  • Prerequisites: this design approved, and section 26 accepted by the Project Owner. Parent roadmap text is not that acceptance.
  • Non-goals: reading the repository or producing a real brief.
  • Acceptance: the JSON document shape and validator failure type stay.
  • Design First gate: section 26. Accepted 2026-11-29 13:31:01 Europe/Berlin. Implementation was authorized separately at 2026-11-29 13:46 Europe/Berlin after main verification of c72168a.

P1K.12 Pack update planning ​

  • Responsibility: planPackUpdate and PlanPackUpdateOptions.
  • Target: packages/application/src/project-adoption/plan-pack-update.ts.
  • It imports planProjectAdoption from the existing adoption leaf.
  • Preserve: pack update CLI tests.
  • Lines removed: 44 effective including the options interface. Glue about 4. Net about 40.
  • SCC: unchanged. Adoption modules that import the barrel stay as they are.
  • Prerequisites: this design approved.
  • Non-goals: making the operation map rewrite map-existing or create.
  • Acceptance: default target version stays "1.1.0"; symlink roots still throw the current error.
  • Implementation is in review. Measured sizes are in section 27.18. The line figures in this list remain the design forecast.

P1K.13 Workspace composition bindings ​

  • Responsibility: move the two read-model bindings off the barrel.
  • Declarations: InteractiveWorkspaceState, getInteractiveWorkspaceState, syncLocalWorkspaceState.
  • Targets: workspace/interactive-workspace-composition.ts and workspace/local-workspace-sync.ts.
  • Preserve: P1H.7 tests, UI CLI, Neutron sync CLI, and the P1J structure assertion that local sync passes the four ports. That assertion will name the new module instead of the barrel body. That is a test-path update, not a behavior change, and it belongs to the implementation slice.
  • Lines removed: 52 effective. Glue about 6. Net about 46.
  • SCC: unchanged.
  • Prerequisites: P1K.8 and P1K.10.
  • Non-goals: changing the read model or security audit call.
  • Acceptance: the port object keys and call arguments stay identical.
  • Design First gate: section 28. Implementation is not authorized until the Project Owner accepts section 28.18 and separately authorizes the implementation after main verification of that design merge.

P1K.14 Dispatcher and Approved Apply retarget ​

  • Responsibility: Option B only from section 8.3.
  • Move synchronizeGeneratedFiles and the private TransactionMetadata contract unchanged into packages/application/src/generated-file/synchronize-generated-files.ts.
  • Retarget all imports in approved-apply-engine.ts to canonical leaf owners (nodeFileSystem and FileSystem from host-file-system.ts, TransactionOptions from generated-file/transaction-contracts.ts, the dispatcher from the new leaf).
  • Retarget harness/harness-benchmark-sample.ts to import the dispatcher from the leaf. Do not edit files under src/neutron/.
  • Preserve: evaluate the Approved Apply gate; validate declared-path scope; capture or validate baseline; call the existing dispatcher unchanged; preserve transaction stages, rollback, and diagnostics; return the existing validated result shape.
  • Preserve: existing ApprovedApplyEngineOptions fields (fs, failAt, rollbackFailPaths, and any others today). No public callback or dispatcher override.
  • Preserve: tests/approved-apply-engine.test.ts, generated-file transaction tests, harness benchmark tests. Use existing filesystem fault injection and transaction options for regression tests.
  • Lines removed from the barrel: 12 effective. Re-export glue about 3.
  • SCC: engine and bounded execution leave the 27-file component. Harness leaves with its retarget. Predicted index component size: 19. Membership is section 16. No new component. Re-measured membership must match the approved prediction; this design makes no guarantee beyond the forecast.
  • Prerequisites: this design's Option B choice. Not dependent on the memory slices.
  • Non-goals: changing gate checks, path-scope checks, baseline behavior, stage names, rollback, or adding ApprovedApplyEngineOptions fields.
  • Acceptance:
    • No import of index.ts from approved-apply-engine.ts, including type-only imports (no index.js specifier in engine source).
    • No new public dispatcher override on ApprovedApplyEngineOptions.
    • No behavioral change to Apply, transactions, or rollback.
    • Measured SCC membership after the slice matches the section 16 prediction for this slice.
    • Existing Approved Apply, transaction, and rollback tests pass.
    • Declared-path mode still does not receive validatedMetadata.

P1K.15 Engineering-quality root retarget ​

  • Responsibility: point specialized-pack external apply at the project-root leaf.
  • No barrel body remains for this symbol after P1K.10.
  • SCC: the five engineering-quality files leave the index component. Predicted size: 14.
  • Prerequisites: P1K.10.
  • Non-goals: lockfile or activation behavior.
  • Acceptance: quality module has no index.js import; daemon handlers still import assertCanonicalProjectRoot from the package root.

P1K.16 Adoption import retarget ​

  • Responsibility: move syncProject and adoptProject to project-lifecycle/project-sync-binding.ts and project-adoption/generated-file-adoption-binding.ts. Retarget existing-project imports of lifecycle functions, adoption bindings, ProjectMapping, InitOptions, and TransactionOptions onto their leaves. Replace P1K.9 barrel wrappers with re-exports once the proposal leaf can import the adoption binding.
  • SCC: the remaining index component dissolves. index.ts is in no component. Extension quartet and Neutron trio stay.
  • Prerequisites: P1K.12, P1K.14, and P1K.9.
  • Non-goals: adoption approval rules or health checks.
  • Acceptance: no file that index.ts re-exports imports index.ts.

P1K.17 Export-from barrel ​

  • Responsibility: delete residual value imports and express the public surface as export ... from only. Remeasure index.ts.
  • Prerequisites: P1K.13, P1K.15, and P1K.16.
  • SCC: unchanged from P1K.16.
  • Non-goals: removing a public name, splitting the package, or adding a subpath.
  • Acceptance: measured effective lines are at most 400 and physical lines at most 700, or the pull request stops and names the declarations that still prevent it. This design does not pre-approve an exception.

11. Public compatibility strategy ​

CLI, daemon, and MCP import @intentloom/application, and the CLI barrel star-re-exports it. Every moved name stays exported from index.ts. No signature gains a required parameter. executeApprovedApplyPlan keeps (request, filesToApply, options?). ApprovedApplyEngineOptions keeps its current fields only; P1K.14 does not add a dispatcher override.

Internal relative imports of index.ts are retargeted only in P1K.14, P1K.15, and P1K.16, and only for the symbols those slices own. Neutron files keep their current barrel imports. That preserves topology allowlists in tests/application-neutron-topology.test.ts.

JSON bytes, CLI flags, error strings listed in section 14, and the ignored fields already documented for P1J stay. planFeature remains a stub. Security categories that return no findings remain empty.

12. Security and trust boundaries ​

mermaid
flowchart TB
  caller["CLI daemon MCP or Neutron caller"]
  barrel["package root re-exports"]
  memory[".aif/memory JSON stores"]
  workspace[".aif/workspace and .aif/proposals"]
  project["project files inside the resolved root"]
  gate["evaluateApprovedApplyPlan"]
  dispatcher["synchronizeGeneratedFiles"]
  transaction["declared-path or owned-file transaction"]

  caller --> barrel
  barrel -->|"secretLikePath filter on task paths"| memory
  barrel -->|"regex redaction on appended messages"| workspace
  barrel -->|"path exclusion before context read"| memory
  caller -->|"non-empty approvedBy is not the Apply gate"| barrel
  barrel -->|"proposal create and review do not write project files"| workspace
  gate -->|"fail closed before write"| dispatcher
  dispatcher --> transaction
  transaction -->|"contained writes and transactional rollback"| project

Source: security-trust-boundaries.mmd.

Boundaries that pure extraction must not change:

  • Project writes stay inside the root checks each current function already performs. inside remains the path join for memory, conversations, and proposals. assertCanonicalProjectRoot still rejects a missing root and a symbolic-link root.
  • nodeFileSystem still follows symlinks on write. P1J recorded that the legacy task store does not revalidate the destination realpath, and that a caller-supplied task id can stay inside the project root while leaving .aif/neutron/subagents/. Those gaps stay assigned to separately approved hardening. They are not fixed inside a move.
  • Workspace append redaction stays the current three replacements.
  • Bounded-context exclusion stays the current nine patterns.
  • Task-summary path filtering stays secretLikePath on affectedPaths only.
  • Persisted JSON stays schema version "1", two-space indent, and a trailing newline. Checkpoint state names stay the current strings.
  • Security adapter order, rule ids, severities, and empty categories stay.
  • Transaction stages stay the TransactionStage union: generated-stage, generated-commit, manifest-stage, manifest-finalize, source-map-stage, source-map-finalize, post-write-consistency, and success-cleanup.
  • The Approved Apply gate still runs before baseline capture and before the dispatcher. Path-scope mismatch still returns before any write.
  • Proposal creation and readyToApply do not authorize Apply. Workspace approvedBy does not grant atomic-commit-approval.
  • Transaction rollback stays inside the existing sync implementations. P1K.14 does not expose a public dispatcher substitution seam. User Undo stays U4 and U5 and does not start.
  • Public error strings in section 14 stay.
  • CLI output stays whatever the current commands print from these return values.
  • Neutron execution stays provider-neutral. No slice calls a model, starts a background job, or turns a stub adapter into a scanner.

13. Data and filesystem flows ​

Memory writes are validate, mkdir when the parent is absent, then write of pretty JSON. Reads are exists plus read, or a full fs.list followed by a prefix filter. That list walks the project. Extraction does not replace it with a directory listing unless a test proves the same paths, order, and error ignoring.

Conversation and proposal flows are the same pattern under .aif/workspace/conversations/ and .aif/proposals/. Proposal file bytes are the AdoptionProposal returned by dry-run adoptProject, not the conversation transcript.

Generated-file flow is unchanged: the dispatcher chooses declared-path sync or owned-file commit. Declared-path collision and noncanonical paths fail with rollbackAttempted: false before writes. Later declared-path failures carry failedStage and may restore backups. Owned-file commit keeps its current stage machine. The engine maps a non-success result to diagnostics and does not start a second write.

Interactive and local sync do not write. They call the read model with the current ports.

14. Error and rollback behavior ​

mermaid
sequenceDiagram
  participant Caller
  participant Engine as executeApprovedApplyPlan
  participant Gate as evaluateApprovedApplyPlan
  participant Baseline as baseline capture
  participant Dispatcher as synchronizeGeneratedFiles
  participant Declared as synchronizeDeclaredProjectPaths
  participant Commit as commitOwnedGeneratedFiles

  Caller->>Engine: request files options
  Engine->>Gate: evaluate request
  alt gate failed
    Gate-->>Engine: passed false
    Engine-->>Caller: applied false gate-evaluation-failed
  else declared paths and path sets differ
    Engine-->>Caller: applied false path-scope-mismatch
  else gate passed
    Engine->>Baseline: capture or assert current baseline
    alt supplied baseline is stale or a symlink blocks it
      Baseline-->>Caller: ApplyBlockedBeforeWrite
    else baseline accepted
      Engine->>Dispatcher: root files fs options
      alt syncMode is declared paths only
        Dispatcher->>Declared: same arguments without metadata
      else ordinary generated files
        Dispatcher->>Commit: root files fs options metadata
      end
      alt status is not success
        Dispatcher-->>Engine: failedStage rollback fields
        Engine-->>Caller: applied false transaction-failed and stage diagnostics
      else success
        Dispatcher-->>Engine: success
        Engine-->>Caller: applied true empty diagnostics
      end
    end
  end

Source: approved-apply-sync-sequence.mmd.

Before-write Apply failures:

  • Gate failure returns applied: false and diagnostics beginning with gate-evaluation-failed, then the gate diagnostics. No baseline read and no dispatcher call.
  • Declared-path mode with unequal path sets returns path-scope-mismatch before baseline and before the dispatcher.
  • assertApprovedApplyBaselineCurrent throws ApplyBlockedBeforeWrite with project-stale / restoration-baseline-changed when a supplied baseline path has a symlink ancestor or the bytes changed. The engine does not catch that throw. Preserve the throw.

After the dispatcher returns status !== "success", diagnostics are, in order: transaction-failed:${status}, failed-stage:${failedStage} when present, rollback-attempted when rollbackAttempted is true, and rollback-failures: plus the joined paths when rollback failures are non-empty. applied stays false. Rollback evidence carries the captured baseline. Success returns applied: true and diagnostics: [], and still attaches rollback evidence for the baseline that was not restored.

That rollback is the transaction restore inside declared-path sync or owned-file commit. It is not user Undo.

Other error strings to preserve:

  • project root does not exist
  • project root is a symbolic link and is not stable
  • task identifier is required
  • pack update planning requires a non-symbolic explicit project root
  • Task checkpoint not found: ${id}
  • Cannot resume cancelled task checkpoint: ${id}
  • Profile not found: ${name}
  • Role [${role}] is not allowed by profile [${name}]
  • Conversation ${id} not found
  • Workspace conversation ${id} not found
  • human approval required (--approved-by USER)

Corrupt memory, checkpoint, profile, conversation, and ranking-config reads stay soft: null, default config, or a skipped list entry. They do not throw.

15. Source-size forecasts ​

Start: 1,804 effective, 1,953 physical.

Function bodies: 1,304 effective and 1,396 physical. Non-function remainder: 500 effective. Lines 1–147, the import preamble, are 146 effective lines that the final export-from barrel deletes. Local type and class bodies are 58 effective lines, replaced by about 15 re-export lines. Moved functions add about 70 named re-export lines.

Central forecast after P1K.17:

500 - 146 - 58 + 15 + 70 = 381 effective lines.

Physical forecast:

1953 - 1396 - 147 - 60 + 85 + 30 = 465 physical lines.

After sliceEstimated effectiveWhat changed
P1K.11750profiles
P1K.21688delegation
P1K.31542summaries
P1K.41372checkpoints
P1K.51260ranking
P1K.61162bounded context
P1K.7953security adapters
P1K.8839conversations
P1K.9769proposals, wrappers still present
P1K.10718root and timeline
P1K.11655planFeature
P1K.12615pack update
P1K.13569workspace composition
P1K.14560dispatcher re-export
P1K.16about 520bindings and proposal wrappers
P1K.17381bottom-up identity below

P1K.15 does not change the barrel size. Rows P1K.1 through P1K.16 are rounded running estimates of function-body removal. They still contain the import preamble. P1K.17 is not "the previous row minus 146". The completion number is the bottom-up identity, 381. Each implementation pull request remeasures. The P1K.11 cell of 655 assumed a post-P1K.10 barrel near 718. Section 26 remeasures index.ts at 742 effective lines on 39ee6e8 and forecasts about 679 after the same net of about 63. That forecast is not an observed extraction. Glue that runs long by about 40 lines, or type re-exports that stay verbose, produces an upper band near 420 effective lines, which misses 400.

The P1K.13 cell of 569 assumed a post-P1K.12 barrel near 615. Section 28 remeasures index.ts at 629 effective lines on 3d641e4 and forecasts 574 after the simulated move. That forecast is not an observed extraction. The 569 cell stays the historical running estimate.

The plan reaches the target in the central estimate without an exception. It does not reach the target in the upper band. The unresolved block in that band is leftover forwarding wrappers plus the protocol type and validator re-export lists, which are about 74 and 23 lines of public compatibility surface. Those lists are not an approved exception. P1K.17 measures the file. If the result is over 400, that pull request stops and names the lines. It does not declare P1 complete.

Physical lines stay under 700 in both the central estimate and a band of about 80 extra blank or wrapping lines.

Composition that must still exist somewhere, and must not remain as bodies on the final barrel, is syncProject, adoptProject, the two workspace bindings, and the dispatcher. Their bodies are about 64 effective lines. The forecast assumes they live in the binding modules in section 7.

16. Full SCC membership forecasts ​

Current membership is section 8.1. Predictions:

SliceImport-onlyRe-export component containing index.tsEngine component
P1K.1–13still the Neutron triostill the same 27 filesengine remains inside that 27
P1K.14unchanged19 files, engine and harness and bounded execution goneengine is in no component
P1K.15unchanged14 files, quality chain goneengine stays out
P1K.16unchangednoneengine stays out
P1K.17unchangednoneengine stays out

P1K.1 through P1K.13 add modules that must stay outside every component. They do not retarget existing edges, so membership is unchanged. They do not create a component.

P1K.14 removes these eight files from the index component: approved-apply-engine.ts, bounded-execution-apply.ts, bounded-execution-w11.ts, bounded-execution-workspace.ts, bounded-execution-workspace-cli.ts, harness/harness.ts, harness/harness-benchmark.ts, and harness/harness-benchmark-sample.ts. The remaining 19 are index.ts, inception-flow.ts, foundation-flow.ts, the existing-project files listed in section 8.1, and the five engineering-quality files listed there.

P1K.15 removes the five engineering-quality files. The remaining 14 are index.ts, inception-flow.ts, foundation-flow.ts, and the eleven existing-project files in section 8.1.

P1K.16 removes the adoption back-edges. That component disappears. The extension quartet stays size 4 with the same four files. The Neutron trio stays size 3 with the same three files, on both import-only and re-export graphs. No new component is predicted. A new component in an implementation slice is a failed acceptance check.

Type-only retargets matter because the cycle detector counts them. P1K.14 is not complete if FileSystem or TransactionOptions still come from index.ts.

17. Regression testing strategy ​

Each implementation slice keeps the tests named in section 10 and adds a structure test in the style of tests/legacy-subagent-task-record-p1j-structure.test.ts: measured file and function sizes, no index.js import from the new leaf, and applicationCycles equal to the prediction for that slice.

Behavior tests to keep green across the program:

  • tests/controlled-learning-l1.test.ts through l8
  • tests/memory-security-m1.test.ts, m4, and s2
  • tests/cli-plan.test.ts, pack update, checkpoint, rank, workspace
  • tests/workspace-agent.test.ts, tests/workspace-apply.test.ts
  • tests/workspace-read-model-p1h7.test.ts
  • tests/approved-apply-engine.test.ts
  • generated-file transaction, declared-path, and post-write tests
  • harness benchmark tests
  • tests/application-neutron-topology.test.ts without allowlist edits

P1K.6 and P1K.7 add characterization tests before the split: context ordering, token budget, exclusion count, adapter category order, finding ids, and empty categories. P1K.14 relies on existing Approved Apply and generated-file transaction tests plus existing failAt and rollbackFailPaths fault injection. It does not require a new public override seam or new production diagnostics.

No snapshot-only evidence for rollback or authorization. pnpm verify is the implementation gate. This design pull request does not change tests.

18. ADR impacts ​

ADR-0053 stays accepted and unchanged. Option B does not change the gate, the requirement for explicit approval, the digest check, or transactional rollback. A new ADR is required only if a later decision replaces the dispatcher, changes who may Apply, or merges workspace approvedBy with the Approved Apply capability. This plan does not do those things.

No ADR is required to place profiles, summaries, checkpoints, or conversations in existing directories. R4A through R4D stay in force because no Neutron file is an extraction target. P1H.7 and P1I.2 seams are reused, not reopened.

docs/decisions/ is not modified by this design.

19. Risks and mitigations ​

RiskMitigation
A large function moves unchangedP1K.5, P1K.6, and P1K.7 split before the new files are accepted
Type-only barrel import keeps the SCC edgeP1K.14 acceptance searches the engine for index.js
Proposal leaf imports adoptProject from the barrel and cyclesPort injection until P1K.16
Wrapper lines push the barrel over 400P1K.17 measures and stops; no exception is implied
Extraction "fixes" empty adapters, stub planning, or workspace applySection 12 non-goals and characterization tests
Symlink or task-id containment gets patched silentlyHardening stays a separate approved change
Neutron topology test is edited to allow a new edgeNeutron files are out of scope; the test stays unmodified
Implementation starts from this document before approvalStatus line and Duty Watch say the slices are not approved

Rollback of an implementation slice is reverting that pull request. Data formats do not migrate, so revert does not need a storage migration.

20. P1 completion checklist ​

P1 is complete only when all of the following are true on main:

  • [ ] This design is explicitly approved, or a successor design replaces it.
  • [ ] P1K.1 through P1K.17 are merged, or a maintainer-approved subset still meets the measurements below.
  • [ ] measureProductionSource reports index.ts at or below 400 effective lines and 700 physical lines, without an unapproved exception.
  • [ ] applicationCycles(false) is only the Neutron trio.
  • [ ] applicationCycles(true) is the extension quartet and the Neutron trio. index.ts is in neither. approved-apply-engine.ts is in neither.
  • [ ] No new component exists.
  • [ ] tests/application-neutron-topology.test.ts passes without allowlist edits.
  • [ ] CLI, daemon, and MCP still typecheck against the root barrel.
  • [ ] pnpm verify passes on the final implementation head.
  • [ ] No slice changed behavior, error strings, or persisted bytes.
  • [ ] Undo U4 and Desktop Undo U5 are still unstarted.
  • [ ] P2 through P6 are still unstarted.

This checklist is not satisfied by merging the design.

21. Unresolved maintainer decisions ​

  1. Whether the working label P1K is acceptable, and whether the seventeen ids stay.
  2. Whether P1K.1, the profile store, is the first implementation slice.
  3. Whether Option B (leaf dispatcher, no public override) is accepted, or Option D should be chosen instead. Option C (dispatcher injection) is rejected in this design. Option A does not complete P1.
  4. Whether P1 is incomplete until index.ts leaves every SCC, which this plan does in P1K.16, or only until it leaves the engine's component, which happens in P1K.14. The written gate names the Approved Apply component. This plan treats the remaining hub as in scope because a barrel that implementation modules import is not the section 14 end state.
  5. Whether delegateTaskRole must be split in P1K.2. This design says yes. The 65-line function is legal and still mixes policy with IO.
  6. Whether the four empty security categories remain empty. This design says yes.
  7. No line-budget exception is granted by this document. If P1K.17 measures above 400, the maintainer decides whether to name an exception or cut more re-export surface.

Project Sable and other future product ideas are unchanged and are not decided here.

22. P1K.7 security adapter execution — Design First gate ​

Status: proposed (this documentation pull request). Parent design PR #627 remains the architectural roadmap. This section records verified current behavior and implementation boundaries for slice P1K.7 only. It does not approve implementation.

22.1 Problem and scope ​

P1K.7 extracts correlateSecurityFindings and runLocalSecurityAdapters from index.ts into six modules under packages/application/src/security/ without changing scanning rules, persistence bytes, public signatures, or CLI output. ADR-0028 and the existing security finding store contract stay in force.

22.2 Public interfaces and compatibility ​

SymbolVisibilityCompatibility
correlateSecurityFindings(findings)exported from @intentloom/applicationsame signature; pure function; no FileSystem
runLocalSecurityAdapters(options, fs?)exported from @intentloom/applicationsame options.root, optional categories, optional FileSystem defaulting to nodeFileSystem
Scanner modulespackage-internalnot exported from barrel or export map
Protocol types@intentloom/protocolunchanged in this slice

CLI intentloom security scan continues to call runLocalSecurityAdapters through the package root with optional single --category (wraps as a one-element categories array). JSON and text output shapes stay as today.

22.3 Proposed dependency direction ​

mermaid
flowchart TB
  cli["CLI security-operations-command.ts"]
  barrel["index.ts re-exports"]
  runner["security/security-adapter-run.ts"]
  correlate["security/security-adapter-correlation.ts"]
  dep["security/security-adapter-dependency.ts"]
  secret["security/security-adapter-secret.ts"]
  cfg["security/security-adapter-config.ts"]
  mcp["security/security-adapter-mcp.ts"]
  store["security/security-finding-store.ts"]
  pathmod["project-path.ts inside secretLikePath"]
  fsport["host-file-system.ts"]
  protocol["@intentloom/protocol validators"]

  cli -->|"runLocalSecurityAdapters"| barrel
  barrel --> runner
  runner --> dep
  runner --> secret
  runner --> cfg
  runner --> mcp
  runner --> correlate
  runner -->|"securityFindingPath"| store
  dep --> fsport
  dep --> pathmod
  dep --> protocol
  secret --> fsport
  secret --> pathmod
  secret --> protocol
  cfg --> fsport
  cfg --> protocol
  mcp --> fsport
  mcp --> pathmod
  mcp --> protocol
  runner --> fsport
  runner --> protocol
  correlate --> protocol

Source: security-adapter-dependencies.mmd. Section 7 future-module-layout.mmd already shows the same leaf names; that diagram is still correct and is not duplicated here.

Rules:

  • Clients depend on the package barrel only; no new subpath exports.
  • Extracted leaves import host-file-system.ts, project-path.ts, protocol validators, and sibling scanner modules only through the runner.
  • No leaf imports index.ts or src/neutron/**.
  • security-finding-store.ts does not import adapter modules.

22.4 DDD ownership ​

Bounded context: Security findings (section 5). Local adapter execution produces normalized SecurityFinding records and adapter metadata; it is not Approved Apply, not sandbox evaluation, not continuous audit orchestration. Correlation is a domain helper for duplicate suppression within one category batch.

22.5 Data flow ​

mermaid
sequenceDiagram
  participant Caller
  participant Runner as runLocalSecurityAdapters
  participant Dep as dependency scanner
  participant Secret as secret scanner
  participant Config as config scanner
  participant Mcp as mcp scanner
  participant Corr as correlateSecurityFindings
  participant FS as FileSystem
  participant Disk as .aif/security/findings

  Caller->>Runner: root, categories, fs
  Runner->>Runner: category order, shared timestamp, counter starts at 1
  loop each category in order
    alt dependency
      Dep->>FS: exists package.json
      opt file exists
        Dep->>FS: read package.json
        Note over Dep: one try covers read, JSON.parse, and validateSecurityFinding
      end
    else secret
      Secret->>FS: list root
      Note over Secret: no file read, and validateSecurityFinding is outside any try
    else config
      Config->>FS: list root
      Note over Config: no file read, and validateSecurityFinding is outside any try
    else mcp
      Mcp->>FS: list root
      loop each .aif/mcp JSON file
        Mcp->>FS: read that file
        Note over Mcp: per-file try covers read, JSON.parse, and validateSecurityFinding
      end
    else source, extension, hook, or agentic
      Note over Runner: no filesystem call and no findings
    end
    Runner->>Corr: this category raw findings
    Corr-->>Runner: sorted by id
    loop each correlated finding
      Runner->>FS: exists parent directory
      opt parent is missing
        Runner->>FS: mkdir parent
      end
      Runner->>FS: write finding JSON
      FS->>Disk: .aif/security/findings/id.json
    end
    Runner->>Runner: validate adapter metadata and result
  end
  Runner-->>Caller: SecurityAdapterResult array

Source: security-adapter-run-sequence.mmd.

22.6 Failure propagation and error boundaries ​

BoundaryBehavior todayP1K.7 change
Dependency package.json missingfs.exists is false; no dependency findings; category still returns one adapter resultnone
Dependency fs.exists failurepropagates before the try; this category is not persisted; earlier categories stay on disknone
Dependency fs.read, JSON.parse, or validateSecurityFindingone try around the whole manifest; catch keeps findings already pushed and counter increments already evaluated; remaining names in that manifest are skipped; no throw; correlation and persistence still run; later categories still runnone
Secret or config fs.list failurepropagates; this category is not correlated or persisted; earlier categories stay on disknone
Secret or config validateSecurityFindingoutside any try; propagates; findings already pushed for this category are not written; counter is not rewound; later categories do not runnone
MCP fs.list failurepropagates, same as secret and config listingnone
MCP per-file fs.read, JSON.parse, or validateSecurityFindingone try per matching JSON file; that file stops; earlier files' findings stay; a validation throw consumes an id and does not push; later files still run; the partial list is correlated and persistednone
Parent fs.exists, fs.mkdir, or fs.write during persistenceoutside every scanner try; propagates; findings already written in this run stay, including earlier findings in the same category; remaining writes and categories do not runnone
validateSecurityAdapterMetadata or validateSecurityAdapterResultafter that category's writes; throw leaves those files on disk and skips later categoriesnone
inside() path traversalthrows; not caught by the dependency try when it happens before fs.existsnone

No new fail-open or fail-closed policy is introduced. Partial persistence on write failure is an existing limitation, not fixed here.

22.7 Security and trust invariants ​

Documented in section 3.8 and section 12. Additional P1K.7 clarifications:

  • Secret scanner: path-only; secretLikePath from project-path.ts; evidence redacted; description exposes relative path (future hardening candidate).
  • Empty stub categories must remain zero-finding adapters with full metadata.
  • Adapter readOnly / networkAccess metadata does not skip persistence.
  • nodeFileSystem symlink follow behavior unchanged.

22.8 Code size and SCC constraints ​

ConstraintRequirement
Production file budgeteach new module ≤250 effective preferred, ≤400 hard
Function budgeteach function ≤40 preferred, ≤80 hard; runner orchestration split so no 188-line function remains
SCC after sliceimport-only [3]; re-export-inclusive [4, 27, 3] unchanged
Structure testsame style as tests/legacy-subagent-task-record-p1j-structure.test.ts: no index.js import from new leaves, measured sizes

Forecast: index.ts drops by ~209 effective lines toward the P1K.7 row in section 15 (remeasure on implementation).

22.9 Test strategy ​

Before extraction (characterization, new or extended tests):

  • Default eight categories in exact order; assert eight adapter results.
  • Caller order ["mcp", "dependency"] and duplicate ["dependency", "dependency"].
  • Shared counter: dependency then secret ids sec-dep-1, sec-secret-2 (etc.).
  • Correlation: higher, equal, and lower severity on same rule/evidence key.
  • Secret: .env match, skip node_modules, evidence [REDACTED], description contains relative path.
  • Dependency: * / latest / >=; ^ not flagged; malformed JSON silent.
  • Config: .aif/ without .aif/policy.
  • MCP: allowGenericShell === true; malformed JSON silent.
  • Empty categories source, extension, hook, agentic: zero findings, one result each.
  • Persisted JSON bytes and path layout under .aif/security/findings/.
  • Partial persistence: simulate write failure after first finding (injected FS).
  • CLI JSON and text for security scan.

After extraction: existing tests above plus pnpm verify; structure test for six modules; applicationCycles unchanged.

22.10 Design First acceptance matrix ​

AreaCovered
Public interfaces and compatibilitysection 22.2
Component ownership (six modules)sections 3.8, 22.3–22.4
Data flow scanner → correlation → persistencesection 22.5
Success pathsection 22.5 sequence
Failure paths and propagationsection 22.6
Validation boundariessections 22.6, 3.8
Partial write / no rollbacksections 22.6, 3.8
Category and finding orderingsection 3.8
Redaction and description-path behaviorsections 3.8, 22.7
Test strategy including negativessection 22.9
Non-goalssections 10 (P1K.7), 22.11
SCC topology and size budgetssection 22.8
Diagramssections 22.3–22.5, 7, 12

Maintainer approval of this matrix and section 3.8 decomposition is required before any P1K.7 implementation pull request.

22.11 Non-goals (P1K.7) ​

  • Implementing scanners for source, extension, hook, or agentic.
  • Changing rule IDs, severities, scanners strings, or trust classes.
  • Symlink hardening, transactional persistence, retries, or caching.
  • Protocol schema or package export-map edits.
  • Neutron, Approved Apply, Undo, or P1K.8+ slices.

22.12 Future work (not P1K.7) ​

  • Redact or generalize secret-finding descriptions that include paths.
  • Real scanners for stub categories (separate Design First).
  • Stronger containment for fs.list traversal and symlink writes (section 12).

22.13 Implementation acceptance matrix (for the future implementation PR) ​

The implementation PR must satisfy all of the following (characterization tests first, then move code):

  1. All eight categories in exact default order when categories omitted.
  2. Caller-supplied category order preserved; duplicate categories not deduped.
  3. Shared findingCounter across categories in one invocation.
  4. Finding ID prefixes sec-dep-, sec-secret-, sec-cfg-, sec-mcp- and deterministic lexicographic order after correlation.
  5. Correlation: higher severity replaces lower; equal keeps first; lower does not replace higher.
  6. Secret path exclusions and evidence [REDACTED].
  7. Description still interpolates relative path for secret findings.
  8. Malformed dependency JSON is caught with read and validateSecurityFinding for the whole manifest: no throw, findings already accepted in that manifest stay, the counter is not rewound, and later dependency names in that file are skipped. Malformed MCP JSON is caught per file with that file's read and validateSecurityFinding: no throw, other MCP files continue, and a consumed id is not reused.
  9. Dependency version matching: *, latest, >= only.
  10. Config missing-policy when .aif/ present without .aif/policy.
  11. MCP allowGenericShell === true detection.
  12. Empty scanner categories still return adapter results with totalCount: 0.
  13. Persisted finding JSON: two-space indent, trailing newline, paths via securityFindingPath.
  14. Directory creation when the parent is missing. Listing failures, parent exists / mkdir / write failures, and secret or config validation failures propagate. Dependency and MCP read, parse, and validation failures stay inside their existing catch boundaries.
  15. Partial persistence when a write fails after earlier writes succeeded.
  16. CLI JSON and text output unchanged for security scan.
  17. No protocol or public export changes beyond re-export wiring.
  18. No new SCC; structure tests and applicationCycles match section 22.8.
  19. Six modules exist; runLocalSecurityAdapters body not a single 188-line function in any file.
  20. Barrel re-exports correlateSecurityFindings and runLocalSecurityAdapters only; scanners stay internal.

22.14 Remaining risks ​

RiskMitigation
Behavior drift during mechanical movecharacterization tests before edit
Accidental scanner implementation for stub categoriesexplicit non-goals and tests
Leaf imports barrel and recreates SCCstructure test forbids index.js import
Oversized runner after splitmeasure each function in CI structure test
Silent "fix" of description-path leakdocumented as future work only

23. Diagram index ​

DiagramSource fileSection
Current application barrel dependenciescurrent-barrel-dependencies.mmd4
Bounded-context ownershipbounded-context-ownership.mmd5
Future target module layoutfuture-module-layout.mmd7
Approved Apply cycleapproved-apply-cycle.mmd8
Alternatives for breaking that cycleapproved-apply-alternatives.mmd8
Phased implementation dependenciesphased-implementation.mmd9
Security trust boundariessecurity-trust-boundaries.mmd12
Approved Apply synchronization sequenceapproved-apply-sync-sequence.mmd14
P1K.7 security adapter dependenciessecurity-adapter-dependencies.mmd22
P1K.7 adapter run sequencesecurity-adapter-run-sequence.mmd22
P1K.9 proposal lifecycle dependenciesworkspace-proposal-dependencies.mmd24
P1K.9 promote, review, and applyworkspace-proposal-sequence.mmd24
P1K.10 project root and timeline depsproject-root-timeline-dependencies.mmd25
P1K.10 root validation and timelineproject-root-timeline-sequence.mmd25
P1K.11 feature planning dependenciesfeature-planning-dependencies.mmd26
P1K.11 validation sequencefeature-planning-validation-sequence.mmd26
P1K.12 pack update planning depspack-update-planning-dependencies.mmd27
P1K.12 pack update planning sequencepack-update-planning-sequence.mmd27
P1K.13 current workspace compositionworkspace-composition-current.mmd28
P1K.13 proposed workspace compositionworkspace-composition-proposed.mmd28
P1K.13 interactive read sequenceworkspace-composition-sequence.mmd28
P1K.13 local sync sequenceworkspace-composition-sync-sequence.mmd28
P1K.13 failure classesworkspace-composition-failure-sequence.mmd28

24. P1K.9 workspace proposal lifecycle — Design First gate ​

Status: proposed (this documentation pull request). Parent design PR #627 remains the architectural roadmap. This section records behavior verified on main at d8c5f2c5c4c06e86bf6f04d4014bcf6e68f066db (P1K.8, PR #639) and the extraction contract for slice P1K.9 only. It does not approve implementation and it does not change adoption, sandbox, or mutation behavior.

Branch naming. Pull request #640 uses design/p1k9-workspace-proposal-boundaries. AGENTS.md allows only <type>/<short-kebab> with change types such as feat, fix, refactor, docs, test, chore, build, ci, perf, security, release, and revert; design/ is not in that list. Keep PR #640 and its remote branch as is unless a maintainer explicitly authorizes a rename or a duplicate pull request. Use an approved prefix (for example docs/p1k9-workspace-proposal-boundaries) for future work on this slice.

24.1 Problem and scope ​

P1K.9 moves workspace proposal path resolution, promotion, review, and apply orchestration out of packages/application/src/index.ts into packages/application/src/workspace/workspace-proposal-lifecycle.ts.

Declarations:

NameTodayAfter extraction
workspaceProposalPathprivate in index.tsprivate in the leaf
promoteWorkspaceConversationToProposalpublicpublic wrapper on the barrel; body on the leaf
WorkspaceProposalReviewResultpublic interfacepublic type re-exported from the leaf
reviewWorkspaceProposalpublicpublic wrapper; body on the leaf
applyWorkspaceProposalpublicpublic wrapper; body on the leaf

Conversation persistence stays in workspace/workspace-conversation-store.ts. syncLocalWorkspaceState and getInteractiveWorkspaceState stay on index.ts.

Measured on this baseline with measureProductionSource: index.ts is 857 effective lines and 903 physical lines. The parent forecast removes about 70 effective lines while the three public wrappers remain. Re-measure during the implementation PR. Preferred file budget is 250 effective lines; hard limit is 400. Preferred function budget is 40 effective lines; hard limit is 80. Current bodies are within the hard function limit (promote about 33 effective, review about 38, apply about 23, path helper 3).

24.2 Verified current behavior ​

Verified by reading packages/application/src/index.ts and packages/cli/src/workspace-command.ts on the baseline above.

Promote

  • Loads the conversation with getWorkspaceConversation and the same FileSystem (implementation in workspace-conversation-store.ts).
  • Conversation path resolution. workspaceConversationPath calls inside(root, ...) before any I/O. A conversation id that escapes the root throws path traversal: from path resolution. That error propagates; promote does not catch it.
  • Conversation presence and readability. fs.exists(path) runs outside the read/parse/validate try/catch. An exists error propagates. When exists is false, getWorkspaceConversation returns null.
  • Conversation bytes and record shape. fs.read, JSON.parse, and validateWorkspaceConversationRecord run inside a try/catch that returns null on any failure (unreadable file, invalid JSON, or invalid record). Those failures do not propagate as read or parse errors to promote's caller.
  • Throws Workspace conversation ${conversationId} not found when the loaded record is null. Promote does not distinguish missing file, bad JSON, or invalid record. It does not copy conversation messages into the proposal.
  • Proposal id is options.proposalId when supplied, otherwise prop-${Date.now()}.
  • Calls adoptProject with profile: "generic", adapters: ["codex"], and dryRun: true. No transactionOptions argument is passed.
  • Resolves .aif/proposals/{id}.json with workspaceProposalPath only after that dry-run adoption returns. A proposal id that escapes the root throws path traversal: at this point, after adoption and before fs.exists.
  • Writes JSON.stringify(proposal, null, 2) plus a trailing newline to that path.
  • Creates the parent directory only when fs.exists(dirname(path)) is false.
  • Returns the adoption proposal object, not a separate review record.
  • Conversation fs.read, JSON parsing, and record validation failures are caught inside getWorkspaceConversation, which returns null. Promote then throws Workspace conversation ${conversationId} not found. Those failures do not propagate as read, parse, or validation errors.
  • Conversation path resolution (workspaceConversationPath / inside) and conversation fs.exists failures outside that catch propagate unchanged.
  • After a conversation record is loaded, adoption failures, proposal parent directory creation (mkdir), proposal-path fs.exists, and proposal write failures propagate as implemented today. There is no retry and no rollback of a partial write.

Review

  • Resolves the proposal path with workspaceProposalPath before fs.exists. A proposal id that escapes the root throws path traversal: before the read and before the dry-run adoption fallback.
  • When the file exists, assigns JSON.parse(await fs.read(path)) with no schema validator and no try/catch.
  • When the file does not exist, calls the same dry-run adoptProject as promote and does not write that result.
  • affectedPaths is proposalData.items.map((item) => item.path).
  • Sandbox input is { changes: affectedPaths.map((path) => ({ type: "modify", path })) } with { root, projectId: options.proposalId } and the same filesystem.
  • readyToApply is sandboxEval.allowed. schemaVersion on the review result is the literal 1, not a field read from the proposal file.
  • options.policyPath is part of the public options object. The function body does not read it and does not pass it to evaluateProposalAgainstSandbox. The CLI still forwards --policy into that field. Preserve this unused argument.

Apply

  • Throws human approval required (--approved-by USER) when approvedBy is missing or approvedBy.trim() is empty.
  • A non-empty trimmed string is the only check. It is not a capability token, plan digest, or ADR-0053 approval.
  • Then calls adoptProject with profile: "generic", adapters: ["codex"], and dryRun: options.dryRun ?? false.
  • proposalId and planFile are accepted on the options object and are not read. Apply does not call workspaceProposalPath or inside() for the proposal id, does not open the stored proposal, and does not read readyToApply. A proposal id that would fail path checks does not throw from this function.
  • Apply does not call executeApprovedApplyPlan or evaluateApprovedApplyPlan.
  • The CLI always passes dryRun from the presence of --dry-run, so the CLI path does not rely on the library default. Direct library callers that omit dryRun get false.

These are existing semantics. Extraction must not “correct” them.

24.3 Port and public wrappers ​

adoptProject still lives on index.ts and calls adoptGeneratedFiles with syncProject. A leaf that imported adoptProject from ../index.js would cycle as soon as the barrel re-exported the leaf.

The leaf therefore takes a typed internal port. It is not a public option on promoteWorkspaceConversationToProposal, reviewWorkspaceProposal, or applyWorkspaceProposal.

ts
type WorkspaceProposalAdoption = (
  options: InitOptions,
  fs: FileSystem,
  transactionOptions?: TransactionOptions,
) => Promise<AdoptionProposal>;

Leaf operations take (options, fs, adoptProject). They do not default adoptProject. Barrel wrappers keep today’s public signatures, including fs = nodeFileSystem, and pass the local adoptProject:

ts
export async function promoteWorkspaceConversationToProposal(
  options,
  fs = nodeFileSystem,
) {
  return promoteWorkspaceConversationToProposalOperation(
    options,
    fs,
    adoptProject,
  );
}

The same pattern applies to review and apply. WorkspaceProposalReviewResult is defined on the leaf and re-exported from the barrel. workspaceProposalPath stays unexported. There is no new package, package.json export, workspace directory barrel, or public dependency-injection callback.

The port does not add an authorization bypass. Callers of @intentloom/application still hit the wrappers, which always pass the existing adoptProject. Tests may pass a substitute only by importing the leaf module directly. That substitute cannot widen the public CLI or package API.

When adoptProject later moves to a module that does not import the barrel (P1K.16), the port can become a direct import and the wrappers can become re-exports. That is not part of P1K.9.

24.4 Dependency direction ​

mermaid
flowchart TB
  cli["CLI workspace-command.ts"]
  barrel["index.ts public wrappers"]
  leaf["workspace/workspace-proposal-lifecycle.ts"]
  port["WorkspaceProposalAdoption port"]
  adopt["adoptProject on index.ts"]
  conv["workspace/workspace-conversation-store.ts"]
  sandbox["security/sandbox-proposal-evaluation.ts"]
  fs["FileSystem"]

  cli --> barrel
  barrel --> leaf
  barrel --> adopt
  leaf --> port
  port -.-> adopt
  leaf --> conv
  leaf --> sandbox
  leaf --> fs
  adopt --> fs
  sandbox --> fs

Source: workspace-proposal-dependencies.mmd.

The leaf may import getWorkspaceConversation from the conversation leaf and evaluateProposalAgainstSandbox from security/sandbox-proposal-evaluation.ts. It must not import ../index.js, @intentloom/application, Neutron modules, or Approved Apply modules.

Import-only SCC membership on this baseline is the Neutron mutation trio ([3]). Re-export-inclusive membership is [4, 27, 3] with the same members as P1K.8, including index.ts inside the 27-file component. The new leaf must stay outside every component. Do not edit quality-exceptions.json.

24.5 Sequence ​

mermaid
sequenceDiagram
  participant Caller
  participant Barrel as index.ts wrapper
  participant Leaf as proposal lifecycle leaf
  participant Conv as conversation store
  participant Adopt as adoptProject port
  participant FS as FileSystem
  participant Sandbox as sandbox evaluation

  Caller->>Barrel: promote(options, fs)
  Barrel->>Leaf: promote(options, fs, adoptProject)
  Leaf->>Conv: getWorkspaceConversation
  alt conversation missing
    Leaf-->>Caller: throw Workspace conversation id not found
  else conversation exists
    Leaf->>Adopt: profile generic, adapters codex, dryRun true
    Note over Leaf: workspaceProposalPath runs after adoption
    alt proposal path escapes the root
      Leaf-->>Caller: throw path traversal after dry-run adoption
    else path stays inside the root
      Leaf->>FS: exists parent, mkdir if absent, write proposal JSON
      Leaf-->>Caller: AdoptionProposal
    end
  end

  Caller->>Barrel: review(options, fs)
  Barrel->>Leaf: review(options, fs, adoptProject)
  Note over Leaf: workspaceProposalPath runs before exists
  alt proposal path escapes the root
    Leaf-->>Caller: throw path traversal before read or adoption
  else path stays inside the root
    Leaf->>FS: exists proposal path
    alt file exists
      Leaf->>FS: read and JSON.parse
    else file missing
      Leaf->>Adopt: same dryRun true adoption
    end
    Leaf->>Sandbox: changes from item paths, root, projectId = proposalId
    Note over Leaf: policyPath is accepted and unused
    Leaf-->>Caller: readyToApply equals sandbox.allowed
  end

  Caller->>Barrel: apply(options, fs)
  Barrel->>Leaf: apply(options, fs, adoptProject)
  Note over Leaf: does not call workspaceProposalPath or inside
  alt approvedBy missing or blank after trim
    Leaf-->>Caller: throw human approval required
  else non-blank approvedBy
    Note over Leaf: proposalId and planFile are not read
    Note over Leaf: stored proposal and readyToApply are not read
    Leaf->>Adopt: dryRun defaults to false
    Leaf-->>Caller: AdoptionProposal
  end

Source: workspace-proposal-sequence.mmd.

24.6 Security and trust ​

Three classes of statement are kept separate.

Verified today

  • Promote proves only that a conversation record loaded. It then stores a dry-run adoption proposal. Creating that file is not permission to mutate the project.
  • Review reports sandbox allowed as readyToApply. A denied review is a report. Apply does not consult it.
  • Apply checks that approvedBy is non-blank after trim, then runs adoption with dryRun defaulting to false. The string is an operator label, not a cryptographic grant and not an ADR-0053 capability.
  • ADR-0053 requires plan digest, expiry, project-state digest, and evaluateApprovedApplyPlan before mutation. This workspace API does not call that gate and does not provide atomic rollback, transaction binding, or fail-closed plan identity.

Preserve in P1K.9

  • The three behaviors above, including the unused policyPath, proposalId, and planFile fields, and the fact that apply ignores readyToApply.

Future Design First, not this slice

  • Binding apply to the stored proposal, honoring readyToApply, forwarding policyPath, or routing workspace apply through ADR-0053. Any of those changes behavior and needs its own design review.

No invariant in this extraction requires a behavior change. If implementation cannot keep apply off the Approved Apply engine without a code change, stop and report a blocker.

24.7 Error and persistence matrix ​

ConditionOperationCurrent resultPersistence
Proposal id escapes the root (inside)promotethrows path traversal: only after the conversation load and dry-run adoptProject return, and before fs.existsno proposal write; dry-run adoption already ran
Proposal id escapes the root (inside)reviewthrows path traversal: when resolving the path, before fs.exists, read, or the adoption fallbackno proposal write
Proposal id that would escape the rootapplynot checked. Apply does not call workspaceProposalPath or inside()no proposal write from this function
Conversation id escapes root (inside)promotethrows path traversal: during workspaceConversationPath, before exists or readno proposal write
Conversation file absent (exists false)promotegetWorkspaceConversation returns null; promote throws Workspace conversation ${id} not foundno proposal write
Conversation fs.read fails (caught)promoteswallowed in getWorkspaceConversation; promote throws the not-found errorno proposal write
Conversation JSON parse fails (caught)promotesame as read failure: null, then not-found errorno proposal write
Conversation record validation fails (caught)promotesame: null, then not-found errorno proposal write
Conversation fs.exists throwspromotepropagates (outside the catch in getWorkspaceConversation)no proposal write
fs.exists throws on proposal pathpromote, reviewpropagatesno new write from this function
adoptProject throwspromotepropagates before writeno proposal file from this function
Parent mkdir throwspromotepropagates after dry-run adoptionproposal file absent
Proposal write throwspromotepropagatespartial file only if the filesystem wrote before failing; this function does not roll back
Proposal JSON parse throwsreviewpropagatesno write
Stored JSON has no itemsreviewthrows when mapping pathsno write
Proposal file absentreviewdry-run adoptProject fallbackfallback is not written
Sandbox evaluation throwsreviewpropagatesno write
approvedBy missing or blankapplythrows the approval error before adoptionno write in this function
adoptProject throwsapplypropagatesmutation effects are whatever adoptProject already performed; this function adds no rollback
dryRun: trueapplyadoption dry-runno project mutation beyond what dry-run adoption already does
dryRun omittedapplytreated as falsemutating adoption, still not ADR-0053

No new retries, caches, swallowed errors, or transactions.

24.8 Alternatives ​

OptionResult
Leave the three operations on index.tsNo cycle, but the barrel keeps proposal persistence and the P1K size gate stays missed.
Leaf imports adoptProject from index.tsRe-export cycle as soon as the barrel exports the leaf. Rejected.
Leaf takes WorkspaceProposalAdoption from the barrel wrapperPreserves public signatures, avoids the cycle, and does not add a public injector. Selected.
Public dispatcher or executeApprovedApplyPlan inside applyChanges authorization and mutation. Rejected for P1K.9.

24.9 Implementation test plan ​

The implementation PR adds characterization tests before moving production code, then structure and port tests after the leaf exists. Do not add those tests in this design PR.

Stage A — Before extraction (baseline characterization) ​

Characterize the three public operations only through the current @intentloom/application package API and existing filesystem or test seams (memory filesystem, integration fixtures, CLI tests where applicable).

  • Use observable behavior: public return values, thrown error messages and types, bytes on disk, and sandbox side effects.
  • Do not introduce production dependency injection, optional callbacks, or other hooks solely to enable baseline characterization.
  • Baseline characterization must pass on main-equivalent behavior before any proposal lifecycle bodies move out of index.ts.

Suggested file: tests/workspace-proposal-p1k9-characterization.test.ts.

Required Stage A cases:

  • Promote succeeds and writes formatted JSON with a trailing newline.
  • Conversation absent (exists false): promote throws the exact not-found error and writes nothing.
  • Conversation file present but malformed JSON or invalid record: promote throws the same not-found error (not a parse or validation error at the promote boundary).
  • Conversation fs.read failure: the file exists, read throws, and promote throws the exact Workspace conversation ${conversationId} not found error and writes nothing. Observe this through the public package API and an existing filesystem seam. Do not add a production test hook to force the failure.
  • Conversation id path traversal: path traversal: propagates from promote (before not-found).
  • Conversation fs.exists failure: propagates through promote.
  • Supplied proposalId and generated prop-${Date.now()} ids.
  • Observable adoption outcome on promote: persisted bytes are the formatted dry-run AdoptionProposal, not the conversation record. AdoptionProposal does not expose top-level profile, adapters, or dryRun; assert applied: false, applicationStatus: "not-requested", transactionOutcome: null, and exact JSON with trailing newline. Exact internal adoptProject argument lists and invocation ordering belong in Stage B port tests when public seams cannot observe the call.
  • Directory is created only when absent.
  • Review of an existing file uses those bytes and does not call adoption.
  • Review of a missing file calls dry-run adoption and does not write it.
  • Sandbox changes are { type: "modify", path } for each item path, and projectId is the proposal id.
  • readyToApply follows allowed for both true and false.
  • Passing policyPath does not change the sandbox call.
  • Malformed proposal JSON and exists failures propagate.
  • Blank and whitespace approvedBy throw the exact approval error.
  • Apply with dryRun: true and with dryRun omitted (false).
  • proposalId and planFile do not select a file or plan.
  • Filesystem and adoption failures propagate.
  • Promote path traversal throws only after conversation retrieval and dry-run adoption, and does not write the proposal file.
  • Review path traversal throws before exists, read, and adoption.
  • Apply does not throw a proposal-path traversal error. A traversal-shaped proposalId still reaches the approval check and adoptProject.
  • CLI JSON and text output and exit codes stay as in tests/cli-workspace.test.ts (promote 0, review 0 or 3, apply approval failure).

Existing references: tests/workspace-apply.test.ts, tests/cli-workspace.test.ts, tests/workspace-agent.test.ts.

Stage B — After extraction (leaf and adoption port) ​

Once workspace-proposal-lifecycle.ts exists, add tests that import the leaf operations with a mock WorkspaceProposalAdoption port (not a new public API). Do not require a production callback or other test hook before extraction. Stage A stays on the public package API and existing filesystem seams.

When exact adoption arguments or invocation ordering cannot be asserted through those baseline seams, Stage B port tests are the place that verifies them:

  • Assert exact adoption arguments (profile: "generic", adapters: ["codex"], dryRun: true for promote and the review fallback; apply dryRun as passed), call count, and invocation ordering for promote, review fallback, and apply.
  • Assert adoption errors propagate unchanged through wrappers.
  • Assert public barrel wrappers preserve current signatures, default nodeFileSystem, and observable compatibility with Stage A baselines.
  • Do not expose an additional public callback or production test hook.

Structure tests must show one implementation of each moved body, a private path helper, no workspace/index.ts, no new export map, no leaf import of index.js, unchanged SCC member sets, and unchanged quality-exceptions.json.

Public wrappers are not the same function references as the leaf operations, because each wrapper injects the existing adoptProject. Stage B structure and compatibility assertions include:

  • The public names promoteWorkspaceConversationToProposal, reviewWorkspaceProposal, and applyWorkspaceProposal stay exported from @intentloom/application with the current options and the default FileSystem.
  • Each wrapper passes the caller options, the filesystem, and the existing adoptProject function into its leaf operation.
  • Return values, error messages, and observable behavior stay compatible with Stage A.
  • WorkspaceProposalReviewResult stays a public type.
  • The internal adoption-port operations are not new package-level APIs.
  • The extraction adds no import or re-export cycle. The leaf stays outside the existing SCC member sets.

24.10 Design First acceptance matrix ​

Implementation starts only after a maintainer checks every row. PR #643 implementation began on 2026-11-26 before this matrix was recorded in Git; that was a Design First sequence deviation. Independent review accepted the extraction architecture; explicit maintainer sign-off for every row below is still required before merge and must be recorded in the pull request and DUTY_WATCH.md — not backdated.

#Maintainer confirmsRequired
1Section 24 matches code on d8c5f2cyes
2Public signatures and CLI error strings stayyes
3adoptProject is an internal port, not a public optionyes
4Apply stays off ADR-0053 and ignores readyToApplyyes
5Unused policyPath, planFile, and apply proposalId stay unusedyes
6Leaf stays outside SCC sets [3] and [4, 27, 3]yes
7Characterization tests land before the moveyes
8No Neutron, Undo, or quality-exception editsyes

24.11 Non-goals ​

P1K.10 and later slices, moving sync or interactive workspace state, Approved Apply integration, sandbox rule changes, protocol changes, package export maps, Undo U4, and Desktop Undo U5.

25. P1K.10 project root and timeline — Design First gate ​

Status: accepted 2026-11-28 13:20 Europe/Berlin, after PR #644 merged. Parent design PR #627 remains the architectural roadmap. This section records behavior verified on main at 800716340e22a92240ab5d769f5e347f0363c1e4 (P1K.9 implementation, PR #643) and the extraction contract for slice P1K.10 only. The Project Owner accepted every row in section 25.17 at that time. GitHub reviews on PR #644 were empty when it merged at 2026-11-28 13:15 Europe/Berlin (26dfe51e56f8b37972dd167e71c6fa55e4920f85). This status does not rewrite that GitHub record. A separate implementation task was authorized only after a later main verification succeeded. Documentation run 46143717431 failed at Pages deploy after a successful VitePress build. That historical result stays a failure. This section does not change application, daemon, CLI, or evidence-git runtime behavior, and it does not authorize Neutron changes. Implementation follows main 6fe72e99f53be471d1941032c74ea37c8f8c2a41 (PR #645), whose Documentation, CodeQL, and Compatibility checks succeeded. Run 46143717431 on 26dfe51 was not rerun.

The implementation is merged as PR #646 at 2026-11-28 15:13 Europe/Berlin (fecace86f4baf4a532d4cdd358f2cfc1e4c74cf3). Documentation, CodeQL, and Compatibility on that merge commit succeeded. At 2026-11-28 15:14 Europe/Berlin the Project Owner issued a later statement: As Project Owner, I accept the successful verification of current main 6fe72e99f53be471d1941032c74ea37c8f8c2a41 instead of rechecking the previous SHA 26dfe51. The historical GitHub Pages failure stays in the documentation. I authorize the P1K.10 implementation according to the approved Section 25.17. Prepare the next agent prompt.

That statement accepts the 6fe72e9 verification in place of a Documentation rerun on 26dfe51 and authorizes this slice under section 25.17. It is one minute after the merge timestamp. This section does not backdate it and does not treat it as a GitHub review on PR #644. Historical run 46143717431 stays a failure. No confirmed internal GitHub root cause is claimed.

25.1 Problem and scope ​

P1K.10 moves canonical project-root validation and the release timeline builder out of packages/application/src/index.ts into packages/application/src/project-lifecycle/project-root.ts.

NameTodayAfter extraction
ProjectRootErrorpublic classpublic class on the leaf, re-exported
assertCanonicalProjectRootpublic functionpublic function on the leaf, re-exported
ProjectTimelineOptionspublic interfacepublic type on the leaf, re-exported
ProjectTimelinepublic interfacepublic type on the leaf, re-exported
timelineProjectpublic functionpublic function on the leaf, re-exported

There are no forwarding wrappers. The barrel re-exports the leaf bindings, so public class and function identity stay the leaf values (instanceof and function identity match the owning module).

getInteractiveWorkspaceState still passes the local timelineProject binding into assembleInteractiveWorkspaceState. The barrel therefore imports the leaf symbols and re-exports them; it does not drop the local name.

resolve from node:path stays imported on the barrel because planPackUpdate still calls it. Do not remove unrelated imports.

Proposed barrel arrangement (illustrative; implementation must match remaining barrel composition exactly aside from this move):

ts
import { resolve } from "node:path";
import {
  assertCanonicalProjectRoot,
  ProjectRootError,
  timelineProject,
} from "./project-lifecycle/project-root.js";
import type {
  ProjectTimeline,
  ProjectTimelineOptions,
} from "./project-lifecycle/project-root.js";

export { assertCanonicalProjectRoot, ProjectRootError, timelineProject };
export type { ProjectTimeline, ProjectTimelineOptions };

export async function getInteractiveWorkspaceState(
  options,
  fs = nodeFileSystem,
) {
  return assembleInteractiveWorkspaceState(options, fs, {
    inspectProject,
    doctorProject,
    diffProject,
    timelineProject,
  });
}

Measured on this baseline with measureProductionSource: index.ts is 793 effective and 831 physical lines. The contiguous root and timeline block (lines 289–348) measures 56 effective and 60 physical lines. The parent roadmap forecast removes about 51 effective lines from the barrel after re-export glue. Post-P1K.10 forecast: about 742 effective lines on the central estimate; the phased table row 718 remains the rounded running estimate from section 15. Re-measure during the implementation PR. Do not present forecasts as observed results.

Preferred file budget is 250 effective lines; hard limit is 400.

Branch name. This Design PR uses cursor/docs-p1k10-project-root-timeline-design-e067. AGENTS.md forbids cursor/ prefixes. The published branch and PR stay as-is unless the owner authorizes a rename. Later work uses an approved prefix such as docs/.

25.2 Verified current behavior ​

Verified by reading packages/application/src/index.ts, packages/application/src/host-file-system.ts, packages/evidence-git/src/index.ts, packages/daemon/src/daemon-canonical-root.ts, packages/daemon/src/bin.ts, packages/cli/src/timeline-command.ts, and consumer imports on 8007163.

assertCanonicalProjectRoot ​

  1. const canonicalRoot = resolve(root) (node:path). Relative inputs are resolved against the process current working directory. This is lexical normalization, not realpath.
  2. await fs.exists(canonicalRoot). When the result is false, throw ProjectRootError("invalid_root", "project root does not exist")immediately. isSymbolicLink is not called on this branch.
  3. When exists is true, await fs.isSymbolicLink(canonicalRoot). When true, throw ProjectRootError("stale_root", "project root is a symbolic link and is not stable").
  4. Otherwise return canonicalRoot.

fs defaults to nodeFileSystem. ProjectRootError.name is "ProjectRootError". clientErrorCode is "invalid_root" | "stale_root". The class extends Error. Neither the function nor nodeFileSystem catches errors thrown by a custom FileSystem.

Path cases (current implementation):

CaseWhat happens
Lexically resolved relative pathresolve against cwd; then the checks above
Existing directoryexists true, not a symlink → returned path
Existing regular fileexists true, not a symlink → accepted (no directory check)
Direct symlink whose target existsnodeFileSystem.exists uses stat (follows) so true; isSymbolicLink uses lstat so true → stale_root
Dangling symlinkstat fails, exists returns false → invalid_root; isSymbolicLink not called
Symlink in a parent segment, leaf is not a symlinkresolve does not expand the parent; lstat of the leaf is not a symlink → accepted lexical path
Missing pathexists false → invalid_root; isSymbolicLink not called
Custom exists throwserror propagates; isSymbolicLink not called
Custom isSymbolicLink throws after exists trueerror propagates
nodeFileSystem.exists I/O errorcaught inside exists, returns false → invalid_root
nodeFileSystem.isSymbolicLink I/O errorcaught inside isSymbolicLink, returns false → path accepted if exists was true

timelineProject ​

  1. assertCanonicalProjectRoot(options.root) with the defaultnodeFileSystem. Callers cannot pass a custom filesystem through timelineProject.
  2. collectGitEvidence with root set to the validated path. limit, timeoutMs, maxOutputBytes, and run are copied only when !== undefined.
  3. Return { root, ...createReleaseTimeline(options.caseId, evidence), diagnostics: [...evidence.diagnostics] }.

Evidence-git (verified in packages/evidence-git/src/index.ts):

  • Defaults inside collectGitEvidence when a property is omitted: limit 50 (clamped 1–500), timeout 5000 ms (clamped 100–30000), max output 512 KiB (clamped 4096–4 MiB), run defaults to the built-in git runner.
  • The try wraps the runner call and stdout parsing. A throw inside that try returns status: "unavailable" and diagnostics: ["git-unavailable"]. That is not a claim that every failure outside that try becomes unavailable evidence.
  • limit-reached sets diagnostics: ["commit-limit-reached"] and createReleaseTimeline maps that to quality: "bounded" and finding evidence-bounded. available maps to quality: "complete" and empty findings. unavailable maps to quality: "unavailable" and finding evidence-unavailable.
  • Events are commits sorted by timestamp, then commit id.
  • A GitRunner observes file, args, { cwd, timeout, maxBuffer }. It does not show whether optional properties were present on the object timelineProject passed to collectGitEvidence. Exact omission needs a test-level module mock of @intentloom/evidence-git (or an equivalent existing seam). Do not add a production injection callback.

timelineProject does not write under root.

Two timeline entry points (different root checks) ​

  • Library and daemon RPC (packages/daemon/src/bin.ts) call timelineProject, which runs assertCanonicalProjectRoot first.
  • Standalone CLI (packages/cli/src/timeline-command.ts) calls collectGitEvidence and createReleaseTimeline directly. It does not call assertCanonicalProjectRoot. P1K.10 does not retarget the CLI. These paths do not share root-validation semantics.

Daemon JSON-RPC handlers that call assertCanonicalProjectRoot may throw ProjectRootError for a relative path before the application function, with message project root must be an absolute path. That is a handler pre-check, not DaemonRootError, and not collectGitEvidence. packages/daemon/src/daemon-canonical-root.ts uses DaemonRootError and realpath (section 25.9). Do not conflate those three error sites.

25.3 Proposed module ownership ​

Target: packages/application/src/project-lifecycle/project-root.ts.

The directory already owns project lifecycle operations. No project-lifecycle/index.ts. No new package.json exports.

25.4 Public contracts ​

All five names stay on @intentloom/application with the same signatures. Re-exports preserve class and function identity. ProjectRootError must keep working for instanceof in specialized-pack-external-apply.ts.

Protocol ProjectTimelineParams / ProjectTimelineResult stay in @intentloom/protocol.

25.5 Dependency direction ​

mermaid
flowchart TB
  cli_timeline["CLI timeline-command.ts"]
  daemon_rpc["daemon bin.ts timeline RPC"]
  desktop["Desktop client"]
  protocol["protocol ProjectTimeline RPC"]
  neutron["neutron-tool-dispatch.ts"]
  workspace["getInteractiveWorkspaceState"]
  eq_apply["specialized-pack-external-apply.ts"]
  eq_daemon["daemon quality and specialized-pack handlers"]
  barrel["index.ts re-exports plus local binding"]
  leaf["project-lifecycle/project-root.ts"]
  fs["../host-file-system.js"]
  evidence["@intentloom/evidence-git"]
  path["node:path resolve"]
  daemon_root["daemon-canonical-root.ts DaemonRootError"]

  desktop --> protocol
  protocol --> daemon_rpc
  daemon_rpc --> barrel
  neutron --> barrel
  workspace --> barrel
  eq_apply --> barrel
  eq_daemon --> barrel
  eq_daemon --> daemon_root
  barrel --> leaf
  leaf --> fs
  leaf --> evidence
  leaf --> path
  cli_timeline --> evidence

Source: project-root-timeline-dependencies.mmd.

Desktop reaches timeline data through the daemon and protocol. It does not import @intentloom/application for this flow. The CLI timeline edge is a source import of evidence-git, not the same runtime path as daemon RPC. Edges into the barrel are source imports. Re-exports are not extra runtime wrapper calls.

Allowed leaf imports:

  • node:path (resolve)
  • ../host-file-system.js (FileSystem, nodeFileSystem)
  • @intentloom/evidence-git (collectGitEvidence, createReleaseTimeline, type GitRunner, type ReleaseTimeline)

Forbidden leaf imports: ../index.js, @intentloom/application, daemon internals, Engineering Quality modules, Neutron, Approved Apply.

specialized-pack-external-apply.ts keeps from "../index.js" until P1K.15.

25.6 Consumer analysis ​

ConsumerImportSymbolsNotes
packages/daemon/src/bin.ts@intentloom/applicationtimelineProjectRPC; forwards limit, timeoutMs, maxOutputBytes
packages/daemon/src/engineering-quality-handlers.ts@intentloom/applicationassertCanonicalProjectRoot, ProjectRootErrorAbsolute-path pre-check, then application check
packages/daemon/src/specialized-pack-handlers.tssamesamesame pattern
packages/daemon/src/specialized-pack-external-handlers.tssamesamesame pattern
specialized-pack-external-apply.ts../index.jsbothinstanceof; retarget deferred to P1K.15
neutron-tool-dispatch.ts../../index.jstimelineProjectoptional run, limit
index.ts getInteractiveWorkspaceStatelocal bindingtimelineProjectport into the read model
interactive-workspace-read-model.tsinjected portshape onlyno direct import of the function
packages/cli/src/timeline-command.ts@intentloom/evidence-gitcollect + createno application root check
Desktop timeline UIdaemon client + protocolProjectTimelineResultno application barrel import
tests/project-timeline.test.tsapplication index.jstimelineProjectstub run

No production consumer retarget in the design task.

25.7 Error and failure matrix ​

ConditionassertCanonicalProjectRoottimelineProjectcollectGitEvidence
Missing rootinvalid_root after exists false; no isSymbolicLinksame, before Gitnot called
Dangling symlink (nodeFileSystem)exists false → invalid_rootsamenot called
Direct symlink to an existing targetstale_rootsamenot called
Existing directory or regular filereturns resolve resultproceedsrunner cwd is that path
Parent symlink, leaf not a symlinkreturns lexical pathproceedsrunner cwd is that path
Relative pathresolve against cwd, then the checkssamenot called if validation throws
Custom exists throwspropagatesno filesystem argument; default nodeFileSystem onlynot called
Custom isSymbolicLink throwspropagates after exists trueno filesystem argument; default nodeFileSystem onlynot called
nodeFileSystem.exists swallows I/Ofalse → invalid_rootsamenot called
nodeFileSystem.isSymbolicLink swallows I/Ofalse → accept if existsmay proceedmay run
Runner or parse throw inside evidence try—quality: "unavailable", diagnostics include git-unavailablecaught in that try only
Commit limit reached—quality: "bounded", finding evidence-boundeddiagnostic commit-limit-reached
Evidence available—quality: "complete"empty diagnostics

Custom FileSystem error propagation in this table applies to assertCanonicalProjectRoot, which accepts an optional FileSystem. It does not describe an injectable filesystem argument on timelineProject. timelineProject calls assertCanonicalProjectRoot(options.root) with the default nodeFileSystem only. A custom filesystem throw is reached by calling assertCanonicalProjectRoot directly.

Daemon handler absolute-path failures and DaemonRootError are notcollectGitEvidence outcomes. See section 25.2 and 25.9.

25.8 Filesystem and Git evidence flows ​

mermaid
sequenceDiagram
  participant Caller
  participant Leaf as project-root.ts
  participant FS as FileSystem
  participant Git as evidence-git

  Caller->>Leaf: timelineProject(options)
  Leaf->>Leaf: resolve(root)
  Leaf->>FS: exists(resolved)
  FS-->>Leaf: exists result
  alt exists is false
    Leaf-->>Caller: ProjectRootError invalid_root
  else exists is true
    Leaf->>FS: isSymbolicLink(resolved)
    FS-->>Leaf: symlink result
    alt isSymbolicLink is true
      Leaf-->>Caller: ProjectRootError stale_root
    else path accepted
      Leaf->>Git: collectGitEvidence
      Git-->>Leaf: GitEvidenceResult
      Leaf->>Git: createReleaseTimeline(caseId, evidence)
      Git-->>Leaf: ReleaseTimeline
      Leaf-->>Caller: ProjectTimeline diagnostics copy
    end
  end

Source: project-root-timeline-sequence.mmd.

The public timelineProject is the leaf function after a re-export. The diagram does not insert a barrel wrapper hop. Git runs only after validation returns. No realpath, directory check, or extra filesystem calls.

25.9 Daemon canonical root boundary (do not merge) ​

canonicalProjectRoot in daemon-canonical-root.ts requires an absolute path, lstat, a real directory, symlink rejection, and realpath. It throws DaemonRootError. Application assertCanonicalProjectRoot does none of the absolute, directory, or realpath steps. Do not merge the implementations or replace DaemonRootError with ProjectRootError.

25.10 Security and trust boundaries ​

Root validation is a host filesystem gate before read-only git evidence (trust: "local-observed-unverified"). Preserving the current symlink check is not a new authorization control and is not a claim of complete assurance. No new network or telemetry. Accessibility, product discovery, and AI evaluation are NOT APPLICABLE.

25.11 Alternatives, planning, and RAID ​

AlternativeDecision
Leave the symbols on index.tsRejected
Split timeline into a second fileRejected for this slice
project-lifecycle directory barrelRejected
Realpath or directory hardeningRejected for P1K.10
Retarget Engineering Quality imports nowRejected; P1K.15
Merge daemon and application root checksRejected
Fix the Windows durable-claim observation in this PRRejected; out of scope (see Duty Watch)

SWOT: Strengths — one leaf, public re-exports, existing timeline test. Weaknesses — CLI bypasses root validation; sparse root tests; Windows claim observation recorded but not fixed here. Opportunities — Stage A before the move. Threats — class-identity break if wrappers are introduced; scope drift into Neutron.

RACI: Responsible — design author; Accountable — Project Owner; Consulted — independent reviewer; Informed — Duty Watch readers.

RAID:

  • Risk — repeating the P1K.9 sequence (implementation before owner matrix). Mitigation — section 25.13 order; Stage A only after design merge and a separate implementation authorization.
  • Risk — commit 2633821 changed Neutron production code inside a documentation PR. Mitigation — that file is restored to main in the corrective commit; the Windows observation is recorded in DUTY_WATCH.md and is not authorized for implementation here.
  • Assumption — evidence-git defaults and catch scope stay as read on 8007163.
  • Issue — P1K.9 section 24.10 owner matrix was not recorded when PR #643 merged. Historical exception stands. It does not approve section 25.17.
  • Dependency — P1K.9 is on main at 8007163.

Design First estimates (not measured wall-clock for this correction pass):

MeasureEstimate
Human active effort3–10 minutes
AI agent execution effort40–75 minutes
Calendar duration1–2 hours

This correction pass does not invent an observed duration.

Main verification at 8007163 (current, not historical pending):

WorkflowRunResult
CodeQL46138992949success
Compatibility46138992983success
Documentation46138992947success

25.12 Test strategy ​

No new tests in this Design PR.

Existing coverage: tests/project-timeline.test.ts, tests/cli-timeline.test.ts (CLI path without application root check), tests/daemon-canonical-root.test.ts, tests/daemon.test.ts, tests/daemon-engineering-quality.test.ts, tests/evidence-git.test.ts, tests/workspace-read-model-p1h7.test.ts, architecture structure tests.

Stage A — public API, before extraction ​

  • Missing root: invalid_root, and the test filesystem shows exists only (isSymbolicLink not called).
  • Existing root: exists then isSymbolicLink, same path argument, same filesystem object identity where the spy can see it.
  • Custom filesystem throws from exists and from isSymbolicLink propagate.
  • Dangling symlink vs direct symlink (portable fixture; skip with a stated reason only where the platform cannot create the link).
  • Relative root via a path argument resolve can see without changing process.cwd when a lexical expectation can be stated from resolve itself.
  • Regular file accepted; directory accepted; parent-symlink leaf documented.
  • nodeFileSystem swallow vs custom throw, as in section 25.2.
  • Exact ProjectRootError name, message, clientErrorCode, and instanceof.
  • timelineProject does not call GitRunner when root validation throws.
  • Evidence defaults and explicit limit/timeout/maxBuffer visible on GitRunner.
  • Exact property omission of the object passed to collectGitEvidence via a test-level module mock, not a new production callback.
  • Complete, bounded, and unavailable timeline output; event order; diagnostics copy; read-only directory listing.
  • CLI and daemon compatibility: CLI still skips assertCanonicalProjectRoot; daemon RPC still uses timelineProject.

Stage B — after extraction ​

  • One implementation of each moved declaration.
  • Barrel re-export identity equals the leaf (ProjectRootError, assertCanonicalProjectRoot, timelineProject).
  • Public types still exported.
  • No leaf import of index.js.
  • No new package exports or wrappers.
  • SCC sets stay [3] and [4, 27, 3].
  • measureProductionSource recorded from the implementation tree.
  • quality-exceptions.json unchanged.
  • Local timelineProject binding still passed by getInteractiveWorkspaceState.

25.13 Mandatory sequence ​

  1. Proposed system design (this section).
  2. Independent design review.
  3. Explicit Project Owner acceptance of section 25.17 on this Design PR or another genuine dated approval source. Do not backdate it.
  4. Owner merges the Design PR.
  5. Main verification of that merge.
  6. Separate implementation authorization that references the existing approval. The implementation PR does not collect the initial design approval.
  7. Stage A characterization tests.
  8. Production extraction.
  9. Stage B architecture tests.
  10. Independent implementation review.

Do not start P1K.11 or later, Engineering Quality retarget, or Neutron edits in the implementation PR.

Recorded order. Steps 2 and 4 completed before step 3. PR #644 merged at 2026-11-28 13:15 Europe/Berlin with no GitHub review. Step 3 is the Project Owner statement at 2026-11-28 13:20 Europe/Berlin, recorded in section 25.17 and DUTY_WATCH.md. It is not a backdated GitHub approval. Step 6 in that statement stays inactive until step 5 succeeds. Step 5 completed for main 6fe72e99f53be471d1941032c74ea37c8f8c2a41: Documentation, CodeQL, and Compatibility succeeded. The earlier Documentation run 46143717431 on 26dfe51 was not rerun. Step 6 is the separate implementation that cites this section. That implementation merged as PR #646 at 2026-11-28 15:13 Europe/Berlin. The 15:14 Europe/Berlin owner statement recorded above authorizes that same slice. The statement time is after the merge.

25.14 Architecture metrics ​

MetricObserved @ 8007163Forecast after P1K.10
index.ts effective793about 742 central; table row 718
index.ts physical831re-measure
Moved block56 effectiveleaf plus re-export glue
Import-only SCC[3]unchanged
Re-export SCC[4, 27, 3]unchanged

The leaf stays outside those components. Do not edit quality-exceptions.json.

25.15 Definition of Done (implementation, only after section 25.13 steps 1–6) ​

  • [x] Implementation PR links the dated section 25.17 approval
  • [x] Stage A landed before the production move
  • [x] Stage B green
  • [x] pnpm verify PASS
  • [x] Measured lines and SCC recorded
  • [x] PROJECT_STATE.md and DUTY_WATCH.md updated
  • [x] No consumer retarget beyond re-exports and the local timeline binding
  • [x] daemon-canonical-root.ts untouched

25.16 Non-goals ​

P1K.11 and later, CLI timeline retarget, merging daemon canonicalization, realpath or directory hardening, Engineering Quality import retarget, package export changes, protocol changes, Undo U4/U5, Neutron behavior changes, evidence-git changes, and quality-exception edits.

The Windows Node 24 observation on lets only one concurrent caller own the shared durable directory is recorded in DUTY_WATCH.md. This design does not authorize a Neutron fix.

25.17 Design First acceptance matrix ​

The design required every row to be accepted on PR #644, or in another genuine dated source, before merge. PR #644 merged at 2026-11-28 13:15 Europe/Berlin (26dfe51e56f8b37972dd167e71c6fa55e4920f85). Its GitHub review list was empty. This section does not add or backdate a GitHub approval review.

On 2026-11-28 13:20 Europe/Berlin the Project Owner accepted all ten rows. That statement is the dated source. The implementation pull request cites this section and DUTY_WATCH.md. It does not replace them.

The same statement authorizes a separate P1K.10 implementation task only after main verification of 26dfe51 succeeds. It does not authorize Neutron changes. That verification had not succeeded when this acceptance was recorded.

#Maintainer confirmsRequired
1Section 25 matches code on 8007163yes
2Root-check order, messages, and codes in section 25.2 stayyes
3Timeline and evidence-git behavior in section 25.2 stayyes
4Public class, function, and type compatibility via re-export identityyes
5ProjectRootError identity for existing instanceof consumersyes
6Daemon canonical root stays separate from application root checksyes
7Engineering Quality barrel import stays until P1K.15yes
8Module path and dependency direction in section 25.5yes
9Leaf stays outside SCC sets [3] and [4, 27, 3]yes
10Stage A tests precede production extractionyes

All ten rows: accepted by the Project Owner at 2026-11-28 13:20 Europe/Berlin. The later statement at 2026-11-28 15:14 Europe/Berlin, quoted in the section 25 status, accepts main verification of 6fe72e9 and authorizes the implementation. It does not replace these ten rows and it is not backdated onto PR #644.

P1K.9 PR #643 merged without a recorded section 24.10 owner matrix. That exception is unchanged and does not approve this matrix.

Each fenced diagram in this file is the same text as its .mmd source. Mermaid is the only diagram format. Excalidraw and draw.io are not used because these graphs are dependency and sequence records, not sketches that need a freehand canvas.

26. P1K.11 Feature Planning Extraction — Design First gate ​

Status: accepted 2026-11-29 13:31:01 Europe/Berlin, before PR #649 merged. Parent design PR #627 remains the architectural roadmap. This section records behavior verified on main at 39ee6e847c3c0053710f9726519b1769b458bd80 (P1K.10 test-quality closure, PR #648) and the extraction contract for slice P1K.11 only. The design text did not accept itself. A pull request merge, green CI, or the parent roadmap does not accept the matrix in section 26.17.

The Project Owner accepted all eleven section 26.17 rows at 2026-11-29 13:31:01 Europe/Berlin in PR #649 comment 7255868443, reviewing design HEAD 2efd8b8ef9c5bb5afde0d92ca800ceb07708bbff. That comment authorizes the design merge and says implementation needs a separate authorization after successful main verification. PR #649 merged at 2026-11-29 13:31:23 Europe/Berlin (c72168aacb806acca05270d4720d45d7586a1b4e). The merge tree is identical to that design HEAD. GitHub reviews on PR #649 were empty. This record does not add or backdate a review.

Main verification of c72168a succeeded. Documentation run 46262718191 succeeded at 2026-11-29 13:32 Europe/Berlin. CodeQL run 46262718240 succeeded at 2026-11-29 13:33 Europe/Berlin. Compatibility run 46262718209 succeeded at 2026-11-29 13:39 Europe/Berlin. All six jobs succeeded, including windows-latest Node 22 and Node 24. pnpm test succeeded on both Windows jobs.

On 2026-11-29 13:46 Europe/Berlin the Project Owner separately authorized P1K.11 implementation according to the approved section 26.17. That statement is later than the design acceptance and the main verification. It is not inferred from the design comment or the merge, and it is not backdated. Stage A is commit 081e22776fe2e0b15876afb61f8c2119de383032, recorded before the production move.

P1K.9 and P1K.10 process deviations stay historical facts in sections 24 and 25 and in DUTY_WATCH.md. This section does not repeat them and does not treat them as approval of P1K.11.

26.1 Problem and scope ​

P1K.11 moves only planFeature from packages/application/src/index.ts into packages/application/src/feature-intent/plan-feature.ts, then re-exports that function from the public application barrel.

The move is behavior-preserving. The function stays a deterministic stub. It keeps building one feature brief and one context pack, optionally validating both, and returning one formatted JSON string.

ItemThis slice
ResponsibilityplanFeature only
Targetpackages/application/src/feature-intent/plan-feature.ts
Public surfacedirect re-export from index.ts
Error classexisting ArtifactValidationFailure
Compatibility tests already on maintests/cli-plan.test.ts
Estimated body removalabout 66 effective lines
Estimated glueabout 3 effective lines
Estimated net barrel reductionabout 63 effective lines
Cyclic componentsunchanged

Out of this slice: planPackUpdate, Feature Intent workspace preparation, W10 and W11 behavior, repository analysis, model execution, file persistence, schema changes, CLI quirk fixes, package export changes, and any Neutron, Daemon, or Desktop edit.

26.2 Verified signature and JSON contract ​

Verified from packages/application/src/index.ts lines 367–432 on 39ee6e8, and by executing that function. The temporary Vitest probe was deleted before this design commit. It is not a repository test.

ts
export async function planFeature(
  taskId: string,
  validator?: ArtifactValidator,
): Promise<string>;

The function is async and returns a Promise. The body has no await. A thrown Error or ArtifactValidationFailure rejects that promise. The success value is a string, not an object.

A falsy taskId throws Error("task identifier is required") before either object is built and before any validator call. The guard is if (!taskId). This slice adds no trim, normalization, sanitization, or extra validation.

Executed on Node v22.23.4:

taskIdResult
""throws Error("task identifier is required")
runtime undefinedsame error; the guard is falsy, the type remains string
runtime nullsame error
" "resolves; id and title are one space; path plans/ -context.json
"\t"resolves; the tab character is copied through
"\n"resolves; the newline is copied through
"0"resolves; the identifier is the character zero
"a/b"resolves; path plans/a/b-context.json
"../x"resolves; path plans/../x-context.json
"say \"hi\""resolves; the quote characters stay in the identifier
" spaced "resolves; leading and trailing spaces stay

The returned document has two keys, in this order: featureBrief, then contextPack. Serialization is JSON.stringify({ featureBrief, contextPack }, null, 2). The string has no trailing newline. For task-1 its length is 1210 characters. plan-command.ts writes that string to stdout without adding a newline.

Feature brief fields, in literal order. taskId means the argument unchanged:

FieldValue
schemaVersion"1"
idtaskId
titletaskId
status"draft"
priority"medium"
effort"m"
risk"medium"
impact"To be assessed"
ownerMode"unassigned"
problem"To be defined"
userValue"To be defined"
goal"Create an approved bounded implementation brief"
scope[]
outOfScope[]
acceptanceCriteria["Acceptance criteria must be completed before approval"]
architectureBoundaries[]
reuseCandidates[]
contextPackplans/${taskId}-context.json
allowedFiles[]
forbiddenFiles[]
edgeCases[]
verification["Define proportionate verification before implementation"]
liveVerificationfalse
technicalDebtDecision"none"
stopCondition"Stop before implementation until the brief is approved"

Context pack fields, in literal order:

FieldValue
schemaVersion"1"
taskIdtaskId
mustRead[]
readIfNeeded[]
excluded[]
forbiddenToChange[]
relevantSourceAreas[]
contextMode"minimal"
expansionReasons[]
fileBudget20

fileBudget is the number 20. liveVerification is boolean false. Empty arrays stay empty. The two singleton string arrays stay those exact sentences. No repository inspection, model call, file read, or file write occurs inside the function. The plans/... strings are document metadata.

Exact serialized string for planFeature("task-1"). The fence is text, the same convention docs/designs/p1i3-existing-project-adoption/SYSTEM_DESIGN.md uses for an exact body. A json fence is reformatted by Prettier: the singleton verification array collapses onto one line, and that form is 1198 characters. JSON.stringify(value, null, 2) is 1210 characters and has no trailing newline. The text below is that 1210-character string. Stage A compares it with strict string equality to an expected value built independently of the returned string.

text
{
  "featureBrief": {
    "schemaVersion": "1",
    "id": "task-1",
    "title": "task-1",
    "status": "draft",
    "priority": "medium",
    "effort": "m",
    "risk": "medium",
    "impact": "To be assessed",
    "ownerMode": "unassigned",
    "problem": "To be defined",
    "userValue": "To be defined",
    "goal": "Create an approved bounded implementation brief",
    "scope": [],
    "outOfScope": [],
    "acceptanceCriteria": [
      "Acceptance criteria must be completed before approval"
    ],
    "architectureBoundaries": [],
    "reuseCandidates": [],
    "contextPack": "plans/task-1-context.json",
    "allowedFiles": [],
    "forbiddenFiles": [],
    "edgeCases": [],
    "verification": [
      "Define proportionate verification before implementation"
    ],
    "liveVerification": false,
    "technicalDebtDecision": "none",
    "stopCondition": "Stop before implementation until the brief is approved"
  },
  "contextPack": {
    "schemaVersion": "1",
    "taskId": "task-1",
    "mustRead": [],
    "readIfNeeded": [],
    "excluded": [],
    "forbiddenToChange": [],
    "relevantSourceAreas": [],
    "contextMode": "minimal",
    "expansionReasons": [],
    "fileBudget": 20
  }
}

26.3 Validator behavior and error contract ​

ArtifactValidator is an optional caller-supplied dependency. The barrel imports it as a type from @intentloom/validator and does not re-export that type. packages/validator/src/index.ts defines:

ts
export interface ArtifactValidator {
  validate(input: ArtifactValidationInput): ArtifactValidationResult;
}

validate is synchronous. planFeature does not await it. A returned promise would be an ordinary object whose status is not "invalid". This slice keeps that call shape.

ArtifactValidationResult.status is "valid" or "invalid". The result also carries artifactType, schemaId, schemaVersion, documentPath, structuralErrors, semanticErrors, warnings, and an optional document. planFeature reads only status.

When validator is truthy, the function evaluates this array from left to right:

  1. artifactType: "feature-brief", documentPath: plans/${taskId}.json, format: "json", source: JSON.stringify(featureBrief).
  2. artifactType: "context-pack", documentPath: plans/${taskId}-context.json, format: "json", source: JSON.stringify(contextPack).

Each source is the compact JSON of that artifact alone. It is not the pretty combined document. For task-1 the probe recorded those two argument objects and no other fields (skillPolicy and semanticContext are absent).

Both results are collected before results.filter((result) => result.status === "invalid"), unless a validate call throws. Only "invalid" enters the failure array. A "valid" result is dropped even if warnings is non-empty. Any non-empty invalid array throws new ArtifactValidationFailure(invalid). The filtered array keeps original order and object identity.

packages/application/src/artifact-validation-failure.ts is the only error class:

ts
export class ArtifactValidationFailure extends Error {
  constructor(readonly results: readonly ArtifactValidationResult[]) {
    super("project artifact validation failed");
  }
}

The public barrel export and this class are the same function identity today (tests/project-lifecycle-p1i2.test.ts, and the same comparison in the deleted probe). This slice creates no second error class. The barrel keeps exposing that class.

A throw from validate propagates unchanged. It does not become ArtifactValidationFailure. If the feature-brief call throws, the context-pack call is not reached, because the array element is never evaluated. If the context-pack call throws, the feature-brief call has already returned and that result is discarded with the unfinished array. The probe rejected with the same Error object in both throw cases, and the second-throw case observed both artifact types before the rejection.

With no validator, the if (validator) branch is skipped. Zero validate calls. The function still returns the pretty JSON string.

26.4 Proposed module ownership ​

Target file: packages/application/src/feature-intent/plan-feature.ts.

Leaf imports, and no others:

  • import type { ArtifactValidator } from "@intentloom/validator"
  • import { ArtifactValidationFailure } from "../artifact-validation-failure.js"

The leaf does not import ../index.js or @intentloom/application.

The barrel exposes a direct re-export:

ts
export { planFeature } from "./feature-intent/plan-feature.js";

No forwarding wrapper. Source audit found no composition that wraps planFeature before the CLI calls it.

Import cleanup on index.ts, and nothing else:

  • Delete import type { ArtifactValidator } from "@intentloom/validator". On 39ee6e8 that import is used only by the planFeature signature.
  • After the move, the local ArtifactValidationFailure binding is unused. Replace the value import on line 29 and export { ArtifactValidationFailure } on line 254 with one direct re-export: export { ArtifactValidationFailure } from "./artifact-validation-failure.js". That preserves the class identity tests compare with toBe.

Do not add a package.json export. @intentloom/application keeps "." as ./src/index.ts for this symbol. Do not add feature-intent/index.ts or any other directory barrel. Do not add planFeature to feature-intent-w10.ts.

CODE_QUALITY_STANDARDS.md prefers functions at or below 40 lines and sets a hard limit of 80. measureProductionSource on the current function text reports 66 effective lines and 66 physical lines, with no blank or comment lines. The length is the two object literals. Complexity is the falsy guard, the validator guard, and the invalid-length guard. The function has two parameters. Splitting the literals would be a refactor of the stub. This slice moves the function intact and does not edit quality-exceptions.json. The new file is the function plus two import lines, under the 250-line preferred file budget.

26.5 Existing Feature Intent boundary ​

packages/application/src/feature-intent/ already holds a separate planning flow. feature-intent-w10.ts star-exports create, scope, impact, plan, workspace, view model, CLI view, and fixtures. foundation-flow.ts star-exports feature-intent-w10.ts. That chain is how the richer Feature Intent API reaches the barrel. It does not call planFeature.

Three responsibilities stay separate:

FlowWhat it does todayP1K.11
Legacy stubplanFeature builds fixed draft JSON and optionally validates itmove this function only
Feature Intent planprepareImplementationAlternatives and prepareImplementationPlan in feature-intent-plan.ts turn a FeatureIntent into alternatives and a plan whose executionGate is "w11-blocked", reviewRequired is true, and mutationAllowed is falseleave in place
Workspace review and executionprepareFeatureIntentWorkspace reads a project root, resolves scope, analyzes impact, and returns a read-only workspace overviewleave in place

Workspace preparation takes a filesystem and a root. The stub takes a task identifier and an optional validator. Merging them would couple a deterministic draft to repository analysis. This slice does not do that, and it does not introduce W10 execution, W11 execution, AI planning, or autonomous implementation.

Desktop and Daemon do not import planFeature. Their Feature Intent modules, where those exist, are not evidence of a planFeature consumer.

26.6 Consumer audit ​

Repository search for planFeature on 39ee6e8:

LocationKindWhat it does
packages/application/src/index.tsdefinitionthe function this slice moves
packages/cli/src/plan-command.tssource importimport { planFeature } from "@intentloom/application"; calls it after argument parsing and catalog bootstrap
packages/cli/src/update-command.tssource importsame package import; calls it only on the bare-update fallthrough
packages/cli/src/command.tsCLI dispatchplan calls runPlanCommand; update calls runUpdateCommand; the outer catch maps errors to exit codes
tests/cli-plan.test.tsCLI testplan success, errors, parser precedence, catalog failure, --json, read-only project, and bare update
tests/cli-update.test.tsCLI testbare update fallthrough
tests/cli-init.test.tsCLI testbare update fallthrough
tests/cli-sync.test.tsCLI testbare update fallthrough
tests/project-lifecycle-p1i2.test.tsdirect callclass identity and both-invalid results: [invalid, invalid]

Documentation mentions in DUTY_WATCH.md, PROJECT_STATE.md, docs/architecture/PACKAGES_STABILIZATION_PLAN.md, docs/roadmap/CLI_COMMAND_TS_DECOMPOSITION.md, and earlier design documents are references, not runtime callers.

No import exists under apps/, packages/daemon/, or packages/application/src/neutron/.

26.7 CLI compatibility ​

runPlanCommand order:

  1. parsePlanArguments. A CliUsageError throws here, before catalog bootstrap and before planFeature.
  2. createCliArtifactValidator(catalogRoot). A broken catalog throws SchemaCatalogError here. planFeature is not called.
  3. planFeature(parsed.values.get("--task") ?? "", validator).
  4. stdout is the returned string, or JSON.stringify(result, null, 2) when --json is set. The command returns 0.

runCli maps SchemaCatalogError and ArtifactValidationFailure to exit 3. Other Error values, including the missing-task error and parser errors, print error.message and return 2. runPlanCommand itself returns only 0. Exits 2 and 3 come from that outer catch.

Preserved plan behavior, already covered by tests/cli-plan.test.ts:

CaseExitOutput
plan --task <nonempty>0pretty JSON document with featureBrief and contextPack
plan with no --task2stderr task identifier is required
plan --task ""2same stderr message
positional path, unknown option, missing option value, --force, --cache, adoption mappings, paired daemon flags2the existing parser message; catalog text is absent
unknown option against a broken catalog2parser message wins; schema-catalog text is absent
valid parse against a broken catalog3stderr contains Intentloom schema catalog validation failed
that catalog failure with --json3stderr JSON has status, errorCode, and schemaFile
--strict or --profile <value> with --task0flags are parsed and ignored by planFeature
--root with --task0root does not change the JSON; planFeature never receives it
--json0stdout is a JSON encoding of the string payload; JSON.parse(stdout) equals the plain stdout string
project files present0planFeature and runPlanCommand do not write them

runPlanCommand does not take a filesystem. The memory filesystem in the plan tests is unused by this command. Catalog bootstrap reads the catalog directory with Node readdir.

runUpdateCommand reaches planFeature only when --plan and --apply are both absent. Order on that path:

  1. parseUpdateArguments. Parser errors throw first. A positional token becomes --root when --root is not already set. That parser rule stays. plan rejects a positional token instead.
  2. createCliArtifactValidator.
  3. loadInvalidProjectMetadata("update", ...). readsProjectMetadata is true only for sync, adopt, and diff, so this call returns [] without reading the project.
  4. buildProjectMutationOptions for command "update". Because the command does not read project metadata, this call does not read or write project files. The returned options object is discarded.
  5. planFeature(parsed.values.get("--task") ?? "", validator).
  6. The same --json string encoding as plan. A string result selects exit 0 through typeof result === "string".

Bare update therefore still calls planFeature("") after those metadata helpers, prints task identifier is required, and exits 2. tests/cli-plan.test.ts, tests/cli-update.test.ts, tests/cli-init.test.ts, and tests/cli-sync.test.ts lock that fallthrough. --plan and --apply return before planFeature. This slice does not remove the fallthrough and does not fix the --json double encoding. Both are compatibility contracts.

26.8 Dependency direction ​

mermaid
flowchart TB
  command["CLI command.ts"]
  planCli["CLI plan-command.ts"]
  updateCli["CLI update-command.ts"]
  barrel["application index.ts"]
  leaf["feature-intent/plan-feature.ts"]
  failure["artifact-validation-failure.ts"]
  validator["@intentloom/validator ArtifactValidator"]
  inception["inception-flow.ts"]
  foundation["foundation-flow.ts"]
  w10["feature-intent-w10.ts"]
  intentPlan["feature-intent-plan.ts"]

  command -->|"source import and runtime dispatch"| planCli
  command -->|"source import and runtime dispatch"| updateCli
  planCli -->|"source import and runtime call"| barrel
  updateCli -->|"source import and runtime call"| barrel
  barrel -->|"direct re-export, no wrapper call"| leaf
  leaf -->|"source import"| failure
  leaf -.->|"type-only import"| validator
  barrel -->|"export star"| inception
  inception -->|"export star"| foundation
  foundation -->|"export star"| w10
  w10 -->|"export star"| intentPlan

Source: feature-planning-dependencies.mmd.

This is a scoped module view. It shows the planFeature consumers and the existing public Feature Intent re-export chain. It is not every export from inception-flow.ts or foundation-flow.ts.

Edge labels name the relationship. command.ts source-imports plan-command.ts and update-command.ts and calls them at runtime. Those commands source-import planFeature from the barrel and call it at runtime. The barrel line into plan-feature.ts is a direct re-export, not a wrapper call. The leaf source-imports ArtifactValidationFailure. The dotted edge is a type-only import. The export star edges are the current public path: index.ts to inception-flow.ts to foundation-flow.ts to feature-intent-w10.ts to feature-intent-plan.ts. planFeature is not on that path, and this slice does not add it there.

26.9 Sequence ​

mermaid
sequenceDiagram
  participant Caller
  participant Plan as planFeature
  participant Validator as ArtifactValidator

  Caller->>Plan: planFeature taskId and optional validator
  alt taskId is falsy
    Plan-->>Caller: rejected Promise, Error task identifier is required
  else taskId is nonempty
    Plan->>Plan: create featureBrief and contextPack
    alt validator is absent
      Plan-->>Caller: resolved Promise, formatted JSON string
    else validator is present
      Plan->>Validator: validate feature-brief compact JSON
      alt feature-brief validate throws
        Validator-->>Plan: throw original exception
        Note over Plan: context-pack validate is not called
        Plan-->>Caller: rejected Promise, same exception
      else feature-brief result returned
        Validator-->>Plan: feature-brief result
        Plan->>Validator: validate context-pack compact JSON
        alt context-pack validate throws
          Validator-->>Plan: throw original exception
          Note over Plan: no ArtifactValidationFailure
          Plan-->>Caller: rejected Promise, same exception
        else context-pack result returned
          Validator-->>Plan: context-pack result
          Plan->>Plan: collect both results, then keep status invalid
          alt any collected status is invalid
            Plan->>Plan: construct ArtifactValidationFailure
            Plan-->>Caller: rejected Promise with that error
          else no invalid status
            Plan-->>Caller: resolved Promise, formatted JSON string
          end
        end
      end
    end
  end

Source: feature-planning-validation-sequence.mmd.

validate returns its result to planFeature, or throws to planFeature. planFeature rejects its Promise with that same exception. A throw from the feature-brief call does not call context-pack validation. A throw from the context-pack call happens after the feature-brief call has returned. That path does not construct ArtifactValidationFailure. When both calls return, planFeature collects both results and then filters status === "invalid". It constructs ArtifactValidationFailure with the invalid results and rejects with that error. The error class does not throw on its own. A successful call resolves with the formatted JSON string.

Mermaid is enough for this scoped dependency view and this sequence. Excalidraw and draw.io are not required: the diagrams are labeled graphs of existing modules and one call order, and a freehand canvas would not add a reviewable fact. Each fence in this section is the same text as its .mmd source. This repository's documentation build does not render Mermaid, so source equality is not a rendering check.

26.10 Error and failure matrix ​

Executed or read from the current control flow on 39ee6e8. "Later" means the next step inside planFeature or, for the CLI rows, the call to planFeature.

CaseOrderResultLater steps
Empty taskId ""guard throws immediatelyError("task identifier is required")objects and validate are not reached
Nonempty taskId, no validatorobjects, then returnpretty JSON Promiseno validate
Whitespace-only " ", tab, or newlinetreated as nonemptypretty JSON with the raw character in id, title, taskId, and both path stringsno trim
Unusual ids "0", "a/b", "../x", quotes, surrounding spacessame nonempty pathcharacters copied into fields and path stringsno sanitization
No validator argumentif (validator) is falsepretty JSONzero validate calls
Both results status: "valid"feature-brief, then context-packpretty JSONboth calls happen; filter keeps nothing
First invalid, second validboth calls, then filterArtifactValidationFailure whose results is [first] and results[0] === firstsecond call still happens
First valid, second invalidboth calls, then filterresults is [second] with that object identityfailure is thrown after both calls
Both invalidboth calls, then filterresults is [first, second] with both identitiessame objects and order; message project artifact validation failed
First validate throwsfeature-brief call throwsthe same thrown objectcontext-pack is not called; no ArtifactValidationFailure
Second validate throwsfeature-brief returns, context-pack throwsthe same thrown objectno ArtifactValidationFailure; the first result is discarded
CLI catalog bootstrap failureparser succeeds, createCliArtifactValidator throws SchemaCatalogErrorexit 3 and the existing catalog stderrplanFeature is not called
CLI --jsonplanFeature returns a stringexit 0; stdout is JSON.stringify of that stringthe string is encoded again; this stays

26.11 Architecture metrics and cycles ​

measureProductionSource on 39ee6e8:

FileEffectivePhysical
packages/application/src/index.ts742777
packages/application/src/project-lifecycle/project-root.ts6469
planFeature lines 367–4326666

project-root.ts is the P1K.10 leaf. P1K.11 does not edit it. The parent inventory's old range 426–491 is the pre-extraction line range. Section 3.3 now records 367–432. The 66 / 66 counts are unchanged.

Parent roadmap forecast, still a forecast:

QuantityFigure
Body lines removedabout 66 effective
Re-export glueabout 3 effective
Net barrel reductionabout 63 effective
Forecast index.tsabout 679 effective (742 - 63)

Section 15's running cell of 655 assumed a post-P1K.10 barrel near 718. The measured barrel is 742, so 679 is the forecast from this baseline. Deleting the unused type import, or collapsing the error-class import-plus-export into one re-export line, can move the result by a line or two inside that "about". The implementation remeasures. This design does not claim 679 as an observed size. Physical lines start at 777; the same net is about 714 physical lines, also a forecast.

Observed with measureProductionSource after the move: index.ts is 675 effective lines and 710 physical lines. The leaf feature-intent/plan-feature.ts is 68 effective lines and 69 physical lines. planFeature remains 66 effective lines and 66 physical lines. That is 67 effective lines below the 742 baseline. The forecast of about 679 counted about 3 lines of glue against a 66-line removal. The move also deletes the unused ArtifactValidator type import and replaces the value import plus separate export of ArtifactValidationFailure with one direct re-export, which accounts for the further reduction. The 66-line function exceeds the preferred 40-line budget and stays within the hard 80-line limit. It is not split, and quality-exceptions.json is not edited.

applicationCycles on 39ee6e8 returned the same components as section 8.1:

GraphSizesMembers
Import-only[3]neutron/mutation/apply/neutron-mutation-apply-durable-record.ts, neutron/mutation/apply/neutron-mutation-apply-store.ts, neutron/mutation/verification/neutron-mutation-verification-retry-eligibility.ts
Re-export-inclusive[4, 27, 3]size 4: apply-extension-update.ts, discover-and-apply-extension-update.ts, extension-update-files.ts, propose-and-apply-extension-adoption.ts. Size 27: the index.ts component named in section 8.1, including approved-apply-engine.ts, foundation-flow.ts, inception-flow.ts, the harness files, the engineering-quality files, and the existing-project files. Size 3: the same Neutron trio

No feature-intent file is in those components. artifact-validation-failure.ts is outside them. The new leaf must stay outside all of them. Expected topology after the move: the same sizes and the same members. The new edges are barrel re-export to the leaf, and leaf value import to artifact-validation-failure.ts. Neither edge loops back to index.ts.

These structure tests locked the barrel at 742 effective and 777 physical lines before this extraction. The implementation updates those locks to the measured 675 effective and 710 physical lines. It does not change their other assertions:

  • tests/bounded-project-context-p1k6-structure.test.ts
  • tests/generated-file-transaction-p1i1-structure.test.ts
  • tests/legacy-subagent-task-record-p1j-structure.test.ts
  • tests/profile-store-p1k1-structure.test.ts
  • tests/project-adoption-p1i3-structure.test.ts
  • tests/project-lifecycle-p1i2-structure.test.ts
  • tests/project-root-p1k10-structure.test.ts
  • tests/role-delegation-p1k2-structure.test.ts
  • tests/security-adapter-p1k7-structure.test.ts
  • tests/security-audit-structure-p1h6.test.ts
  • tests/semantic-ranking-p1k5-structure.test.ts
  • tests/task-checkpoint-store-p1k4-structure.test.ts
  • tests/task-session-summary-store-p1k3-structure.test.ts
  • tests/workspace-conversation-p1k8-structure.test.ts
  • tests/workspace-read-model-p1h7-structure.test.ts

26.12 Security and trust boundaries ​

The task identifier is copied into feature-brief id and title, context-pack taskId, the brief's contextPack string, and the two documentPath strings passed to validate. The current function does not open or write those paths.

Keeping that behavior is not a claim that an arbitrary task identifier is safe for a future writer of plans/${taskId}.json. Path segments, .., quotes, and whitespace already pass through. A later persistence slice needs its own path policy. This slice adds no sanitizer, no authorization check, and no new trust boundary.

Technical-debt candidate, separate from P1K.11: if a future command persists those generated paths, it must decide how untrusted task identifiers are confined. That decision is not part of this extraction.

Accessibility: NOT APPLICABLE. No user interface change. AI evaluation: NOT APPLICABLE. No model behavior. Product discovery: NOT APPLICABLE. No new product capability.

26.13 Alternatives, planning, and RAID ​

AlternativeDecision
Leave planFeature in index.tsRejected by the parent roadmap. The barrel stays 66 effective lines larger and still owns a stub
Move it to feature-intent/plan-feature.ts and re-export itSelected proposal. One leaf, no new port, public identity preserved
Merge it into feature-intent-plan.ts or feature-intent-w10.tsRejected. That file prepares Feature Intent alternatives and a W11-blocked plan. The stub is a different contract. A star export through foundation-flow.ts would also mix the two public paths
Add a planning service or portRejected. The parent roadmap asks for a leaf without a new abstraction, and the function has no second implementation

The selected row was PROPOSED until section 26.17 was accepted on 2026-11-29 13:31:01 Europe/Berlin.

SWOT: Strengths — one function, one leaf, existing CLI tests, and a direct re-export. Weaknesses — the function is a 66-line stub over the preferred 40-line budget, and the task identifier is copied into path-shaped strings. Opportunities — Stage A can lock the JSON and validator contract before the file move. Threats — a wrapper that breaks function or error-class identity, a star export that merges this stub into Feature Intent workspace planning, or a leaf import of the barrel that joins the size-27 component.

RACI: Responsible — the design author of this section. Accountable — the Project Owner, for section 26.17. Consulted — the independent design reviewer. Informed — the next watch, which does not implement until the owner authorizes that separate task.

RAID:

  • Risk — behavior drift while moving the function. Mitigation — Stage A on the original implementation, then the move, then Stage B. The implementation keeps the Stage A assertions.
  • Risk — the leaf imports index.ts and enters the size-27 component. Mitigation — Stage B forbids ../index.js and @intentloom/application from the leaf, and compares applicationCycles to section 8.1.
  • Risk — a design merge is treated as owner acceptance. Mitigation — section 26.17 stayed PROPOSED until the dated Project Owner statement at 2026-11-29 13:31:01 Europe/Berlin. Implementation waited for the separate 13:46 Europe/Berlin authorization.
  • Assumption — if (!taskId) and synchronous validate remain the contract. Empty, whitespace, and unusual identifiers stay as section 26.2 records them.
  • Assumption — CLI --json double encoding and bare update fallthrough stay, including the metadata helpers that return without project I/O for command "update".
  • Issue — generated plans/${taskId} strings are not a filesystem policy. Recorded in section 26.12. No fix in this slice.
  • Dependency — P1K.10 implementation is on main at fecace86. P1K.10 test-quality closure is on main at 39ee6e8. P1K.11 implementation waited for owner acceptance of this section and a separate authorization. Both are recorded above.
  • Dependency — ArtifactValidationFailure remains the class in artifact-validation-failure.ts. CLI instanceof checks use the barrel export of that same class.

Implementation sequence, after acceptance:

  1. This Design PR.
  2. Independent design review.
  3. Explicit Project Owner acceptance of section 26.17.
  4. Owner merges the Design PR.
  5. Main verification of that merge.
  6. Separate implementation authorization.
  7. Stage A characterization tests, committed on their own, against the original index.ts function.
  8. Production extraction.
  9. Stage B structure tests, and updates to the barrel-size locks listed in section 26.11.
  10. Independent implementation review.
  11. Owner merge.

Testing strategy: section 26.14. This Design PR adds no test.

Security assessment: section 26.12. No new authorization mechanism.

Design-stage estimates for this Design First task. They are planning figures, not observed durations for this watch or for a future implementation.

MeasureEstimate
Human active effort5–10 minutes
AI agent execution effort30–60 minutes
Calendar duration1–2 hours

26.14 Two-stage test plan ​

This Design PR does not add tests.

Existing tests that must stay green, unchanged in assertion strength:

  • tests/cli-plan.test.ts
  • tests/cli-update.test.ts
  • tests/cli-init.test.ts
  • tests/cli-sync.test.ts
  • tests/project-lifecycle-p1i2.test.ts

Stage A — characterization before extraction ​

File: tests/plan-feature-p1k11-characterization.test.ts.

Commit this file and run it against the original planFeature in index.ts before any production move. Use a test double that implements ArtifactValidator. Do not add a production injection hook. Keep the real catalog validator on the existing CLI tests; do not replace those with the double.

Cover:

  • The public signature remains callable as (taskId, validator?) and the resolved success value is a string.
  • Build the expected feature brief and context pack in the test, apart from the returned string. Assert every default in section 26.2, key order, and the exact serialized string, including indentation and the absence of a trailing newline. For task-1, that string is the 1210-character text block in section 26.2. Do not parse the output and compare it with itself.
  • Identifier interpolation, including whitespace, "0", a slash, .., quotes, and surrounding spaces.
  • "" rejects with Error("task identifier is required") and the validator double is not called.
  • Call planFeature with no validator and no project filesystem. The JSON still returns. That assertion is about planFeature itself. A caller-supplied validator may perform its own I/O; the test double used here must not, and the no-validator call must not touch a project directory. Returned paths exist only as strings in the JSON.
  • Successful validation: exactly two validate calls, feature-brief then context-pack. Each captured argument is strictly equal to an expected object that owns only artifactType, documentPath, format, and source. skillPolicy and semanticContext are absent. source equals the compact JSON.stringify of that artifact.
  • First invalid, second invalid, and both invalid: exactly two calls in each case. Use a distinct result object for each call. Assert ArtifactValidationFailure, the barrel class identity, message project artifact validation failed, and results holding those original objects in order (results[0] === first, and results[1] === second when both are invalid).
  • A "valid" result with a nonempty warnings array does not reject.
  • Use two distinct thrown errors. The rejection is that same object (rejects.toBe). A throw from the first call performs no second call. A throw from the second call performs exactly two calls. When the first result is invalid and the second call throws, the rejection is the original second-call exception and is not an ArtifactValidationFailure.

Stage B — architecture after extraction ​

File: tests/plan-feature-p1k11-structure.test.ts.

Run after the production move. Keep every Stage A assertion. Verify:

  • One implementation, in feature-intent/plan-feature.ts.
  • index.ts re-exports it directly. index.ts no longer contains function planFeature.
  • The barrel function and the leaf function are the same reference.
  • The TypeScript signature stays compatible with section 26.2.
  • ArtifactValidationFailure from the barrel and from artifact-validation-failure.ts are the same reference.
  • The leaf source does not import ../index.js or @intentloom/application.
  • The leaf's relative imports are only ../artifact-validation-failure.js.
  • packages/application/package.json gains no export.
  • feature-intent/ gains no index.ts, and feature-intent-w10.ts does not export planFeature.
  • applicationCycles(false) and applicationCycles(true) still report sizes [3] and [4, 27, 3] with the section 8.1 members. The new leaf is in neither component.
  • measureProductionSource on index.ts and on the new leaf. Record the measured numbers. Do not assert the forecast 679 as if it were known before the move; assert the measured post-move size, and fail if the barrel still contains the function body.
  • Existing CLI tests still pass without edited expectations.

Avoid assertions that only repeat a string the test itself wrote. Update the fifteen barrel-size locks in section 26.11 to the measured post-move size in the implementation pull request.

26.15 Mandatory sequence ​

  1. Design PR.
  2. Independent design review.
  3. Explicit Project Owner acceptance.
  4. Owner merges the Design PR.
  5. Main verification.
  6. Separate implementation authorization.
  7. Stage A tests.
  8. Production extraction.
  9. Stage B tests.
  10. Independent implementation review.
  11. Owner merge.

This design pull request stops at step 2. Steps 3 through 11 are not authorized by publishing this section.

26.16 Non-goals ​

P1K.12 through P1K.17, Engineering Quality retarget, Approved Apply changes, Undo U4, Desktop Undo U5, Neutron edits, Daemon edits, CLI behavior changes, validator or schema contract changes, new package dependencies, quality-exceptions.json, CI changes, and any rewrite of published Git history.

26.17 Design First acceptance matrix ​

The parent roadmap, green CI, and the merge of the Design PR do not check these rows. The Project Owner accepted all eleven rows at 2026-11-29 13:31:01 Europe/Berlin in PR #649 comment 7255868443, before that pull request merged at 13:31:23. A separate implementation authorization followed at 2026-11-29 13:46 Europe/Berlin, after main verification of c72168a succeeded. Neither statement is backdated.

#Proposed decisionStatus
1Section 26 records the current signature and behavior on 39ee6e8accepted
2Every JSON field and default in section 26.2 staysaccepted
3Validator order, argument objects, compact source, and the absent-validator path stayaccepted
4ArtifactValidationFailure keeps its class identity, message, and result objectsaccepted
5Exceptions thrown by validate propagate unchanged, including first-call short-circuitaccepted
6CLI plan and update behavior in section 26.7 stays, including --json and bare updateaccepted
7The target module and the dependency direction in sections 26.4 and 26.8 are the approved shapeaccepted
8The stub stays separate from feature-intent-plan.ts and workspace preparationaccepted
9Cyclic-component membership stays section 8.1, and the new leaf stays outside itaccepted
10Stage A characterization is committed before the production extractionaccepted
11The implementation adds no unrelated runtime, schema, security, or product changeaccepted

27. P1K.12 Pack Update Planning — Design First gate ​

Status: section 27.17 is ACCEPTED after design PR #651 merged. The implementation later merged as PR #655. Section 27.19 records that merge, the cancelled macos-latest / Node 24 job on 89fbcd7, and the documentation-only follow-up PR #657. The paragraphs below keep their pre-merge wording. Parent design PR #627 remains the architectural roadmap. This section records behavior verified on main at 23f5176f31586518cb4d0825bdb7b3dbae682729 (P1K.11 implementation, PR #650) and the extraction contract for slice P1K.12 only. That planner source is unchanged on main at 9d2a9741d99123f11c5e45fb473e984e5ca14e0d (PR #652, documentation only), at 43819a8aedb40f52d31745772d308cd2fbce1194 (PR #653, documentation only), and at b4cfb09c5fa895be89b4bb0dd14dc76de05626f3 (PR #654, documentation only). Design PR #651 then merged at 2026-12-02 23:20:06 Europe/Berlin as a787faf0524414b63a4e65ad0335bb07bd65aa3d. The design text did not accept itself. A pull request merge, green CI, or the parent roadmap does not accept the matrix in section 27.17.

The Project Owner accepted all eleven section 27.17 decisions after that merge, and accepted the Compatibility workflow changes included in PR #651. The acceptance is in the supervising conversation. This repository does not record a GitHub review identifier or an exact acceptance timestamp. Acceptance was after the merge, not before it. PR #651 is not documentation-only: the Compatibility workflow change is an accepted scope deviation. Earlier handoff text that described the design work as documentation-only remains in the historical Duty Watch entries and is not rewritten. Implementation was conditionally authorized upon successful verification of a787faf. Documentation run 46983897938, CodeQL run 46983897891, and Compatibility run 46983897990 succeeded. Compatibility completed at 2026-12-02 23:37:38 Europe/Berlin. All six operating-system and Node.js combinations passed, including their test steps. That success made the conditional authorization effective. No further owner authorization was required for this bounded extraction. Observed implementation results are in section 27.18. The implementation stayed in review until the owner merged it. Section 27.19 is that record.

P1K.11 merged on 2026-11-29. Main verification of 23f5176 succeeded: Documentation run 46288457468, CodeQL run 46288457443, and Compatibility run 46288457515 all completed successfully on the main push for PR #650.

27.1 Problem and scope ​

P1K.12 moves only planPackUpdate and PlanPackUpdateOptions from packages/application/src/index.ts into packages/application/src/project-adoption/plan-pack-update.ts, then re-exports both from the public application barrel.

The move is behavior-preserving. The wrapper stays a read-only planning facade over planProjectAdoption, with an optional target pack version assignment.

ItemThis slice
ResponsibilityplanPackUpdate and PlanPackUpdateOptions
Targetpackages/application/src/project-adoption/plan-pack-update.ts
Public surfacedirect re-export from index.ts
Compatibility tests already on maintests/cli-pack-update.test.ts, tests/cli-update.test.ts
Estimated body removal44 effective lines (interface 6, function 38)
Estimated glueabout 4 effective lines (re-exports)
Estimated net barrel reductionabout 40 effective lines
Cyclic componentsunchanged

Out of this slice: behavior changes, new root validation helpers, consolidating the two symlink checks, recomputing planId, CLI edits, schema changes, package export changes, Neutron, Daemon, Desktop, Approved Apply, Engineering Quality, Undo, and P1K.13+ work.

27.2 Verified public contract ​

Verified from packages/application/src/index.ts lines 375–422 on 23f5176.

ts
export interface PlanPackUpdateOptions {
  readonly root: string;
  readonly targetPackVersion?: string;
  readonly validations?: readonly ValidationRequirement[];
  readonly exceptions?: readonly AcceptedException[];
}

export async function planPackUpdate(
  options: PlanPackUpdateOptions,
  fs: FileSystem = nodeFileSystem,
): Promise<AdoptionPlan>;

ValidationRequirement, AcceptedException, and AdoptionPlan are type-only imports from @intentloom/core/adoption on the barrel today. The leaf imports those types from @intentloom/core/adoption directly. It does not import governance-adoption-contracts.ts. FileSystem and the default nodeFileSystem come from ../host-file-system.js.

Preserved semantics:

  • Lexical resolve(options.root) via node:path resolve.
  • First symlink rejection with message pack update planning requires a non-symbolic explicit project root.
  • Optional validations and exceptions forwarded only when !== undefined, using the same object references.
  • The same fs instance passed through to planProjectAdoption.
  • targetPackVersion uses nullish coalescing: options.targetPackVersion ?? "1.1.0".
  • No new normalization, root policy, or target-version validation.

27.3 Root validation and delegated planning ​

First check (wrapper). After resolve(options.root), planPackUpdate awaits fs.isSymbolicLink(root). On true, it throws new Error with the pack-update message above. No delegation occurs after this rejection.

Second check (delegate). planProjectAdoption resolves options.root again (the wrapper passes the already-resolved string; resolve is idempotent for an absolute path) and awaits fs.isSymbolicLink(root) with message adoption planning requires a non-symbolic explicit project root.

Distinct cases:

CaseFirst checkSecond checkWhat the caller observes
Non-symlink rootpassespassesdelegation and the artifact scan
Symlink rootnew wrapper Errornot reachedpack-update message; planProjectAdoption not called
Race: symlink only visible to second checkpassesnew delegate Erroradoption-planning message; one delegation
Wrapper isSymbolicLink throwssame exception objectnot reachedpropagated filesystem exception; no delegation
Delegate isSymbolicLink throwspassedsame exception objectpropagated filesystem exception
fs.list throwspassedpassedsame exception object; the artifact loop does not start
fs.read throws for one pathpassedpassedreadGovernanceArtifact returns null; that artifact omitted; scan continues
inside throws in that same trypassedpassedsame swallowed failure; fs.read is not called; scan continues
Secret-like pathpassedpassedreadGovernanceArtifact returns null without fs.read

A wrapper symlink rejection and a delegate symlink rejection are different new Error values with different messages. A thrown isSymbolicLink, fs.list, or other uncaught filesystem rejection is not replaced by either message. The caller receives that same exception object.

fs.list and fs.read are not the same failure. governanceArtifacts awaits fs.list(root) with no catch. A rejection propagates unchanged through planProjectAdoption and planPackUpdate. The artifact loop does not start.

projectRelativePaths then filters the entries. Paths that normalize to "", "..", any "../" prefix, or an ignored scan path are dropped and never reach readGovernanceArtifact, so an ordinary fs.list fixture cannot drive an inside path-traversal throw through the scan loop. For each path that survives that filter, governanceArtifacts calls readGovernanceArtifact. That function returns null for secretLikePath without calling fs.read. Otherwise it evaluates fs.read(inside(root, path)) inside one try. Any throw from that try, including an fs.read rejection or an inside path-traversal throw for a kept relative path, returns null. governanceArtifacts omits that artifact and continues with the next path. A swallowed artifact-read failure is not a propagated exception. A later readable artifact is still collected, and planGovernanceAdoption still runs with the artifacts that were kept.

checksum, ownershipClassForPath, and roleCandidatesForPath run after that try. A throw from one of them is not caught and is not a swallowed artifact-read failure. It propagates unchanged through planProjectAdoption and planPackUpdate.

Do not replace either check with assertCanonicalProjectRoot or daemon root validation. Do not consolidate the two checks.

Delegated planner behavior (wrapper does not duplicate this):

  • Defaults: projectId ?? "project", packId ?? "duty-watch", packVersion ?? "1.0.0" inside planProjectAdoption.
  • Calls planGovernanceAdoption in @intentloom/core/adoption with the artifacts that survived the scan.

27.4 Target version and plan transformation ​

After delegation returns basePlan:

  1. targetVersion = options.targetPackVersion ?? "1.1.0".
  2. If basePlan.packVersion === targetVersion, return basePlan (same object reference).
  3. Otherwise build:
ts
const updatedOperations = basePlan.operations.map((op) => {
  if (op.kind === "map-existing" || op.kind === "create") {
    return op;
  }
  return op;
});

return {
  ...basePlan,
  packVersion: targetVersion,
  operations: updatedOperations,
};

The map is a no-op for every operation kind: each branch returns the original operation reference. When versions differ, the result is a shallow copy with a new outer object and a new operations array, but operation elements keep their identities. Other fields (planId, repositoryHash, mappings, findings, and so on) are copied by spread from basePlan without mutation of basePlan.

Explicit targetPackVersion: "" uses ?? only, so "" is the target, not "1.1.0".

27.5 planId and repositoryHash consistency ​

planGovernanceAdoption computes planId as deterministicId("plan", planContent) where planContent.packVersion is the delegated version (default "1.0.0" unless PlanProjectAdoptionOptions override it — planPackUpdate does not pass packVersion).

When the wrapper changes packVersion on the returned plan without recomputing planId, planId can describe "1.0.0" while packVersion reads "1.1.0". repositoryHash is artifact-derived and unchanged by the wrapper.

parseAdoptionPlan requires non-empty planId, packVersion, and repositoryHash strings but does not validate cross-field consistency. applyProjectAdoption uses per-operation expectedCurrentHash staleness, not planId or repositoryHash equality, in staleHashResult.

Record this as an existing consistency concern / technical-debt candidate, not a claimed security defect. This slice does not recompute identifiers or redesign plan integrity.

27.6 Consumers ​

LocationRelationship
packages/cli/src/update-command.tsruntime import and planPackUpdate({ root }, fileSystem) on --plan
tests/cli-pack-update.test.tsdirect planPackUpdate and CLI integration
tests/cli-update.test.tsCLI paths that touch update routing
tests/project-adoption-p1i3-structure.test.tstoday expects function body and planProjectAdoption( in index.ts; Stage B relocates assertions

No runtime import under apps/, packages/daemon/, or Neutron for planPackUpdate. Documentation references in stabilization and handoff documents are not callers.

planProjectAdoption remains a separate public export from the barrel (export { planProjectAdoption } from the existing import). Its identity is unchanged.

27.7 CLI compatibility ​

Preserve all runUpdateCommand behavior without editing CLI in this Design PR.

update --plan: planPackUpdate({ root }, fileSystem) where root is --root or cwd(). JSON via stableStringify(plan); human output via formatGovernanceAdoptionPlan. Optional --output writes through resolveWithin and fileSystem.write (CLI I/O, not application planning). --strict exit 3 when automaticApplyAllowed is false or findings include ambiguous or conflicting.

update --apply: transactional apply of a plan file; unchanged.

Bare update: still falls through to planFeature; not this slice.

Catalog bootstrap, parser-error precedence, exit codes 0/2/3/4/5, and error messages stay as on 23f5176.

27.8 Dependency direction ​

mermaid
flowchart TB
  updateCli["CLI update-command.ts"]
  packTest["tests/cli-pack-update.test.ts"]
  updateTest["tests/cli-update.test.ts"]
  barrel["application index.ts"]
  leaf["project-adoption/plan-pack-update.ts"]
  delegate["governance-adoption-plan.ts"]
  contracts["governance-adoption-contracts.ts"]
  hostFs["host-file-system.ts"]
  projectPath["project-path.js"]
  coreAdoption["@intentloom/core/adoption"]
  artifacts["governance-adoption-artifacts.ts"]

  updateCli -->|"source import and runtime call"| barrel
  packTest -->|"source import and direct call"| barrel
  updateTest -->|"CLI integration"| updateCli
  barrel -->|"direct re-export, no wrapper call"| leaf
  leaf -->|"source import and runtime call"| delegate
  leaf -->|"source import"| hostFs
  leaf -.->|"type-only ValidationRequirement, AcceptedException, and AdoptionPlan"| coreAdoption
  delegate -->|"planGovernanceAdoption runtime call"| coreAdoption
  delegate -->|"source import"| hostFs
  delegate -->|"source import"| projectPath
  delegate -->|"source import"| artifacts
  delegate -.->|"type-only PlanProjectAdoptionOptions"| contracts

Source: pack-update-planning-dependencies.mmd.

Solid edges are source imports and runtime calls. Dotted edges are type-only. The barrel re-exports the leaf without a forwarding wrapper function. PlanPackUpdateOptions is declared in the leaf. It uses ValidationRequirement and AcceptedException, and the function returns AdoptionPlan. Those three names are the leaf's only @intentloom/core/adoption imports, and the dotted edge names them. The leaf does not import PlanPackUpdateOptions from core. The leaf has no edge to governance-adoption-contracts.ts. The delegate keeps its existing type-only dependency on PlanProjectAdoptionOptions from that contracts module, and its runtime call to planGovernanceAdoption.

After extraction, index.ts may drop the node:path resolve import when planPackUpdate is the only caller (verified on 23f5176). The leaf owns resolve.

No reverse barrel imports, directory barrel under project-adoption/, new DI port, or new package.json export.

27.9 Sequence ​

mermaid
sequenceDiagram
  participant Caller
  participant Pack as planPackUpdate
  participant Fs as FileSystem
  participant Delegate as planProjectAdoption
  participant Scan as readGovernanceArtifact
  participant Core as planGovernanceAdoption

  Caller->>Pack: planPackUpdate options and optional fs
  Pack->>Pack: resolve options.root lexically
  Pack->>Fs: isSymbolicLink resolved root
  alt isSymbolicLink throws
    Fs-->>Pack: original exception
    Pack-->>Caller: propagated filesystem exception and no delegation
  else root is a symbolic link
    Pack-->>Caller: wrapper symlink error
  else root is not a symlink
    Pack->>Delegate: same fs, resolved root, optional keys omitted when undefined
    Delegate->>Delegate: resolve options.root lexically
    Delegate->>Fs: isSymbolicLink resolved root
    alt isSymbolicLink throws
      Fs-->>Delegate: original exception
      Delegate-->>Pack: same exception object
      Pack-->>Caller: propagated filesystem exception
    else root is a symbolic link
      Delegate-->>Pack: delegate symlink error
      Pack-->>Caller: same Error object
    else root is not a symlink
      Delegate->>Fs: governanceArtifacts awaits list root with no catch
      alt fs.list throws
        Fs-->>Delegate: original exception unchanged
        Delegate-->>Pack: same exception object
        Pack-->>Caller: propagated filesystem exception and the artifact loop does not start
      else entries returned
        loop each project-relative path
          Delegate->>Scan: readGovernanceArtifact root path and the same fs
          alt secret-like path
            Scan-->>Delegate: null and fs.read is not called
          else ordinary path
            alt inside throws before read
              Scan-->>Delegate: null from that try and fs.read is not called
            else inside returns a path
              Scan->>Fs: read the absolute path
              alt fs.read throws
                Fs-->>Scan: original rejection
                Scan-->>Delegate: null caught by readGovernanceArtifact
              else content returned
                alt checksum, ownership, or role candidates throw
                  Scan-->>Delegate: uncaught exception from after the try
                  Delegate-->>Pack: same exception object
                  Pack-->>Caller: propagated exception, not a swallowed read failure
                else those calls return
                  Scan-->>Delegate: artifact with checksum, ownership, and role candidates
                end
              end
            end
          end
        end
        Delegate->>Core: planGovernanceAdoption with surviving artifacts and defaults
        Core-->>Delegate: AdoptionPlan basePlan
        Delegate-->>Pack: basePlan same object
        Pack->>Pack: targetVersion is options.targetPackVersion when present else 1.1.0
        alt packVersion equals targetVersion
          Pack-->>Caller: return basePlan same object
        else versions differ
          Pack->>Pack: map operations keeping each original operation
          Pack-->>Caller: shallow copy new operations array updated packVersion planId unchanged
        end
      end
    end
  end

Source: pack-update-planning-sequence.mmd.

Mermaid is sufficient: labeled module graph and one call order. Excalidraw and draw.io add no reviewable fact for this bounded move. Each fence matches its .mmd source. The documentation build does not render Mermaid; equality is not a rendering check unless someone runs an external renderer.

The sequence uses the same four failure classes as section 27.10. A wrapper symlink error and a delegate symlink error are separate new Error values, and each one stops before the artifact scan. An isSymbolicLink throw and an fs.list throw are propagated filesystem exceptions: governanceArtifacts does not catch fs.list, and the original object reaches the caller. The artifact loop does not start after a list failure. readGovernanceArtifact returns null for a secret-like path, for an inside throw, and for an fs.read rejection. Those returns have no arrow to planPackUpdate or the caller. The loop continues, and planGovernanceAdoption receives only the artifacts that were kept. Checksum, ownership, and role candidates run only after a successful read. A throw from those calls is a separate alt: the original exception reaches the caller and is not the swallowed read failure.

27.10 Error and failure matrix ​

CaseClassResult
Symlink root at wrapperwrapper symlink errornew wrapper Error; planProjectAdoption not called
Symlink root at delegate onlydelegate symlink errornew delegate Error; that same Error object reaches the caller
Wrapper isSymbolicLink throwspropagated filesystem exceptionsame exception object; no delegation
Delegate isSymbolicLink throwspropagated filesystem exceptionsame exception object through the wrapper
fs.list throwspropagated filesystem exceptionsame exception object; artifact loop does not start
fs.read throws for one pathswallowed artifact-read failurereadGovernanceArtifact catches it and returns null; that artifact is omitted; scanning continues; the caller is not rejected
inside throws in that same tryswallowed artifact-read failurethe same catch returns null; fs.read is not called; scanning continues
Secret-like pathomitted before readreadGovernanceArtifact returns null before fs.read; scanning continues
Equal target and base packVersionsuccessoriginal basePlan reference
Different versionssuccessnew plan object; new operations array; same operation object references

The four failure classes stay distinct. A symlink rejection is a new Error with the message for that layer. A propagated filesystem exception is the original thrown object, including an isSymbolicLink rejection and an fs.list rejection. A swallowed artifact-read failure, including an inside throw in that try, returns null from readGovernanceArtifact and does not reject the planning promise. A throw from checksum, ownership classification, or role-candidate selection is outside that try, so it is not this swallowed class.

27.11 Architecture metrics and cycles ​

Baseline on 23f5176 (measureProductionSource):

FileEffectivePhysical
packages/application/src/index.ts675710
PlanPackUpdateOptions66
planPackUpdate function3841
Combined slice (interface + function)4449

Parent forecast (not observed post-move):

QuantityFigure
Body removed44 effective
Re-export glueabout 4 effective
Net reductionabout 40 effective
Forecast index.tsabout 635 effective (675 - 40)

Implementation remeasures. This design does not claim 635 as observed.

Observed after extraction (measureProductionSource on da8e74927a53ce1f4bf388d3e34ee4030aa10c78):

FileEffectivePhysical
packages/application/src/index.ts629659
plan-pack-update.ts5257
planPackUpdate function3841
PlanPackUpdateOptions declaration66

The observed barrel is 629 effective lines, not the forecast of about 635. The reduction from 675 is 46 effective lines. quality-exceptions.json was not edited. The function remains 38 effective lines, inside the preferred 40-line budget.

Strongly connected components (unchanged expectation):

GraphSizesNotes
Import-only[3]Neutron mutation trio per section 8.1
Re-export-inclusive[4, 27, 3]same member sets as section 8.1

The new leaf must stay outside all components. project-adoption/ modules do not import the barrel today (verified on 23f5176).

Structure tests locking barrel at 675 / 710 (update in implementation PR to post-move measured size):

  • tests/bounded-project-context-p1k6-structure.test.ts
  • tests/generated-file-transaction-p1i1-structure.test.ts
  • tests/legacy-subagent-task-record-p1j-structure.test.ts
  • tests/profile-store-p1k1-structure.test.ts
  • tests/project-adoption-p1i3-structure.test.ts
  • tests/project-lifecycle-p1i2-structure.test.ts
  • tests/project-root-p1k10-structure.test.ts
  • tests/plan-feature-p1k11-structure.test.ts
  • tests/role-delegation-p1k2-structure.test.ts
  • tests/security-adapter-p1k7-structure.test.ts
  • tests/security-audit-structure-p1h6.test.ts
  • tests/semantic-ranking-p1k5-structure.test.ts
  • tests/task-checkpoint-store-p1k4-structure.test.ts
  • tests/task-session-summary-store-p1k3-structure.test.ts
  • tests/workspace-conversation-p1k8-structure.test.ts
  • tests/workspace-read-model-p1h7-structure.test.ts

27.12 Security and filesystem trust boundaries ​

Planning is read-only at the application layer: list, read, and checksum governance artifacts through the injected FileSystem. No write, mkdir, or remove in planPackUpdate or its delegate path for this operation.

Trust boundaries:

  • Caller-supplied root and optional fs (CLI passes project root and may inject a test filesystem).
  • fs.list failures propagate. The delegate excludes secretLikePath and swallows individual fs.read failures. Scanning continues after an omitted artifact.
  • CLI --output writes plan text; that is CLI responsibility, not the application planner.

Do not claim a security defect from planId / packVersion mismatch without operational evidence.

Accessibility: NOT APPLICABLE. AI evaluation: NOT APPLICABLE. Product discovery: NOT APPLICABLE.

27.13 Alternatives, SWOT, RACI, and RAID ​

AlternativeDecision
Leave wrapper in index.tsRejected by parent roadmap
Leaf plan-pack-update.ts + barrel re-exportPROPOSED selected shape
Merge into governance-adoption-plan.tsRejected; separate public pack-update contract
New planning port or DIRejected
Single symlink checkRejected; two messages are compatibility

SWOT: Strengths — small leaf, existing CLI tests, clear delegate boundary. Weaknesses — duplicate symlink checks, no-op operation map, planId drift when version changes. Opportunities — Stage A locks delegation and identity before move. Threats — accidental planId recompute, barrel import cycle, weakened structure tests.

RACI: Responsible — design author. Accountable — Project Owner for section 27.17. Consulted — independent design reviewer. Informed — next watch.

RAID: Risk — behavior drift; mitigation Stage A then B. Risk — leaf imports barrel; mitigation structure tests. Assumption — planProjectAdoption defaults stay. Issue — planId vs packVersion consistency (section 27.5). Dependency — P1K.11 on main at 23f5176.

Design-stage estimates (planning figures, not observed):

MeasureEstimate
Human active effort5–10 minutes review
AI agent execution30–60 minutes
Calendar duration1–2 hours

27.14 Stage A — planned characterization tests ​

Not implemented in this Design PR. The implementation pull request adds this suite. Results are in section 27.18.

Proposed file: tests/plan-pack-update-p1k12-characterization.test.ts

Commit Stage A before production extraction. Use a test-level vi.mock (or equivalent) of ./project-adoption/governance-adoption-plan.js for exact delegation arguments and reference identity — not a production injection port.

Keep two groups in that file. Do not mix them, and do not fold either into tests/cli-pack-update.test.ts. Together they keep every characterization case already proposed for this slice: lexical root resolution, both symlink checks and their exact messages, propagated exception identity, the default filesystem, delegated argument identity, optional-property omission, reference equality of forwarded arrays, one-or-zero delegation, every target-version case including "", base-plan and operation identity, preserved planId and repositoryHash, no mutation of basePlan, and no write, mkdir, or remove. Cases that need the real scanner stay in the integration group.

Module-mocked delegation and identity. vi.mock (or equivalent) of ./project-adoption/governance-adoption-plan.js. These tests do not execute the real scanner.

  • Relative and absolute root values after lexical resolve.
  • Exactly one planProjectAdoption call after a passing first check; zero after first-check rejection.
  • First symlink check: isSymbolicLink true rejects with Error("pack update planning requires a non-symbolic explicit project root") and does not call the delegate.
  • Wrapper filesystem-error identity: isSymbolicLink rejects with a specific object, planPackUpdate rejects with that same object (rejects.toBe), and the delegate is not called.
  • Default fs (nodeFileSystem) when omitted. That omitted call passes the nodeFileSystem reference itself as the delegate's filesystem argument.
  • Unchanged filesystem reference: when the caller passes an fs object, the second argument of planProjectAdoption is that same object (toBe), not a clone and not nodeFileSystem.
  • Exact optional-property omission: build the expected delegated object in the test. It is exactly { root } when both optionals are omitted, exactly { root, validations } when only validations !== undefined, exactly { root, exceptions } when only exceptions !== undefined, and exactly { root, validations, exceptions } when both are passed. Compare with strict equality. An omitted option is an absent key, not a key whose value is undefined. targetPackVersion, projectId, packId, and packVersion are never keys on that object.
  • Reference equality for forwarded validations and exceptions arrays (toBe on the array, not a deep copy).
  • Target version: default "1.1.0", explicit value, equal to base, different from base, and explicit "" via nullish semantics.
  • Same basePlan reference when versions match; new plan and operations array when they differ; original operation references for every kind.
  • planId, repositoryHash, and other fields preserved on version change.
  • No mutation of the original basePlan.
  • The mock filesystem records zero write, zero mkdir, and zero remove calls.

Real planner integration. No module mock of planProjectAdoption. Use the real delegate and an injected FileSystem. These tests do not replace the delegation assertions above. projectRelativePaths filters traversal-shaped list entries before readGovernanceArtifact calls inside, so Stage A must not prescribe a real-planner fixture whose sole purpose is to make inside throw before read. The shared try/catch shape for inside stays in sections 27.3, 27.10, and the sequence diagram; integration coverage for swallowed artifact-read failures uses an ordinary kept path whose fs.read throws.

  • Second symlink check: isSymbolicLink returns false for the wrapper and true for the delegate. The rejection is Error("adoption planning requires a non-symbolic explicit project root"). The wrapper does not replace that Error (rejects.toBe on the delegate's error object).
  • Delegate filesystem-error identity: isSymbolicLink throws on the delegate call. The caller receives that same exception object (rejects.toBe).
  • fs.list failure propagation: the rejection is that same exception object (rejects.toBe). No read runs after that throw.
  • fs.read failure omission and continued scanning: one ordinary path that survives projectRelativePaths has read throw and another ordinary kept path returns content. Planning fulfills. The failed artifact is absent and the readable artifact is still collected. The caught rejection is not the planning result.
  • A secret-like path is omitted without fs.read, and a later ordinary path is still read.
  • Unchanged filesystem reference: list and read run on the injected object, not on nodeFileSystem.
  • That injected filesystem records zero write, zero mkdir, and zero remove calls.

Symlink fixtures: document platform limits (create real symlink fixtures where the OS permits; otherwise mock isSymbolicLink). Real symlink fixtures cover the wrapper rejection. The delegate-only rejection remains the sequenced isSymbolicLink case above, because both checks see the same resolved root.

27.15 Stage B — planned architecture tests ​

Not implemented in this Design PR. The implementation pull request adds this suite. Results are in section 27.18.

Proposed file: tests/plan-pack-update-p1k12-structure.test.ts

After extraction, assert:

  • Single owning implementation in plan-pack-update.ts.
  • Direct public re-export of function and type from index.ts.
  • application.planPackUpdate === leaf export (function identity).
  • TypeScript public signature compatibility.
  • Allowed dependency direction; no ../index.js or package self-import on the leaf. The leaf does not import governance-adoption-contracts.ts. Its type-only adoption imports come from @intentloom/core/adoption. The delegate still imports PlanProjectAdoptionOptions from the contracts module.
  • applicationCycles membership unchanged vs section 8.1.
  • measureProductionSource on barrel and leaf; barrel must not contain the function body.
  • Existing CLI coverage still passes.
  • Package-export preservation. packages/application/package.json is not edited. planPackUpdate stays reachable only through the package root. The new structure test reads that file and asserts exports equals this map, including key order:
json
{
  ".": "./src/index.ts",
  "./model-adapter": "./src/model-adapter.ts",
  "./ollama-model-adapter": "./src/ollama-model-adapter.ts",
  "./neutron-runtime": "./src/neutron/neutron-runtime-contracts.ts",
  "./neutron-n2": "./src/neutron/neutron-n2-loop.ts",
  "./neutron-context-assembly": "./src/neutron/context/neutron-context-assembly.ts",
  "./neutron-n4": "./src/neutron/tools/neutron-tool-router.ts",
  "./neutron-scheduler": "./src/neutron/neutron-scheduler.ts",
  "./neutron-graph-mutation": "./src/neutron/neutron-graph-mutation.ts",
  "./neutron-session": "./src/neutron/session/neutron-session-runtime.ts",
  "./engineering-assessment": "./src/engineering-assessment.ts",
  "./engineering-quality": "./src/engineering-quality.ts"
}

Object.keys(exports) equals those keys in that order, and each key's target equals the value above. The existing Object.keys equality in tests/project-adoption-p1i3-structure.test.ts stays in that file at its current strength. This slice does not move or weaken it.

Relocate these assertions from tests/project-adoption-p1i3-structure.test.ts without reducing their strength:

  • /export async function planPackUpdate\(/ moves from index.ts to plan-pack-update.ts. After the move, index.ts must not match that function declaration.
  • /planProjectAdoption\(/ moves from index.ts to the leaf call. The barrel keeps export { planProjectAdoption } and is not required to contain a call. The leaf must still match the call.
  • expect(typeof application.planPackUpdate).toBe("function") stays on the barrel binding. Do not drop it when the source assertions move.

27.16 Mandatory sequence and non-goals ​

  1. Design PR (this change).
  2. Independent design review.
  3. Explicit Project Owner acceptance of section 27.17.
  4. Owner merge.
  5. Main verification.
  6. Separate implementation authorization.
  7. Stage A.
  8. Production extraction.
  9. Stage B.
  10. Independent implementation review.
  11. Owner merge.

This pull request stops at step 2.

The list above is the design-time gate. The actual order differed. PR #651 merged before owner acceptance. The owner then accepted section 27.17 and the Compatibility workflow deviation, conditionally authorized implementation, and main verification of a787faf succeeded. This implementation pull request stops at step 10, independent implementation review. It is not merged. The non-goals below still apply to behavior, schema, package exports, CI, and later slices.

Design-PR non-goals, preserved as history: P1K.13+, production code, tests, schema, package exports, CI, quality-exceptions.json, Neutron, Daemon, Desktop, and behavior changes. The implementation pull request was separately authorized to add this extraction and its tests. It still does not change behavior, schema, package exports, CI, quality-exceptions.json, Neutron, Daemon, Desktop, or start P1K.13.

27.17 Design First acceptance matrix ​

The rows below were PROPOSED in the design pull request. Green CI did not accept them. The Project Owner accepted all eleven after PR #651 merged at 2026-12-02 23:20:06 Europe/Berlin. The evidence is the supervising conversation. There is no GitHub review identifier and no exact acceptance timestamp in this repository. That acceptance was after the merge, not before it. It includes the Compatibility workflow changes in PR #651 as a scope deviation.

#Proposed decisionStatus
1Section 27 records the public signature and options on 23f5176ACCEPTED
2Both root symlink checks, order, and exact error messages stayACCEPTED
3Default nodeFileSystem and delegated argument contract stayACCEPTED
4Target-version nullish semantics and "1.1.0" default stayACCEPTED
5Base-plan reference on version match; shallow copy and operation identity on mismatch stayACCEPTED
6Existing planId and repositoryHash behavior without recomputation staysACCEPTED
7CLI update --plan / --apply / bare update compatibility in section 27.7 staysACCEPTED
8Ownership in plan-pack-update.ts and dependency direction in section 27.8 stayACCEPTED
9Cyclic-component membership stays section 8.1; new leaf stays outsideACCEPTED
10Stage A characterization commits before production extractionACCEPTED
11Implementation adds no unrelated behavioral changeACCEPTED

27.18 Implementation record ​

The extraction was in review when this subsection was written. It is now merged. Section 27.19 records PR #655 and does not replace the measurements below.

ItemRecord
Stage A commita677ac769776a379cd003ef5e08a2cc51c194ba8
Production extractionda8e74927a53ce1f4bf388d3e34ee4030aa10c78
Stage A filetests/plan-pack-update-p1k12-characterization.test.ts
Stage B filetests/plan-pack-update-p1k12-structure.test.ts
Leafpackages/application/src/project-adoption/plan-pack-update.ts
Barreldirect re-export; no forwarding wrapper

Stage A ran against the original barrel implementation before the production commit. Node v22.23.5, pnpm 10.12.4, Vitest 5.0.0. pnpm exec vitest run tests/plan-pack-update-p1k12-characterization.test.ts passed: 1 file, 21 tests, 0 skipped. The same file passed again after extraction. Related CLI and adoption tests stayed green in that post-extraction run: 7 files, 54 tests, 0 skipped (plan-pack-update characterization and structure, project-adoption-p1i3 behavior and structure, cli-pack-update, cli-update, and plan-feature-p1k11-structure).

Mocked delegation and real planner integration stay in one characterization file. vi.doMock loads a fresh module graph. The integration group calls the static planPackUpdate binding, which that mock does not replace. A second file was not required. The delegate constructs its symlink Error internally. No existing seam exposes that object before propagation, and no production hook was added. That case asserts Error class and the exact adoption-planning message. Injected filesystem rejections use rejects.toBe. Linux created the real symlink fixture for the wrapper rejection. The delegate-only rejection remains a sequenced isSymbolicLink double because both checks see the same resolved root.

applicationCycles(false) equals the section 8.1 import-only member set: the Neutron mutation trio. applicationCycles(true) equals the section 8.1 re-export member sets: the four extension-update files, the 27-file Approved Apply component that still contains index.ts, and the same Neutron trio. The structure test compares those arrays, not only the sizes [3] and [4, 27, 3]. project-adoption/plan-pack-update.ts is outside every component. The public planProjectAdoption export is the same function as the delegate leaf. Package export keys, order, and targets are unchanged. There is no project-adoption directory barrel. quality-exceptions.json is unchanged.

planId is still the delegated plan's identifier. A changed packVersion does not recompute it. That consistency concern remains technical debt.

Accessibility, AI evaluation, and product discovery are NOT APPLICABLE. CLI production code, Neutron, Daemon, Desktop, core adoption planning, and CI configuration were not modified. The accepted Compatibility changes from PR #651 remain the baseline.

Local verification on Node v22.23.5 and pnpm 10.12.4: pnpm verify exit 0. Typecheck passed. Lint passed with 307 existing warnings and none in the new leaf or P1K.12 tests. Format check passed. Vitest reported 404 files, 3413 passed, and 3 skipped in 240.45s. Build passed. git diff --check passed. pnpm docs:build exited 0 in 6.13s with the existing Rolldown plugin warnings. VitePress does not render Mermaid. Compatibility run 46993907291 on 16ddec5 failed in pnpm test on windows-latest Node 22 and Node 24. The characterization expected the POSIX string "/project" where resolve("/project") is drive-qualified. Ubuntu passed. macos-latest Node 22 was cancelled before any step, and Node 24 was skipped because it needs that job. That is runner acquisition, not a product failure. The follow-up characterization expects the resolved path. On b9ecb00dc5d08848a5666cb906b6487cfe6a9834, Compatibility run 46996737420 succeeded at 2026-12-03 00:50 Europe/Berlin. All six operating-system and Node.js jobs passed, including pnpm test. Governance run 46996737392, CodeQL run 46996737385, Desktop SEA run 46996737393, and harness benchmark run 46996737698 also succeeded. Documentation does not run on pull requests. Dependency review did not run. CI configuration was not changed.

27.19 Post-merge reconciliation ​

PR #655 merged the extraction. The merge commit is 89fbcd7c7656be0d6a37b06f1b70b575f19b2749, at 2026-12-03 22:02 Europe/Berlin. Section 27.18 was written while that pull request was in review. This subsection records the merge. It does not rewrite the Stage A evidence or the earlier CI notes above.

On 89fbcd7, Documentation run 47202449747 succeeded and CodeQL run 47202449499 succeeded. Compatibility run 47202449502 finished with workflow conclusion failure. Five jobs passed, including pnpm test: ubuntu Node 22 and Node 24, windows Node 22 and Node 24, and macos Node 22. macos-latest / Node 24 was cancelled. Its runner id was 0, its runner name was empty, and it executed no steps. The job started at 2026-12-03 22:21 Europe/Berlin and completed at 2026-12-03 22:36 Europe/Berlin. That cancellation is not a product regression and it is not a successful test run. This reconciliation does not mark it passed.

PR #657 then merged as 3d641e4a8a6b066ade281ce53b215d4a522b5b39 at 2026-12-03 22:51 Europe/Berlin. Its files are CHANGELOG.md, DUTY_WATCH.md, README.md, ROADMAP.md, and docs/index.md. It is documentation only. Current-main verification of that commit is section 28.20. The product bytes of the P1K.12 extraction are in that tree. The 89fbcd7 cancellation remains part of the record for that commit.

28. P1K.13 workspace composition bindings — Design First gate ​

Status: rows 1 through 10 of section 28.18 are ACCEPTED. Row 11 is PENDING. This section is the Design First gate for slice P1K.13 only. It does not authorize implementation. The acceptance record is in section 28.18. Merging this design, a previous roadmap approval, and the task prompt that requested this section were not owner acceptance of section 28.18. The parent roadmap in sections 9 and 10 remains the sequencing sketch. Section 28 is the verified contract.

Feasibility verdict: feasible. Alternative B is the recommended architecture. No proposed leaf needs to import packages/application/src/index.ts. That import is not an acceptable default, and this design does not use it.

28.1 Task triage ​

Printed before planning, then reassessed after discovery. The session model was not switched. No subagent was launched.

text
Task: P1K.13 workspace composition bindings — Design First
Environment: Cursor
Score: 5/10
Blast Radius: 2
Ambiguity: 1
Risk: 0
Verification: 2
Unknowns: 0
Recommended Model: mid
Reasoning Effort: high
Context Budget: larger
Delegation: none
Approval Required: yes
Stop Condition: Stop before repository edits if current main Compatibility is incomplete. Stop the design if a leaf would have to import the application barrel. Otherwise stop when the documentation pull request is ready for independent review.

The preliminary score was also 5/10, with blast radius 1 and unknowns 1. Discovery raised blast radius to 2 because the documentation change touches more than five files, and it lowered unknowns to 0 because the dependency graph, consumers, and measurements were read from this checkout. The sum stays 5. Ambiguity stays 1: alternatives A, B, and C were compared, and the import graph leaves one safe default. This is still an architectural choice, so the grilling workflow applies. Questions that the repository can answer are answered below. Decisions that belong to the Project Owner were PENDING in section 28.18 when this design was written. Section 28.18 records which rows the Project Owner has since accepted. Silence is not acceptance.

28.2 Problem and scope ​

packages/application/src/index.ts still owns three public declarations that only bind existing workspace reads:

  • InteractiveWorkspaceState (lines 536–554)
  • getInteractiveWorkspaceState (lines 556–577)
  • syncLocalWorkspaceState (lines 633–643)

Section 3.1 still lists InteractiveWorkspaceState at the original inventory lines 1635–1653. Those line numbers are not the current file. The remeasurement on 3d641e4 is the line range above, still 19 effective lines.

getInteractiveWorkspaceState returns the promise from assembleInteractiveWorkspaceState and passes inspectProject, doctorProject, diffProject, and timelineProject. syncLocalWorkspaceState returns the promise from assembleLocalWorkspaceSyncState and passes inspectProject, doctorProject, listWorkspaceConversations, and listNeutronSubagentTasks. Both default fs to nodeFileSystem.

Those callees already live on leaves. P1H.7 moved the assemblers and LocalWorkspaceSyncState to packages/application/src/workspace/interactive-workspace-read-model.ts. P1I moved inspection, doctor, and diff. P1K.10 moved timelineProject. P1K.8 moved listWorkspaceConversations. P1J moved listNeutronSubagentTasks. The barrel is no longer the owner of any port. Keeping the two bindings on the barrel is leftover composition, not a remaining domain rule.

This slice moves only those three declarations onto two existing-package leaves and re-exports them from the barrel. It does not change the assemblers, the ports, the CLI, the daemon, Desktop, or MCP.

28.3 Current architecture and responsibility map ​

mermaid
flowchart TB
  cliUi["CLI ui-command.ts"]
  cliNeutron["CLI neutron-command.ts"]
  cliBarrel["CLI index.ts star re-export"]
  barrel["application index.ts"]
  readModel["interactive-workspace-read-model.ts"]
  inspect["project-inspection.ts"]
  doctor["doctor-project.ts"]
  diff["project-plan.ts"]
  timeline["project-root.ts"]
  conversations["workspace-conversation-store.ts"]
  tasks["legacy-subagent-task-record.ts"]
  audit["security-audit-report-store.ts"]
  sessions["agent-session.ts"]
  host["host-file-system.ts"]

  cliUi -->|"getInteractiveWorkspaceState"| barrel
  cliNeutron -->|"syncLocalWorkspaceState"| barrel
  cliBarrel -->|"export star"| barrel
  barrel -->|"value import of both assemblers"| readModel
  barrel -->|"passes inspectProject doctorProject diffProject timelineProject"| readModel
  barrel -->|"passes inspectProject doctorProject listWorkspaceConversations listNeutronSubagentTasks"| readModel
  barrel --> inspect
  barrel --> doctor
  barrel --> diff
  barrel --> timeline
  barrel --> conversations
  barrel --> tasks
  barrel --> host
  readModel -->|"calls injected ports"| inspect
  readModel -->|"calls injected ports"| doctor
  readModel -->|"calls injected ports"| diff
  readModel -->|"calls injected ports"| timeline
  readModel -->|"calls injected ports"| conversations
  readModel -->|"calls injected ports"| tasks
  readModel --> audit
  readModel --> sessions
  readModel --> host

Editable source: workspace-composition-current.mmd.

ResponsibilityCurrent ownerPublic?
InteractiveWorkspaceStateindex.tstype export
getInteractiveWorkspaceStateindex.tsvalue export
syncLocalWorkspaceStateindex.tsvalue export
LocalWorkspaceSyncStateworkspace/interactive-workspace-read-model.tsexport type from the barrel
assembleInteractiveWorkspaceStatesame read modelno
assembleLocalWorkspaceSyncStatesame read modelno
inspectProjectproject-lifecycle/project-inspection.tsbarrel re-export
doctorProjectproject-lifecycle/doctor-project.tsbarrel re-export
diffProjectproject-lifecycle/project-plan.tsbarrel re-export
timelineProjectproject-lifecycle/project-root.tsbarrel re-export
listWorkspaceConversationsworkspace/workspace-conversation-store.tsbarrel re-export
listNeutronSubagentTasksworkspace/legacy-subagent-task-record.tsbarrel re-export
FileSystem, nodeFileSystemhost-file-system.tsbarrel re-export

doctorProject still has an optional third argument, validationResults, defaulting to []. The assembler calls it with two arguments. timelineProject does not take a filesystem. The bindings do not wrap either function.

There is no packages/application/src/workspace/index.ts. The package export map has twelve keys and no workspace subpath:

. , ./model-adapter, ./ollama-model-adapter, ./neutron-runtime, ./neutron-n2, ./neutron-context-assembly, ./neutron-n4, ./neutron-scheduler, ./neutron-graph-mutation, ./neutron-session, ./engineering-assessment, ./engineering-quality.

28.4 Consumers ​

Direct production callers, all through @intentloom/application:

  • packages/cli/src/ui-command.ts imports getInteractiveWorkspaceState and the InteractiveWorkspaceState type. runUiCommand passes { root, projectId, activeView } and the CLI filesystem.
  • packages/cli/src/neutron-command.ts imports syncLocalWorkspaceState. The sync section passes { root } and the CLI filesystem. It does not pass projectId.
  • packages/cli/src/index.ts star-re-exports @intentloom/application, so every public name stays visible from the CLI package entry.

Direct test callers of the public functions:

  • tests/workspace-read-model-p1h7.test.ts
  • tests/security-audit-behavior-p1h6.test.ts
  • tests/interactive-ui.test.ts
  • tests/cli-neutron.test.ts
  • tests/neutron-orchestration.test.ts
  • tests/legacy-subagent-task-record-p1j-characterization.test.ts
  • tests/v1-client-surface-equivalence.test.ts
  • tests/v1-compatibility-contract.test.ts

Transitive or neighboring surfaces that do not import these symbols:

  • apps/desktop does not import @intentloom/application. Workspace views use @intentloom/protocol. This slice does not change them.
  • packages/daemon imports other application operations. A repository search found no reference to getInteractiveWorkspaceState, syncLocalWorkspaceState, or InteractiveWorkspaceState.
  • packages/mcp-server imports other application operations, including nodeFileSystem. It does not import these three declarations.

The only production definition of the two functions is the barrel. The read model does not call them. No proposed leaf imports the barrel.

28.5 Domain boundaries ​

The ubiquitous language already has Agent Workspace. These bindings are application composition over that read model. They are not a new bounded context, aggregate, or domain event. InteractiveWorkspaceState is the public snapshot type. LocalWorkspaceSyncState stays the sync snapshot owned by the read model. The private InteractiveWorkspaceView union inside the read model stays private. This slice does not unify those two spellings.

docs/governance/DOMAIN_MODELING.md does not require a new pattern here. No ADR is required: the move follows ADR-0033 and ADR-0036 by keeping the same public operations, and it follows the P1K dependency rule that a leaf must not import the barrel.

28.6 Proposed architecture ​

text
packages/application/src/index.ts
packages/application/src/workspace/interactive-workspace-composition.ts
packages/application/src/workspace/local-workspace-sync.ts
packages/application/src/workspace/interactive-workspace-read-model.ts

The first three lines are the only production files this slice changes or adds. The read model is not edited. No workspace/index.ts is added. No package export key is added. No new directory is added.

mermaid
flowchart TB
  cliUi["CLI ui-command.ts"]
  cliNeutron["CLI neutron-command.ts"]
  cliBarrel["CLI index.ts star re-export"]
  barrel["application index.ts"]
  interactive["interactive-workspace-composition.ts"]
  sync["local-workspace-sync.ts"]
  readModel["interactive-workspace-read-model.ts"]
  inspect["project-inspection.ts"]
  doctor["doctor-project.ts"]
  diff["project-plan.ts"]
  timeline["project-root.ts"]
  conversations["workspace-conversation-store.ts"]
  tasks["legacy-subagent-task-record.ts"]
  audit["security-audit-report-store.ts"]
  sessions["agent-session.ts"]
  host["host-file-system.ts"]

  cliUi -->|"unchanged package import"| barrel
  cliNeutron -->|"unchanged package import"| barrel
  cliBarrel -->|"export star"| barrel
  barrel -->|"direct re-export"| interactive
  barrel -->|"direct re-export"| sync
  barrel -->|"export type LocalWorkspaceSyncState"| readModel
  interactive -->|"same options and fs"| readModel
  sync -->|"same options and fs"| readModel
  interactive --> inspect
  interactive --> doctor
  interactive --> diff
  interactive --> timeline
  interactive --> host
  sync --> inspect
  sync --> doctor
  sync --> conversations
  sync --> tasks
  sync --> host
  readModel --> audit
  readModel --> sessions
  readModel --> host

Editable source: workspace-composition-proposed.mmd.

Ownership after the move:

DeclarationCanonical ownerBarrel
InteractiveWorkspaceStateworkspace/interactive-workspace-composition.tsexport { type InteractiveWorkspaceState }
getInteractiveWorkspaceStatesame fileexport { getInteractiveWorkspaceState }
syncLocalWorkspaceStateworkspace/local-workspace-sync.tsexport { syncLocalWorkspaceState }
LocalWorkspaceSyncStateread model, unchangedexport type { LocalWorkspaceSyncState } from the read model

The barrel re-export is the public function. After the move, getInteractiveWorkspaceState on @intentloom/application is the same function object as the composition-leaf export, and syncLocalWorkspaceState is the same function object as the sync-leaf export. There is no forwarding wrapper on the barrel.

InteractiveWorkspaceState moves with getInteractiveWorkspaceState. P1H.7 left it on the barrel because its field types were declared only there. That reason is gone: ProjectInspection and DoctorFinding live in project-lifecycle-contracts.ts, Plan lives in project-change.ts, ProjectTimeline lives in project-root.ts, and ContinuousSecurityAuditReport and AgentSessionItem live in @intentloom/protocol. The public interface text stays the same, including readonly, null, and the seven active-view literals inspect, doctor, diff, timeline, health, security, and sessions.

28.7 Dependency direction and import mapping ​

Neither leaf imports index.ts, index.js, or @intentloom/application.

interactive-workspace-composition.ts imports:

SymbolModule
AgentSessionItem, ContinuousSecurityAuditReport@intentloom/protocol (type only)
nodeFileSystem, FileSystem../host-file-system.js
inspectProject../project-lifecycle/project-inspection.js
doctorProject../project-lifecycle/doctor-project.js
diffProject../project-lifecycle/project-plan.js
timelineProject, ProjectTimeline../project-lifecycle/project-root.js
DoctorFinding, ProjectInspection../project-lifecycle/project-lifecycle-contracts.js (type only)
Plan../project-change.js (type only)
assembleInteractiveWorkspaceState./interactive-workspace-read-model.js

The port object is exactly:

text
{
  inspectProject,
  doctorProject,
  diffProject,
  timelineProject,
}

local-workspace-sync.ts imports:

SymbolModule
nodeFileSystem, FileSystem../host-file-system.js
inspectProject../project-lifecycle/project-inspection.js
doctorProject../project-lifecycle/doctor-project.js
listWorkspaceConversations./workspace-conversation-store.js
listNeutronSubagentTasks./legacy-subagent-task-record.js
assembleLocalWorkspaceSyncState, LocalWorkspaceSyncState./interactive-workspace-read-model.js

The port object is exactly:

text
{
  inspectProject,
  doctorProject,
  listWorkspaceConversations,
  listNeutronSubagentTasks,
}

Key order is part of the contract because Object.keys can observe it. Each property is the canonical function, not a wrapper. The implementation imports those functions from the modules above, so the leaf binding and the existing barrel binding are the same function objects.

The barrel deletes the value import of the two assemblers. It keeps the existing import-and-export pairs for inspectProject, doctorProject, diffProject, initProject, timelineProject, the Neutron task functions, and the conversation functions. Those pairs are still used by the public re-exports. This slice does not convert them to export { ... } from.

The exact edit for LocalWorkspaceSyncState is this. Today the barrel has one import block from the read model (lines 518–522 on e377b29, two assemblers plus type LocalWorkspaceSyncState) and a separate export type { LocalWorkspaceSyncState }; (line 534). After the move the whole import block is deleted, and line 534 becomes export type { LocalWorkspaceSyncState } from "./workspace/interactive-workspace-read-model.js";. The barrel keeps no local binding of that type. The barrel line count in section 28.12 assumes this form. The P1H.7 structure assertion toContain("export type { LocalWorkspaceSyncState }") accepts it, so that assertion does not need to change.

Two local type imports become unused once the interface leaves the barrel, and lint would reject them:

  • import type { Plan } from "./project-change.js". The public type stays on the existing export type { Change, ChangeKind, Plan } from "./project-change.js".
  • type DoctorFinding and type ProjectInspection in the local contracts import. The public types stay on the existing export type from project-lifecycle-contracts.ts.

That cleanup removes the import-only edge from index.ts to project-change.ts. project-change.ts has no relative imports and is in no strongly connected component. Removing the edge cannot add or remove a component member. DoctorFinding and ProjectInspection remain reachable from the barrel through the existing export type from the contracts module, which is a re-export edge, not a new cycle.

applicationCycles counts import type as an import edge. The new leaves' type imports point at modules whose closures do not include index.ts.

Measured on 3d641e4a8a6b066ade281ce53b215d4a522b5b39 with the same specifier resolver as tests/application-source-cycles.ts. reachesIndex is false for every owner the leaves import:

SeedClosure sizeReaches index.ts
workspace/interactive-workspace-read-model.ts6no
project-lifecycle/project-inspection.ts10no
project-lifecycle/doctor-project.ts38no
project-lifecycle/project-plan.ts16no
project-lifecycle/project-root.ts3no
project-lifecycle/project-lifecycle-contracts.ts5no
workspace/workspace-conversation-store.ts4no
workspace/legacy-subagent-task-record.ts4no
host-file-system.ts2no
project-change.ts1no
agent-session/agent-session.ts4no
security/security-audit-report-store.ts4no

The read-model closure is the module itself plus agent-session.ts, host-file-system.ts, security-audit-report-store.ts, and project-path.ts / project-scan-exclusions.ts behind those. It does not include continuous-security-audit.ts. The new leaves do not add that import.

28.8 Public API compatibility ​

ContractRequired result
NamesInteractiveWorkspaceState, getInteractiveWorkspaceState, syncLocalWorkspaceState, and LocalWorkspaceSyncState stay exported from @intentloom/application
Value identityThe two functions on the package are the leaf functions (===)
Type identityInteractiveWorkspaceState is not a runtime value. "InteractiveWorkspaceState" in application stays false. The same is already true for LocalWorkspaceSyncState
OptionsgetInteractiveWorkspaceState keeps { root: string; projectId?: string; activeView?: <seven literals> }. syncLocalWorkspaceState keeps { root: string; projectId?: string }
FilesystemSecond parameter fs: FileSystem = nodeFileSystem. Omitted and explicit undefined both select nodeFileSystem. Any other value is forwarded by object identity
ReturnPromise<InteractiveWorkspaceState> and Promise<LocalWorkspaceSyncState>
Delegationreturn assemble...(options, fs, ports) with the same options object, not a copy
Active viewThe binding does not default activeView. The assembler still uses options.activeView ?? "inspect"
Project idThe assembler still uses options.projectId ?? "project-local"
Package exportsThe twelve keys, their order, and their targets stay
CLIintentloom ui and intentloom neutron sync keep their current calls. The UI cast that omits health from its local view union stays as it is. The application union still includes health

LocalWorkspaceSyncState fields stay projectId, root, readiness, findingsCount, securityScore (number | null), activeConversationsCount, subagentTasksCount, and syncedAt, all readonly where they are today. A stored health score of 0 stays 0.

28.9 Execution flows ​

Success path for the interactive binding. Editable source: workspace-composition-sequence.mmd.

mermaid
sequenceDiagram
  participant Caller
  participant Binding as getInteractiveWorkspaceState
  participant Assemble as assembleInteractiveWorkspaceState
  participant Inspect as inspectProject
  participant Doctor as doctorProject
  participant Diff as diffProject
  participant Timeline as timelineProject
  participant Audit as getSecurityAuditReport
  participant Sessions as listAgentSessions

  Caller->>Binding: options and optional fs
  alt fs omitted or undefined
    Binding->>Binding: fs is nodeFileSystem
  else caller supplied fs
    Binding->>Binding: forward that FileSystem object
  end
  Binding->>Assemble: same options object, same fs, four canonical ports
  par concurrent reads
    Assemble->>Inspect: root and fs
    Inspect-->>Assemble: ProjectInspection
  and
    Assemble->>Doctor: root, profile generic, adapters codex, and fs
    Doctor-->>Assemble: DoctorPlan
  and
    Assemble->>Diff: root, profile generic, adapters codex, dryRun true, and fs
    Diff-->>Assemble: Plan
  and
    Assemble->>Timeline: root, caseId tui-timeline, limit 50
    Note over Timeline: timelineProject receives no filesystem argument
    Timeline-->>Assemble: ProjectTimeline
  and
    Assemble->>Audit: root and fs
    Audit-->>Assemble: stored report or null
  and
    Assemble->>Sessions: root and fs
    Sessions-->>Assemble: readonly sessions
  end
  Note over Assemble: activeView defaults to inspect inside the assembler
  Assemble-->>Binding: InteractiveWorkspaceState
  Binding-->>Caller: same promise result

Success and failure path for sync. Editable source: workspace-composition-sync-sequence.mmd. The awaits stay sequential. listWorkspaceConversations is not called when an earlier await rejects. That matches the current assembler and tests/workspace-read-model-p1h7.test.ts.

mermaid
sequenceDiagram
  participant Caller
  participant Binding as syncLocalWorkspaceState
  participant Assemble as assembleLocalWorkspaceSyncState
  participant Inspect as inspectProject
  participant Doctor as doctorProject
  participant Audit as getSecurityAuditReport
  participant Conversations as listWorkspaceConversations
  participant Tasks as listNeutronSubagentTasks

  Caller->>Binding: options and optional fs
  alt fs omitted or undefined
    Binding->>Binding: fs is nodeFileSystem
  else caller supplied fs
    Binding->>Binding: forward that FileSystem object
  end
  Binding->>Assemble: same options object, same fs, four canonical ports
  Assemble->>Inspect: root and fs
  alt inspectProject rejects
    Inspect-->>Assemble: rejection
    Assemble-->>Binding: same rejection
    Binding-->>Caller: propagated rejection and later ports are not called
  else inspection returned
    Inspect-->>Assemble: inspection with readiness
    Assemble->>Doctor: root, profile generic, adapters codex, and fs
    alt doctorProject rejects
      Doctor-->>Assemble: rejection
      Assemble-->>Binding: same rejection
      Binding-->>Caller: propagated rejection
    else doctor returned
      Doctor-->>Assemble: DoctorPlan
      Assemble->>Audit: root and fs
      alt getSecurityAuditReport rejects
        Audit-->>Assemble: rejection
        Assemble-->>Binding: same rejection
        Binding-->>Caller: propagated rejection and conversations are not listed
      else report returned or missing
        Audit-->>Assemble: report or null
        Assemble->>Conversations: root and fs
        Conversations-->>Assemble: conversation records
        Assemble->>Tasks: root and fs
        Tasks-->>Assemble: task records
        Assemble-->>Binding: LocalWorkspaceSyncState
        Binding-->>Caller: same promise result
      end
    end
  end

The sync diagram draws the inspect, doctor, and audit rejections at their own awaits, then the success path through conversations and tasks.

Failure classes for the interactive binding. Editable source: workspace-composition-failure-sequence.mmd.

mermaid
sequenceDiagram
  participant Caller
  participant Interactive as getInteractiveWorkspaceState
  participant Sync as syncLocalWorkspaceState
  participant Assemble as assembler

  Note over Caller, Assemble: Caught interactive readers still resolve
  Caller->>Interactive: getInteractiveWorkspaceState
  Interactive->>Assemble: same options, fs, and ports
  Assemble-->>Interactive: snapshot with null or an empty session list
  Interactive-->>Caller: resolved snapshot

  Note over Caller, Assemble: doctorProject rejection propagates
  Caller->>Interactive: getInteractiveWorkspaceState
  Interactive->>Assemble: same options, fs, and ports
  Assemble-->>Interactive: doctor rejection
  Interactive-->>Caller: same rejection

  Note over Caller, Assemble: sync rejection stops later awaits
  Caller->>Sync: syncLocalWorkspaceState
  Sync->>Assemble: same options, fs, and ports
  Assemble-->>Sync: rejection from the current await
  Sync-->>Caller: same rejection and later ports are not called

28.10 Error, filesystem, and security boundaries ​

The bindings contain no try/catch and no call to a FileSystem method. They return the assembler promise, so the rejection object is the assembler rejection. No new error type is introduced.

FailureInteractive resultSync result
inspectProject rejectsinspect is nullrejection propagates; later awaits do not run
doctorProject rejectsrejection propagatesrejection propagates
diffProject rejectsdiff is nullnot called
timelineProject rejects, including ProjectRootErrortimeline is nullnot called
getSecurityAuditReport rejectsauditReport is nullrejection propagates; conversations are not listed
missing or unreadable audit reportauditReport is nullsecurityScore is null
stored score 0report score stays 0securityScore is 0
listAgentSessions rejectssessions is []not called
listWorkspaceConversations or listNeutronSubagentTasks rejectsnot called by this bindingrejection propagates

runContinuousSecurityAudit is not on either path. The read model reads the stored report through getSecurityAuditReport. This slice does not change that, and it does not make the readers execute an audit.

Filesystem boundary: the caller chooses the FileSystem. The default is the nodeFileSystem object from host-file-system.ts. Path containment, symlink inspection, and timeline canonicalization stay inside the current callees. The bindings do not resolve a root and do not write. Persistence behavior stays whatever the unchanged callees do today. Stage A records the public functions' mutation counts on a memory filesystem and the extraction keeps those counts. This design does not claim a new zero-write proof beyond the current tests and that future characterization.

Security boundary: no new trust boundary, network call, or capability. Doctor and diff stay on the assembler inputs profile: "generic", adapters: ["codex"], and, for diff, dryRun: true. Conversation listing and task listing stay read paths. Secret redaction inside the conversation store is unchanged because that store is not edited.

Accessibility, product analytics, and AI evaluation are NOT APPLICABLE. This design does not change a user-facing interface, a telemetry event, or an evaluation set. The CLI text and JSON shapes stay behind the same functions.

Renderer note: VitePress does not render Mermaid. The .mmd files are the editable source, and the fenced copies in this section match those files. Mermaid 12.4.1 parse accepted all five diagrams. The three sequence diagrams parsed in plain Node. The two flowcharts parsed after a jsdom window was installed, because flowchart text sanitizing calls DOMPurify and that call throws DOMPurify.addHook is not a function in this headless Node process before a window exists. That exception is an environment limit of the flowchart sanitizer, not a diagram syntax error. The failure sequence uses notes rather than shaded rect blocks. par and alt follow the sequence grammar already used in this folder.

28.11 Alternatives ​

OptionResultDecision
A. Leave both bindings on index.tsNo cycle risk and no test-path updates. The barrel keeps 52 effective lines of composition that no longer own their callees. P1K.17 still lists P1K.13 as a prerequisite, so deferring the move keeps the export-from barrel blocked on this sliceReject
B. Two leaves, direct imports from the current owners, barrel re-exports the same functionsMatches the distinct port sets. Closures do not reach the barrel, so no new component is created. Public identity is the leaf function. Test updates are path assertions, not weaker contractsRecommend
C. Another dependency-injection composition moduleJustified only if a leaf otherwise had to import the barrel. P1H.7 already injected these ports for that reason. The owners are leaves now. A second seam would add a module without removing a cycleReject

A one-file variant of B would also avoid the barrel, and it would stay under the file budget. It is not recommended. The interactive binding owns a public snapshot type and four project-lifecycle ports. The sync binding owns no snapshot type and two workspace ports. Separate files keep that difference visible and match the section 10 targets. The owner can still choose one file in section 28.18; this design does not expand the slice to make either shape fit.

Option B does not retarget Neutron, Approved Apply, or engineering-quality imports. P1K.14 through P1K.16 keep their current prerequisites and their section 16 membership forecasts. P1K.17 still waits for P1K.13, P1K.15, and P1K.16.

28.12 Measurements and forecast ​

Observed on 3d641e4a8a6b066ade281ce53b215d4a522b5b39 with measureProductionSource. Node v22.23.5, pnpm 10.12.4. These are measurements, not forecasts.

File or declarationEffectivePhysical
packages/application/src/index.ts629659
InteractiveWorkspaceState (lines 536–554)1919
getInteractiveWorkspaceState (lines 556–577)2222
syncLocalWorkspaceState (lines 633–643)1111
read model, locked by P1H.7 and not edited205219

applicationCycles(false) sizes are [3]. applicationCycles(true) sizes are [4, 27, 3]. Member lists match section 8.1 exactly, including file order. The comparison was the arrays, not only the sizes.

Forecast, separate from the measurement. A Prettier 3.9.6 formatting of the proposed barrel and the two leaves was measured in a temporary copy. It was not written into the repository.

Forecast fileEffectivePhysical
index.ts after the move and the unused type-import deletion574602
interactive-workspace-composition.ts5961
getInteractiveWorkspaceState inside that leaf2222
local-workspace-sync.ts2021
syncLocalWorkspaceState inside that leaf1111

The net barrel change is 55 effective lines (629 − 574), not the section 10 sketch of about 46. The difference is the assembler import and the two unused type imports leaving with the 52 lines of interface and function text, minus six re-export lines. Section 15's cell of 569 was a running estimate that assumed a post-P1K.12 barrel near 615. The observed post-P1K.12 barrel is 629. The 569 cell stays historical. Stage B locks the measured file, not 574 and not 569. A different import grouping may change physical lines by a few blanks. It must not change the function texts, so the 22, 19, and 11 line function and interface figures stay unless a formatter wraps a signature. If that happens, Stage B records the observed function size and still enforces the 40-line preference and the 80-line hard limit.

Both leaves are under the 250-line preference. Neither function exceeds 40 effective lines. quality-exceptions.json is not edited. The existing exception and its P1J hash stay.

28.13 Strongly connected components ​

Current membership is section 8.1, re-measured on this commit. P1K.13 must leave that membership unchanged:

  • Import-only: the Neutron mutation trio only.
  • Re-export size 4: the four extension-update files.
  • Re-export size 27: the Approved Apply component that still contains index.ts, ending with inception-flow.ts and index.ts in the section 8.1 order.
  • Re-export size 3: the same Neutron trio.

Both new files stay outside every component. The read model stays outside every component. No cycle allowlist is extended. P1K.14's predicted drop from 27 to 19 files is unchanged because this slice does not retarget the engine, harness, quality, or adoption back-edges.

28.14 Planning ​

Objective: remove barrel-owned workspace composition now that every port has a leaf owner, without any user-facing change. Engineering value is a smaller barrel, one owner per declaration, and a P1K.17 prerequisite that does not enlarge the Approved Apply component. This is not a new product capability.

Work breakdown:

  1. This design, independent review, and explicit section 28.18 acceptance.
  2. Separate implementation authorization after the design merge and successful main verification of that merge commit.
  3. Stage A characterization, committed before the production move.
  4. Add the two leaves, re-export them, and delete only the unused type imports named in section 28.7.
  5. Stage B structural assertions, including the seventeen barrel-size locks.
  6. pnpm verify and pull-request review. The owner merges.

SWOT, for this extraction rather than for a generic refactor:

  • Strength: the P1H.7 seam and the later leaf moves already removed the reason to keep the bindings on the barrel. Closures measured in section 28.7 do not reach index.ts.
  • Weakness: the barrel remains above 400 effective lines after the forecast 574. Seventeen structure tests repeat the same size lock. The public snapshot type still duplicates the private view union.
  • Opportunity: P1K.17 can delete the remaining value-import preamble only after this body, the engineering-quality retarget, and the adoption retarget are gone.
  • Threat: a leaf import of the barrel would put the new files, and any module they drag in, into the 27-file component. A Stage B edit that drops the four-port source assertion would hide a wrapper. A cancelled macOS runner is neither a product regression nor a passing matrix.

Recommended decision: Alternative B, two leaves, direct owner imports.

RAID:

text
Risk: A new leaf imports the application barrel.
Cause: A port looks more convenient from index.ts than from its leaf.
Potential impact: The 27-file component grows and later P1K forecasts become false.
Likelihood: Low. The measured closures do not require that import.
Severity: High for the stabilization program.
Mitigation: Section 28.7 import map. Stage B rejects index.js and @intentloom/application in both leaves.
Contingency: Stop the implementation pull request. Do not add a cycle allowlist.
Responsible: Coding Agent during implementation. Project Owner if the stop is hit.
Trigger: Any specifier that resolves to index.ts.
Status: Open until Stage B passes. Not an issue in the current graph.

Risk: Stage A mocks replace the assembler and stop locking real catch behavior.
Cause: One mock is used for both identity and runtime behavior.
Potential impact: A wrapper could swallow doctor errors and still pass.
Likelihood: Medium if the test design is collapsed.
Severity: Medium. Behavior preservation is the point of the slice.
Mitigation: Separate identity mocks from call-through or real filesystem cases. Keep the existing P1H.7, P1H.6, CLI, and Neutron suites.
Contingency: Add the missing case before the production commit. Do not weaken an existing assertion.
Responsible: Coding Agent.
Trigger: A characterization file that never calls the real assembler.
Status: Open for the implementation. The design requires the split.

Risk: The historical 569 or the forecast 574 is copied into a test as if it were observed.
Cause: Section 15 and section 10 are running estimates.
Potential impact: A false lock, or a lock that fails on the first format.
Likelihood: Medium if Stage B is written from the design table alone.
Severity: Low. The fix is to remeasure.
Mitigation: Stage B uses measureProductionSource on the committed files.
Contingency: Update the lock to the observed value in the same implementation pull request. Do not change quality-exceptions.json.
Responsible: Coding Agent.
Trigger: The first structure run after the move.
Status: Open until that measurement exists.

Risk: A later Compatibility job is cancelled before any step, as on 89fbcd7 macOS / Node 24.
Cause: Runner acquisition, not this design.
Potential impact: The workflow conclusion is failure even when five jobs passed their tests.
Likelihood: Already observed once on the previous main commit.
Severity: Medium for verification evidence. It is not a product defect.
Mitigation: Record runner id, step count, and conclusion. Do not edit the workflow to skip macOS.
Contingency: The owner or GitHub reruns the job. This design does not rerun it and does not change CI.
Responsible: Project Owner for a rerun decision.
Trigger: A job with runner id 0 and no steps, or any incomplete required matrix.
Status: Open as an operational record. The 89fbcd7 cancellation stays cancelled.

Assumptions:

  • P1K.8 and P1K.10 stay merged. Both are on this main.
  • Section 8.1 membership stays current. It was re-measured, not assumed from the old write-up.
  • The repository search covered production callers. A later caller that imports the package root still compiles because the re-exports stay.
  • doctorProject's optional third parameter stays unused by the assembler.

Issue: project-state documents still described P1K.12 as unmerged and the public-description pull request as unmerged. This pull request reconciles those records. It does not rewrite the original Duty Watch entries that were accurate when they were written.

Dependencies: P1K.8 and P1K.10 are satisfied. P1K.14 does not depend on P1K.13. P1K.17 depends on P1K.13. Implementation depends on section 28.18 acceptance plus a separate authorization after main verification of the design merge. Inloom, the AI Software Factory plans, Agent Intelligence, and Project Lantern stay documentation. This slice does not authorize them.

RACI:

DeliverableResponsibleAccountableConsultedInformed
This designCoding AgentProject OwnerMaster Agent, independent reviewNext watch
Section 28.18 acceptanceProject OwnerProject OwnerMaster AgentCoding Agent
Future Stage A and extractionCoding Agent, only after a separate authorizationProject OwnerMaster AgentNext watch
MergeProject OwnerProject OwnerIndependent reviewerNext watch

One person may hold several roles. The Coding Agent does not approve or merge. The Master Agent reviews. The independent reviewer inspects the implementation diff when that pull request exists. This design pull request has no implementation diff.

Effort, distinct from calendar duration and from time already spent in this session. Calendar duration is not estimated. The future extraction is a small structural move: two new files, a barrel re-export, unused type-import deletion, and characterization plus structure tests. Relative size is smaller than P1K.12's planning rules and similar in verification weight because pnpm verify and the seventeen barrel locks still run. Confidence is high on the dependency direction and medium on the mock split, which is why Stage A is specified before the move. This session's reading and writing are observed execution of the design, not an estimate of the implementation.

Stages and dependencies:

  1. Design review. Depends on the current main verification recorded in section 28.20.
  2. Owner acceptance of every section 28.18 row.
  3. Separate implementation authorization. Depends on step 2 and on successful main verification of the design merge commit.
  4. Stage A commit. Depends on step 3. No production edit in that commit.
  5. Production move and Stage B. Depends on Stage A being green against the pre-move barrel.
  6. Independent implementation review and owner merge.

Acceptance for this design pull request:

  • Section 28 states Alternative B, the import map, the compatibility matrix, and the pending owner rows.
  • No production source, test, package export, CI workflow, or quality-exceptions.json change is in the diff.
  • git diff --check, pnpm docs:build, and pnpm verify are recorded with the commands that actually ran.
  • Duty Watch, project state, the docs index, and the stabilization plan match the merged P1K.12 and PR #657 evidence without marking the cancelled macOS job as passed.

Acceptance for a future implementation, not met by this pull request:

  • Stage A was committed before the production move and passed against the original barrel.
  • The two leaves match section 28.7, and the barrel re-exports are direct.
  • Public function identity holds with toBe.
  • Package export keys are unchanged.
  • applicationCycles member arrays equal section 8.1.
  • Both new files are outside every component.
  • P1J still asserts the four port keys and the canonical function identities, with the source path moved to local-workspace-sync.ts.
  • The seventeen barrel-size locks use the observed measurement. Section 28.16 lists them.
  • tests/application-neutron-topology.test.ts is unchanged and passes.
  • quality-exceptions.json is unchanged.
  • CLI ui and Neutron sync tests pass.
  • No behavior outside this slice changes.
  • All new Stage A and Stage B test files respect the budget in section 28.15.
  • Section 28.22 is filled with observed values, and PROJECT_STATE.md, DUTY_WATCH.md, CHANGELOG.md, and the stabilization plan match them.

Stop conditions:

  • Current main Compatibility, CodeQL, or Documentation is not successful before the first repository edit. This design does not start in that case.
  • A leaf needs an import of the application barrel. Stop and record the conflict. Do not add the import.
  • Measured SCC membership changes, or either new file appears in a component.
  • A test, cycle allowlist, or quality exception would have to be weakened.
  • The implementation pull request starts P1K.14 or any later slice, Undo U4, Desktop Undo U5, or P2–P6.
  • Verification fails for a reason that would require a production or CI edit outside the approved design. Fix only inside the design's documentation scope for this pull request, and inside the approved extraction for the future pull request.

28.15 Stage A characterization ​

Design only. This pull request does not add the test. The future file is tests/workspace-composition-p1k13-characterization.test.ts. It is committed before the production extraction and must pass against the current barrel. It imports the public functions from @intentloom/application.

Cover at least:

  • Options objects are forwarded by identity to the assembler, including omitted projectId and omitted activeView.
  • fs omitted, fs passed as undefined, and fs passed as a distinct object. The first two select nodeFileSystem. The third is the same object the assembler receives.
  • Port keys, key order, and function identity (===) for both port objects against inspectProject, doctorProject, diffProject, timelineProject, listWorkspaceConversations, and listNeutronSubagentTasks from their canonical modules.
  • activeView omitted yields "inspect" from the real assembler. Each of the seven literals is returned unchanged when supplied. The CLI omission of health is not "fixed".
  • projectId omitted yields "project-local".
  • Interactive catch matrix: inspect, diff, timeline, audit, and sessions rejections still resolve; doctor rejection still rejects with the same error.
  • Sync propagation: an inspect rejection rejects and does not call listWorkspaceConversations. An audit rejection rejects and does not list conversations. This can call through to the real assembler with mocked ports, or use the existing P1H.7 pattern.
  • runContinuousSecurityAudit is not called by either public reader. Existing tests/security-audit-behavior-p1h6.test.ts still shows a stored report flowing into both public results, including score 0.
  • A memory filesystem records write, mkdir, and remove. After both public calls, those counts match the pre-call snapshot. The characterization records the observed counts. It does not invent a new write.
  • Existing CLI coverage stays in tests/interactive-ui.test.ts, tests/cli-neutron.test.ts, and the CLI case in tests/workspace-read-model-p1h7.test.ts. Stage A does not copy those suites. The implementation runs them.

Use vi.mock only with hoisting so the barrel and the test see the same assembler or port. Do not add a production hook so a test can see a private port. P1K.12's vi.doMock note applies if a static import would capture the real assembler before the mock: reload a fresh graph, and keep a call-through case that is not mocked away.

Test file budget. CODE_QUALITY_STANDARDS.md section 3 prefers at most 400 lines per test file and sets 700 physical lines as the hard limit for a new test file. The scenario list above is long, and the P1K.12 characterization file reached 636 lines. One file stays the default. If the file passes 400 physical lines, split it at the scenario boundary and do not compress assertions:

  • tests/workspace-composition-p1k13-characterization.test.ts: option and fs forwarding, port keys, order and identity, and the activeView and projectId defaults.
  • tests/workspace-composition-p1k13-failure-characterization.test.ts: the interactive catch matrix, sync propagation, the runContinuousSecurityAudit absence, and the memory-filesystem mutation counts.

Commit every Stage A file before the production move and run the complete Stage A suite against the original barrel and again after the move. Stage B follows the same file budget. A file above 700 physical lines needs the exception record in CODE_QUALITY_STANDARDS.md section 7. The Stage A and Stage B commits record the measured line counts.

Filesystem scope of the mutation counts. timelineProject takes no FileSystem. It resolves the root through the host nodeFileSystem default in assertCanonicalProjectRoot and then runs git through @intentloom/evidence-git. The memory-filesystem counters therefore observe only the injected FileSystem. They do not observe that host and git path. On a memory root such as /project, the real call usually rejects with ProjectRootError and timeline is null. The success branch of the timeline port stays covered by the injected-port tests in tests/workspace-read-model-p1h7.test.ts, not by Stage A through the public binding. Stage A records this scope and does not claim a host-level zero-write proof.

28.16 Stage B structural verification ​

Design only. The future file is tests/workspace-composition-p1k13-structure.test.ts, plus updates to existing assertions. Do not weaken them.

  • One owner: index.ts contains no function getInteractiveWorkspaceState, no function syncLocalWorkspaceState, and no interface InteractiveWorkspaceState.
  • The composition leaf contains the interface and export async function getInteractiveWorkspaceState.
  • The sync leaf contains export async function syncLocalWorkspaceState and the exact four-port return expression.
  • Barrel re-exports are direct export { ... } from the two leaves, and export type { LocalWorkspaceSyncState } from the read model.
  • application.getInteractiveWorkspaceState === the composition export. application.syncLocalWorkspaceState === the sync export.
  • Package export keys, order, and targets are unchanged.
  • existsSync("packages/application/src/workspace/index.ts") stays false.
  • Neither leaf contains index.js, @intentloom/application, or continuous-security-audit.
  • applicationCycles(false) and applicationCycles(true) equal the section 8.1 member arrays. Both new files are absent from the flattened member list. The read model stays absent.
  • tests/legacy-subagent-task-record-p1j-structure.test.ts keeps the four-port assertion, moved from index.ts to local-workspace-sync.ts. It still requires the Neutron import-and-export pair on the barrel. It still rejects an index.js import in the task leaf. It still rejects interactive-workspace-read-model inside the task leaf. The sync leaf is allowed to import the read model; the task leaf is not.
  • tests/workspace-read-model-p1h7-structure.test.ts stops requiring the assembler calls and the interface text on index.ts, and requires them on the new leaves. The read-model specifier list, the 205/219 lock, and the assembler function sizes stay.
  • tests/workspace-conversation-p1k8-structure.test.ts stops requiring export async function syncLocalWorkspaceState on the barrel. It still requires listWorkspaceConversations on the barrel and the proposal wrapper. The sync function text moves to the sync leaf.
  • These seventeen files update their index.ts lock from 629/659 to the observed post-move measurement, and they do not change their other contracts: tests/bounded-project-context-p1k6-structure.test.ts, tests/generated-file-transaction-p1i1-structure.test.ts, tests/legacy-subagent-task-record-p1j-structure.test.ts, tests/plan-feature-p1k11-structure.test.ts, tests/plan-pack-update-p1k12-structure.test.ts, tests/profile-store-p1k1-structure.test.ts, tests/project-adoption-p1i3-structure.test.ts, tests/project-lifecycle-p1i2-structure.test.ts, tests/project-root-p1k10-structure.test.ts, tests/role-delegation-p1k2-structure.test.ts, tests/security-adapter-p1k7-structure.test.ts, tests/security-audit-structure-p1h6.test.ts, tests/semantic-ranking-p1k5-structure.test.ts, tests/task-checkpoint-store-p1k4-structure.test.ts, tests/task-session-summary-store-p1k3-structure.test.ts, tests/workspace-conversation-p1k8-structure.test.ts, tests/workspace-read-model-p1h7-structure.test.ts.
  • tests/application-neutron-topology.test.ts is not edited.
  • docs/governance/quality-exceptions.json is not edited. The P1J hash assertion stays.

That list is the complete set of files that currently lock effectiveCodeLines: 629 and physicalLines: 659. The count is seventeen. An earlier handoff said sixteen. This design uses the file search, not that count. Do not add another barrel-size lock.

Run Stage A before the production move and rerun the same files after it. Use the first command for the single-file suite. If Stage A is split, use the second command so the failure scenarios run on both revisions. Run the structure suite and full verification after the production move.

sh
pnpm exec vitest run tests/workspace-composition-p1k13-characterization.test.ts
pnpm exec vitest run tests/workspace-composition-p1k13-characterization.test.ts tests/workspace-composition-p1k13-failure-characterization.test.ts
pnpm exec vitest run tests/workspace-composition-p1k13-structure.test.ts tests/workspace-read-model-p1h7.test.ts tests/workspace-read-model-p1h7-structure.test.ts tests/legacy-subagent-task-record-p1j-structure.test.ts tests/legacy-subagent-task-record-p1j-characterization.test.ts tests/workspace-conversation-p1k8-structure.test.ts tests/security-audit-behavior-p1h6.test.ts tests/interactive-ui.test.ts tests/cli-neutron.test.ts tests/neutron-orchestration.test.ts tests/v1-client-surface-equivalence.test.ts tests/v1-compatibility-contract.test.ts tests/application-neutron-topology.test.ts
pnpm verify

pnpm verify is pnpm typecheck && pnpm lint && pnpm format:check && pnpm test && pnpm build && git diff --check.

28.17 Migration, rollback, and non-goals ​

Migration sequence for the future implementation:

  1. Stage A on the unchanged barrel.
  2. Add the two leaves with the current function and interface text.
  3. Replace the barrel bodies with direct re-exports.
  4. Delete only the unused Plan, DoctorFinding, and ProjectInspection local imports named in section 28.7.
  5. Update the structure assertions in section 28.16.
  6. Re-run Stage A against the re-exports. It must still pass.

Rollback: revert the implementation commits. The public names and call shapes do not change, so there is no data migration and no client rewrite. Persisted audit reports, conversations, and task records are not rewritten by this slice.

Non-goals:

  • Implementing P1K.13 in this design pull request.
  • Moving any declaration in this design pull request.
  • Editing the read model, the ports, or their catch behavior.
  • Adding or modifying executable tests in this design pull request.
  • Changing package exports, CLI, daemon, Desktop, MCP, or Neutron production files.
  • Changing security audit behavior or executing an audit from a reader.
  • Starting P1K.14, P1K.15, P1K.16, P1K.17, Undo U4, Desktop Undo U5, or P2–P6.
  • Modifying CI workflows or quality-exceptions.json.
  • Adding dependencies, a workspace barrel, a package subpath, or a bounded context.
  • Merging, publishing, or releasing.
  • Authorizing Inloom, the AI Software Factory, Agent Intelligence, or Project Lantern.
  • Treating a cancelled Compatibility job as a pass or as a product regression.
  • Unifying the private view union with InteractiveWorkspaceState.
  • Changing the CLI's local view cast.
  • Recomputing planId or any P1K.12 planning rule.

28.18 Owner approval matrix ​

Rows 1 through 10 are ACCEPTED. Row 11 is PENDING. Green CI on this design did not accept a row. The Project Owner accepts or rejects each row explicitly. Acceptance of this matrix is not implementation authorization. Implementation still needs the separate statement in row 11, after main verification of the design merge.

Acceptance record. The Project Owner accepted rows 1 through 10 in the supervising conversation at 2026-12-04 22:11 Europe/Berlin, in an explicit statement that accepted those rows. That was after design PR #658 merged (7911573) and after the independent review in section 28.21. The rows were accepted as written. Their text has not changed since the design merge. This repository has no GitHub review identifier for the acceptance. Row 11 was not accepted and no statement authorizing implementation exists.

#Proposed decisionRationaleEvidenceStatus
1Extract only InteractiveWorkspaceState, getInteractiveWorkspaceState, and syncLocalWorkspaceStateThose are the remaining composition bindings. The assemblers and LocalWorkspaceSyncState already have an ownerSection 28.2 and the current barrel lines 536–577 and 633–643ACCEPTED
2Own the interactive type and function in workspace/interactive-workspace-composition.ts, and own syncLocalWorkspaceState in workspace/local-workspace-sync.ts. Leave LocalWorkspaceSyncState on the read modelThe port sets differ. The P1H.7 reason for keeping the snapshot type on the barrel is obsoleteSection 28.6 and the owner modules measured in section 28.7ACCEPTED
3Adopt Alternative B and reject A and CDirect owner imports do not reach the barrel, so another injection seam is not requiredSection 28.11 and the closure table in section 28.7ACCEPTED
4Preserve the public names, options, defaults, return types, active-view literals, nullability, and readonly contracts through direct barrel re-exportsCallers import @intentloom/application. The re-export is the leaf functionSection 28.4 and section 28.8ACCEPTED
5Preserve both port objects, key order, and canonical function identityA wrapper would change which function the assembler calls while tests of the assembler still passSection 28.7 and the P1J four-port assertionACCEPTED
6Forbid a leaf import of the application barrel. Keep section 8.1 membership unchanged. Keep both new files outside every componentMeasured closures do not include index.ts. A barrel import would enlarge the 27-file componentSection 28.7 and section 28.13ACCEPTED
7Commit Stage A characterization before the production move, covering the contracts in section 28.15The move is behavior-preserving only if the public binding is locked firstSection 28.15. This design adds no testACCEPTED
8Stage B checks ownership, direct re-exports, function identity, unchanged package exports, exact SCC members, the relocated four-port assertion, observed barrel size, and unchanged Neutron topologyPath updates must not weaken the contractsSection 28.16ACCEPTED
9Preserve current error propagation, filesystem defaults, read-model audit reads, and the absence of runContinuousSecurityAudit on these pathsThe bindings do not catch and do not call FileSystem methods. The assembler behavior staysSection 28.9 and section 28.10ACCEPTED
10Limit the future implementation to section 28.17. Roll back by reverting those commits. Do not start later slicesThe public API does not change, so rollback has no migrationSection 28.17ACCEPTED
11Do not authorize implementation by this design, by its merge, or by main verification alone. Implementation starts only after a later Project Owner statement that names the verified design-merge commitP1K.11 and P1K.12 required a separate authorization after design acceptance and main verificationSection 28.14 and section 28.17PENDING

28.19 Questions resolved from the repository ​

These were the grilling questions whose answers are facts, not preferences. They are recorded so the owner matrix does not ask the owner to rediscover them.

  • Can the leaves import the barrel? No. Every canonical owner listed in section 28.7 has a closure that excludes index.ts.
  • Is a new injection boundary required? No. P1H.7 already injected the ports, and the callees are no longer barrel-owned.
  • Do daemon, Desktop, or MCP call these functions? No production reference was found. CLI ui and Neutron sync do.
  • Did P1K.12 merge? Yes. PR #655 merged as 89fbcd7c7656be0d6a37b06f1b70b575f19b2749. Its own Compatibility workflow did not fully pass. See section 27.19.
  • Did PR #657 change product code? No. The pull request files are CHANGELOG.md, DUTY_WATCH.md, README.md, ROADMAP.md, and docs/index.md.

The unresolved choice is approval of the proposed decisions, not a hidden implementation option.

28.20 Verification record for this design ​

Filled in the same pull request after the commands run. A check that was not executed is not PASS.

Baseline before edits: main 3d641e4a8a6b066ade281ce53b215d4a522b5b39. The design edits started only after this gate succeeded.

Documentation run 47211188128 succeeded. It completed at 2026-12-03 22:52 Europe/Berlin. CodeQL run 47211188193 succeeded. It completed at 2026-12-03 22:53 Europe/Berlin. Compatibility run 47211188122 succeeded. The workflow completed at 2026-12-03 23:13 Europe/Berlin. All six jobs passed, and each pnpm test step succeeded:

JobJob idRunner idpnpm testCompleted (Europe/Berlin)
ubuntu-latest / Node 241446287079621000037581success2026-12-03 22:57
ubuntu-latest / Node 221446287083721000037586success2026-12-03 22:56
windows-latest / Node 221446287084841000037585success2026-12-03 22:59
windows-latest / Node 241446287084441000037584success2026-12-03 23:00
macos-latest / Node 221446287083521000037590success2026-12-03 23:07
macos-latest / Node 241446387720611000037592success2026-12-03 23:13

macos-latest / Node 24 is a separate job that waits for macos-latest / Node 22. It ran its own test step. It is not the cancelled job from 89fbcd7.

Local verification on this design branch, Node v22.23.5 and pnpm 10.12.4. pnpm docs:build exited 0. VitePress 1.6.4 reported build complete in 5.88s, with the existing Rolldown plugin warnings and the existing chunk-size warning. VitePress does not render Mermaid. pnpm verify exited 0. Typecheck passed. Lint passed with 307 existing warnings and none in the design files. Format check passed. Vitest 5.0.0 reported 404 files, 3413 passed, and 3 skipped in 203.88s. Build passed. git diff --check passed as the last step of pnpm verify. This paragraph was added after that run. Prettier left the file unchanged, and a second git diff --check exited 0. The pre-push hook then ran pnpm verify again on the committed tree. It exited 0. Vitest reported 404 files, 3413 passed, and 3 skipped in 198.61s. Accessibility, product analytics, and AI evaluation are NOT APPLICABLE for the reasons in section 28.10. No production source, executable test, package export, CI workflow, or quality-exceptions.json file is in this diff.

28.21 Independent review and post-merge record ​

At the time of this review, section 28 was PROPOSED and every row of section 28.18 was PENDING. Section 28.18 records the later acceptance of rows 1 through 10. This subsection records an independent read-only review of the merged design and the main verification that section 28.14 step 3 refers to. It does not accept a row and it does not authorize implementation.

Review: 2026-12-04, Claude Code (Claude Sonnet 5.5), at the Project Owner's request, against main e377b29c973d078c85fbcbfd4d457a56e316cb23. Code and tests on main are unchanged since the design baseline 3d641e4. Only documentation changed in 7911573, 26bb786, and e377b29. No branch named for a P1K.13 implementation exists on origin, and no pull request for one is open.

The review confirmed these design claims against the code:

  • the barrel lines for the interface and both bindings, and the exact port objects and key order;
  • the callers: packages/cli/src/ui-command.ts and packages/cli/src/neutron-command.ts only, with no production reference in daemon, MCP server, or Desktop;
  • the closure sizes in section 28.7, none of which reaches index.ts, and the section 8.1 cycle sizes [3] and [4, 27, 3];
  • the twelve package export keys and the seventeen barrel-size locks;
  • that the five fenced Mermaid blocks equal the five .mmd files.

Main verification by commit. Times are Europe/Berlin.

CommitWorkflowRunResultNote
7911573Compatibility47229566929successdesign merge (PR #658). All six jobs and their pnpm test steps passed. Completed 2026-12-04 00:55
7911573CodeQL47229566861success
7911573Documentation47229566657success
26bb786Compatibility47391527373failurePR #659. windows-latest / Node 24 failed in pnpm test (hook timeout in tests/adapter-packed-process.test.ts). macos-latest / Node 22 cancelled, runner id 0. macos-latest / Node 24 skipped
26bb786CodeQL47391527403success
26bb786Documentation47391527337success
e377b29Compatibility47409489334successPR #660. All six jobs and their pnpm test steps passed. Completed 2026-12-04 20:50
e377b29CodeQL47409489498success
e377b29Documentation47409489345success

The 26bb786 failure is a Windows setup-hook timeout and a macOS runner acquisition failure, not a product assertion. It is recorded as a failure and is not counted as a pass. The next main commit, e377b29, passed all six jobs. No product code differs between those commits.

Local checks on e377b29, Node v22.23.5 and pnpm 10.12.4: twelve existing test files named in section 28.16 passed, 98 tests. pnpm verify exited 0 with lint at 307 existing warnings, Vitest at 404 files, 3413 passed, and 3 skipped in 216.56s, a passing build, and a passing git diff --check. The working tree stayed clean.

Not verified by the review: the 574, 59, and 20 line forecasts in section 28.12, type checking and lint of the proposed leaves, and Mermaid parsing. Stage A and Stage B tests do not exist yet.

The review raised these points. This documentation pull request resolves them:

  • Section 28.14 counted sixteen barrel-size locks in four places, while section 28.16 listed seventeen. The file search gives seventeen, and the text now says seventeen everywhere.
  • The design had no test-file budget. Section 28.15 now sets one, with a split point.
  • The edit to the LocalWorkspaceSyncState import and export was ambiguous. Section 28.7 now states it.
  • The mutation counts do not observe the host and git path of timelineProject. Section 28.15 now says so.
  • The design had no implementation record or post-merge reconciliation, which section 27.18 and 27.19 had for P1K.12. Section 28.22 reserves them.
  • PROJECT_STATE.md still named 3d641e4 as main and did not record the design merge or the 26bb786 failure. It is reconciled in this pull request.

Row 11 stays PENDING, including after the acceptance of rows 1 through 10. Main verification of the design merge commit 7911573 is recorded above. The statement that authorizes implementation is still the Project Owner's, and it must name a verified commit.

28.22 Implementation record and post-merge reconciliation ​

Reserved for the implementation pull request. No implementation exists, so no value is recorded here. The pull request that implements P1K.13 fills this subsection with observed values only and keeps section 28.21 as written.

The implementation record names:

  • the Stage A commit or commits, the Stage A test file or files, and their measured line counts;
  • the production extraction commit and the two leaves;
  • the Stage A command, its commit, and its result before and after the move;
  • the observed index.ts and leaf measurements from measureProductionSource;
  • the applicationCycles(false) and applicationCycles(true) member arrays compared with section 8.1;
  • pnpm verify on the final head, and the pull request CI by job and run id.

The post-merge reconciliation names the merge commit and its time, the CI runs on that commit by job, and any cancelled or failed job, recorded as such. It updates PROJECT_STATE.md, DUTY_WATCH.md, CHANGELOG.md, and the stabilization plan.