Skip to content

Neutron N3 — Context Assembly Maintainer Brief ​

Status ​

Planning artifact with Slice 1 implemented (contract + validator extension), Slice 2 implemented (deterministic assembly core), Slice 3 implemented (memory + task + profile integration), and Slice 4 implemented (N2 pre-turn hook). Optional Slice 5 (CLI/daemon exposure) remains unauthorized.

Evidence baseline: origin/main @ a2a821a (post N3 Slice 3 handoff #430, 2026-08-31).

Slice 1 implementation decisions (2026-08-30) ​

DecisionResolution
Assembly request URNurn:intentloom:schema:neutron-context-assembly-request:1
Protocol typeAssembleNeutronContextRequest in @intentloom/protocol/neutron-runtime
Required fieldsroot, sessionId, projectId
Optional request fieldstaskId, query, profileName, role, skillLevel, maxTokens, maxItems, sourceTypes, includeMemory, semanticRanking
Source provenance extensionOptional path, contentDigest, loadingLevel on NeutronContextSource
path semanticsNormalized project-relative via normalizeStoredPath; rejects absolute/escaping paths
contentDigest semanticssha256:<64 lowercase hex> over normalized excerpt bytes (field validated only; collectors populate in Slice 2+)
loadingLevel semanticsOptional catalog | contract | procedure for skill sources
Bundle / budget URNsUnchanged — NeutronContextBundle and NeutronUsageBudget remain N1 v1
Version bumpAdditive optional fields only; no protocol version bump required
Validator ownership@intentloom/validator/neutron-runtime-n3 + extended validateNeutronContextSource
Remaining for Slice 2assembleNeutronContext orchestrator, collectors, budget algorithm

Slice 2 implementation decisions (2026-08-30) ​

DecisionResolution
Application operationassembleNeutronContext on @intentloom/application/neutron-context-assembly
Result wrapperAssembleNeutronContextResult (bundle, usage, warnings) — application-only, no new protocol URN
Modulesneutron-context-assembly.ts (orchestrate + validate), neutron-context-collectors.ts (Slice 2 sources), neutron-context-budget.ts (priority + truncation)
Source scopeCanonical policy (intent/adr), ownership (PROJECT_STATE.md / DUTY_WATCH.md via M1), skills (discoverSkills), remaining bounded docs/evidence
Reused APIsgetBoundedProjectContext and discoverSkills with injected FileSystem; collectors request a high candidate cap so N3 owns cross-source truncation
PriorityPolicy 1 → ownership 2 → skills 5 → bounded docs 6; deferred Slice 3 placeholders 3/4/7/8. Tie-break: normalized path then sourceId (code-point order)
DefaultsmaxTokens = 4000, maxItems = 20, skillLevel = catalog (application-owned)
Reserved slicesSoft floors: policy 25%, ownership 10%. Implemented as priority-first inclusion up to the global cap; canonical sources may exceed their ratio rather than fail
Token accountingM1 tokenCount (ceil(bytes/4)) for project files; skill contextCost at the requested loading level
sourceTypesFilters bounded-context classes only. Skills are a separate class and are still collected. Unknown strings remain validator-rejected
Deferred Slice 3 fieldsprofileName, taskId, includeMemory (explicit or default-true when query/taskId set), and semanticRanking: true emit stable warnings plus excluded deferred:* sources (deferred-slice-3)
role in Slice 2Passed through to discoverSkills as existing skill-metadata filter only. No getProfile / delegation / capability grant
Semantic rankingNever calls a provider. Deterministic local order remains authoritative; warning + excluded deferred:semantic marker
Secret pathsReuse M1 secret filtering. Secret content never appears. excludedSecretLikePaths stays empty because M1 redacts paths and returns a count only; warning secret-like paths excluded when count > 0
Digestssha256: + checksum over available excerpt bytes (M1 summary, skill id + description). No extra file reread
TrustPolicy/ownership/project docs → project; skills → catalog (never elevated); deferred markers → derived
Persistence / N2 / CLI / DesktopNone. Read-only return of the bundle. mutationAllowed: false / networkMode: offline unchanged
Remaining for Slice 3Persistent memory, task checkpoint/summary, profile resolution and role validation

Slice 3 implementation decisions (2026-08-30) ​

DecisionResolution
ModulesSlice 2 modules keep their roles. neutron-context-state-collectors.ts collects profile/task/memory; neutron-context-state-excerpts.ts owns stable excerpts and token/digest estimates. Budget gains optional rank.
Reused APIsgetProfile, getTaskSummary, listTaskCheckpoints, searchPersistentMemory with injected FileSystem. No delegateTaskRole, rankProceduralMemory, raw .aif parsing, or N2 hook.
includeMemoryfalse skips the query and emits no memory sources. true searches with query ?? taskId. Unset defaults to true when query or taskId is set (Slice 2 contract). Empty accepted results warn.
Memory isolationprojectId is passed explicitly. Only lifecycleState: accepted items from that project are eligible. Search ranking is preserved; score ties keep API id order.
Memory trust / idssourceId is memory:<recordId>. Trust maps record trustClass (user-supplied → user, agent-generated → derived, otherwise project). Provenance intentloom.memory.persistent.v1. No path.
Task stateWhen taskId is set: getTaskSummary(taskId) plus latest listTaskCheckpoints({ taskId }) by updatedAt then id. Missing records warn and emit excluded record-missing markers. No lookup without taskId.
Checkpoint statesactive / paused / cancelled / redirected / resumed are read-only current state. invalidatedPlans stay in the excerpt. N3 never pauses, resumes, redirects, or validates plans.
Profile / roleprofileName fetches that profile only. Missing profile throws Profile not found: <name>. Role is validated against activeRoles only when a profile is present; otherwise role remains a skill filter.
CapabilitiesProfile allowedTools / allowedPaths / allowNetwork / maxBudget are excerpt metadata. No capability grant, no delegation record, mutationAllowed unchanged.
PriorityPolicy 1 → ownership 2 → profile 3 → task 4 → skills 5 → bounded 6 → memory 7 → semantic deferred 8. Shared maxTokens / maxItems. Token cost is ceil(bytes/4) of the stable excerpt.
Deferred remainderSemantic ranking stays excluded deferred:semantic with reason deferred. No provider. Slice 4 is the N2 pre-turn hook.
ProtocolSame N1 bundle / usage URNs. No new protocol field.
Remaining for Slice 4Read-only N2 pre-turn hook that can consume the assembled bundle. No CLI/daemon/Desktop, N4, persistence, or model execution in Slice 3.

Slice 4 implementation decisions (2026-08-31) ​

DecisionResolution
Hook locationprepareNeutronN2ModelPrompt in neutron-n2-context-hook.ts; runNeutronN2ReadOnlyLoop invokes it once before the first Ollama turn and reuses the same modelPrompt for the tool follow-up turn
Assembly timingOne assembly per N2 loop invocation (not per adapter sub-turn). Inspect tool substeps do not reassemble
Request mappingroot, sessionId, projectId from N2 input; optional taskId, profileName, role, skillLevel, maxTokens, maxItems, sourceTypes, includeMemory, semanticRanking, contextQuery → assembly query only when explicitly set
User promptOriginal N2 prompt is appended under ## User request; not auto-mapped to assembly query (avoids filtering canonical policy out of bounded retrieval)
Projection moduleneutron-n3-prompt-context.ts — trust-aware sections (policy → ownership → profile → task → skills → bounded → memory), stable \n framing, project-relative paths only, excluded sources omitted
Result extensionApplication-only: NeutronN2LoopResult.contextAssembly, modelPrompt, contextFramingTokens, modelInputTokensEstimate; AssembleNeutronContextResult.projectionEntries
Blocking failuresInvalid assembly request, missing profile, role/profile mismatch, bundle validation failure — throw before any ModelAdapter.executeTurn; Ollama not invoked
Warning/degradedMissing task, empty memory, semantic deferred — valid bundle; model turn proceeds; warnings preserved on result
Opt-outdisableContextAssembly: true preserves pre-Slice-4 prompt-only N2 behavior for compatibility tests
SafetyRead-only inspect tool only; fingerprint before/after unchanged; no new tools; no capability grants; secrets excluded from projection; no persistence
Remaining after Slice 4Optional Slice 5 CLI/daemon exposure only if a real caller exists; N4 tool router; N6 Desktop model UI — all unauthorized

Authoritative roadmap gate: NEUTRON_RUNTIME_ROADMAP.md §N3. Deferred without explicit authorization per POST_W12_NEXT_INCREMENT_PLAN.md and ENGINEERING_WORKSPACE_CAPABILITY_MATRIX.md.


1. Current baseline ​

ItemEvidence
Post-reconciliation main SHAe44fdc7e82cd51bc784fd8c37e8b45038571d2c9 (PR #422 merged)
CLI decompositionP4l1–P4l16 complete; command.ts 171 physical / 167 effective (#421, #422)
Neutron N1Merged PR #317 @ 7d1dbd1 — versioned runtime contracts, validators, frozen fixture
Neutron N2Merged PR #318 @ 89b6c1d — Ollama loopback adapter + runNeutronN2ReadOnlyLoop
Model adapter boundaryADR-0054, PR #254 — @intentloom/application/model-adapter subpath
Bounded project context (M1)getBoundedProjectContext, intentloom context get (P4l16)
Skill discovery (L7)discoverSkills with catalog/contract/procedure levels
Memory (M1–M4)searchPersistentMemory, listPersistentMemoryItems, accepted lifecycle
Profiles / delegation (L6)getProfile, delegateTaskRole
Task state (L5)getTaskCheckpoint, getTaskSummary, checkpoint lifecycle
Semantic ranking (L8)rankProceduralMemory (optional, provider-dependent)

Relevant current APIs ​

APIPackageRole today
prepareNeutronRuntimeContractSnapshot@intentloom/application/neutron-runtimeN1 root-bound contract validation
runNeutronN2ReadOnlyLoop@intentloom/application/neutron-n2N2 inspect-only model loop
assembleNeutronContext@intentloom/application/neutron-context-assemblyN3 Slice 2 deterministic assembly
getBoundedProjectContext@intentloom/applicationM1 path-scoped file retrieval
discoverSkills@intentloom/applicationProgressive skill selection
searchPersistentMemory@intentloom/applicationAccepted memory keyword search
rankProceduralMemory@intentloom/applicationProcedural/semantic ranking
getProfile / delegateTaskRole@intentloom/applicationRole capability clamping
getTaskCheckpoint / getTaskSummary@intentloom/applicationTask-scoped state
validateNeutronContextBundle@intentloom/validator/neutron-runtimeN1 bundle shape enforcement

N1 baseline (implemented) ​

DimensionState
PurposeVersioned, provider-neutral runtime contract snapshots
InputsCaller-supplied root + frozen or constructed snapshot JSON
OutputsValidated NeutronRuntimeContractSnapshot
APIsNeutronContextBundle, NeutronUsageBudget, tool/graph/subagent envelopes
Persisted stateNone — validation only
Read/writeRead-only validation; rejects mutationAllowed !== false
Trust/securityN1 snapshots require networkMode: "offline", mutationAllowed: false
CLI/Desktop/daemonNo N1 execution surface
Teststests/neutron-runtime-contracts.test.ts, fixture contract-snapshot.v1.json
LimitationsNeutronContextBundle is schema-only; no live assembly engine
DeferredDynamic assembly, provider execution, Desktop exposure

N2 baseline (implemented) ​

DimensionState
PurposeOne real provider (Ollama loopback) through one read-only inspect loop
Inputsroot, sessionId, projectId, prompt, configured ModelAdapter
OutputsSession, adapter capability, tool envelope, response text, fingerprint proof
APIsrunNeutronN2ReadOnlyLoop, OllamaModelAdapter
Persisted stateNone — ephemeral turn; no project writes
Read/writeRead-only; fingerprint before/after must match
Trust/securityLoopback-only URL; one in-flight turn per session; inspect tool only
CLI/Desktop/daemonNo model calls on any client surface (ADR-0055)
Teststests/neutron-n2-ollama.test.ts with fake HTTP listener
LimitationsDoes not call context assembly; prompt goes to model without N3 bundle
DeferredContext engine integration, additional tools, streaming, Desktop (N6)

2. N3 objective ​

Neutron N3 Context assembly is the application-layer operation that, for a given Neutron runtime session bound to one project root, deterministically composes canonical policy, bounded project files, accepted memory, selected skills, task/checkpoint state, and role/profile constraints into a single versioned NeutronContextBundle with full source provenance, trust classification, budget accounting, and explicit exclusion reasons — without mutating project bytes, granting capabilities, or invoking a model.

N3 is not intentloom context get. That CLI command (P4l16) exposes getBoundedProjectContext, which performs a flat, path-type-scoped file scan with secret filtering and token/item clamping. N3 orchestrates multiple existing retrieval operations, maps their outputs into N1 NeutronContextSource records, enforces cross-source priority and reserved budgets, and produces an agent-ready bundle suitable for downstream N4 tool routing and N2/N6 model turns.


3. Existing capabilities reused ​

Subsystem / APIHow N3 uses it
getBoundedProjectContextMandatory source for canonical intent, ADRs, docs, ownership, evidence paths
discoverSkillsMandatory skill candidate selection at declared loading level
searchPersistentMemoryOptional accepted-memory inclusion when taskId/query provided
getTaskCheckpoint / getTaskSummaryOptional task-scoped context when taskId provided
getProfileMandatory when profileName provided; filters skills and annotates constraints
delegateTaskRoleNot invoked by N3; delegation is a separate mutating boundary (L6)
rankProceduralMemoryOptional, default off in N3 v1 for determinism
validateNeutronContextBundleOutput validation against N1 schema
NeutronUsageBudgetToken accounting envelope linked to assembly result
TrustClass (protocol)Maps into N1 NeutronContextSource.trustClass via explicit mapping table
Secret path patterns (M1)Reused from getBoundedProjectContext; never duplicated

4. Explicit non-goals ​

N3 does not:

  • invoke ModelAdapter, Ollama, or any hosted provider;
  • execute tools (inspect, doctor, apply, etc.) — that is N4;
  • mutate project files, memory items, checkpoints, profiles, or delegations;
  • auto-activate skills or write skill proposals;
  • grant capabilities because a profile, skill, or role appears in the bundle;
  • replace getBoundedProjectContext or change context get CLI semantics;
  • add Desktop, TUI, MCP, or daemon RPC surfaces in the first slice;
  • perform cross-project or cross-profile memory retrieval;
  • silently promote agent-generated or user-supplied content to canonical-policy;
  • persist assembled bundles to disk (unless a later ADR requires audit artifacts);
  • implement semantic ranking as a default path (optional flag only);
  • introduce packages/neutron-runtime or grow root package barrels;
  • start P4l17, W13, or any post-decomposition CLI extract.

5. Proposed architecture ​

Owning layer ​

LayerResponsibility
@intentloom/protocol/neutron-runtimeExtend assembly request type; keep NeutronContextBundle URN stable
@intentloom/validator/neutron-runtimeValidate request + assembled bundle
@intentloom/application/neutron-context-assemblyNew subpath; orchestration only
CLI / daemon / DesktopDeferred after application API stabilizes

No new package until N4+ consumer count justifies it (same rule as N1/N2).

Input contract (proposed) ​

typescript
interface AssembleNeutronContextInput {
  readonly root: string;
  readonly sessionId: string;
  readonly projectId: string;
  readonly taskId?: string;
  readonly query?: string;
  readonly profileName?: string;
  readonly role?: DelegatedAgentRole;
  readonly skillLevel?: SkillLoadingLevel; // default "catalog"
  readonly maxTokens?: number; // default 4000, same as M1
  readonly maxItems?: number; // default 20
  readonly sourceTypes?: readonly ContextSourceType[];
  readonly includeMemory?: boolean; // default true when query/taskId set
  readonly semanticRanking?: boolean; // default false (determinism)
}

Validation: root non-empty, sessionId matches N1 session conventions, profile must exist when profileName is set, role must be in profile's activeRoles when both are set.

Orchestration ​

text
AssembleNeutronContextInput
  → validate root/session/profile/role
  → collect mandatory policy/context (getBoundedProjectContext)
  → collect skills (discoverSkills with profile role/pack filters)
  → collect optional memory (searchPersistentMemory, projectId-scoped)
  → collect optional task (getTaskCheckpoint / getTaskSummary)
  → map each candidate → NeutronContextSource (+ exclusion reasons)
  → apply priority ordering + reserved budgets + deterministic truncation
  → validateNeutronContextBundle + NeutronUsageBudget
  → AssembleNeutronContextResult

Each collector is a pure read through existing application APIs with injected FileSystem. No direct filesystem walks outside those APIs.

Output contract ​

Primary output: NeutronContextBundle (existing N1 URN urn:intentloom:schema:neutron-context-bundle:1).

Secondary output (application wrapper, not a new protocol URN in slice 1):

typescript
interface AssembleNeutronContextResult {
  readonly bundle: NeutronContextBundle;
  readonly usage: NeutronUsageBudget;
  readonly warnings: readonly string[];
}

Adapters ​

SurfaceN3 v1 recommendation
Application APIYes — first vertical slice
Unit/integration testsYes
CLINo — context get already covers bounded retrieval; add neutron context assemble only after API freeze
Daemon RPCNo — N4 tool router will need stable bundle shape first
DesktopNo — N6 Neutron Workspace
MCPNo

6. Context sources ​

Priority order (lower number = included first; truncation removes from bottom):

#SourceInclusion rulePriorityTrust / provenanceBudget impactFallback
1Canonical policyAlways: docs/specs/*, docs/decisions/* via getBoundedProjectContext with sourceTypes: ["intent","adr"]1 (reserved 25% tokens)trustClass: project, kind: policy, provenance intentloom.context.bounded.v1Counts toward shared token/item budgetBlocking if root missing
2Project ownership stateAlways: PROJECT_STATE.md, DUTY_WATCH.md when present2 (reserved 10%)kind: policy, trust mapped from M1 canonical-policy / verified-evidenceReserved sliceWarning if unreadable
3Profile constraintsWhen profileName set: include profile metadata as kind: policy source, not full capability grant3kind: policy, provenance intentloom.profile.v1Fixed catalog-cost estimateBlocking if profile missing
4Task intent / checkpointWhen taskId set: latest checkpoint + task summary4kind: task, trust from recordPer-item token estimateWarning if task missing
5Selected skillsdiscoverSkills at requested level; filter by profile role/pack5kind: skill, trust from skill metadataUses skill contextCost.*Empty skills → warning
6Bounded documentationRemaining getBoundedProjectContext docs/ownership/evidence6kind: inspect or evidenceShared budgetSkip unreadable
7Accepted memoryWhen includeMemory and query/taskId: searchPersistentMemory7kind: memory, trust from item classificationShared budgetWarning if none found
8Semantic rank hintsOnly when semanticRanking: true8 (optional)kind: derived, provenance includes provider idDoes not consume file-content budget; metadata onlyFallback: omit rank sources

Explicitly out of scope for N3 ​

SourceReason
Live inspectProject outputTool execution belongs to N2/N4 loops, not pre-turn assembly
Workspace/inception session stateDifferent product boundary; no stable Neutron coupling
Engineering assessments live outputNo daemon/CLI transport; deferred
Delegation records (mutating)N3 reads profile; does not create delegations
Model transcriptsEphemeral per ADR-0055
Cross-project memoryForbidden by memory security model

Deferred to N4+ ​

SourceStage
Tool-router-selected evidence fetchN4
Subagent workspace sync recordsN5
NeutronBench fixture overlaysN7

7. Budget model ​

Reuse M1 defaults and semantics (maxTokens default 4000, maxItems default 20).

Token budget ​

RuleBehavior
Global capinput.maxTokens ?? 4000
Reserved slicesPolicy (intent+ADR): min 25% until filled or exhausted; ownership docs: min 10%
Per-source estimateReuse M1 tokenCount (ceil(bytes/4)) and skill contextCost.*
TruncationDeterministic: sort excluded candidates by priority desc, drop lowest priority first
OverflowSet usage.limitExceeded: true; include warnings entry; still return partial bundle
Empty contextValid result with zero included sources and warning (not blocking)
Hard vs softReserved slices are soft: if canonical files exceed reserved slice, they may consume more rather than fail

Item budget ​

RuleBehavior
Global capinput.maxItems ?? 20
CountingEach included NeutronContextSource counts as one item
SkillsOne source per selected skill at chosen loading level
MemoryOne source per accepted memory item

Deterministic ordering ​

  1. Collect candidates from each subsystem in fixed source order (§6 table).
  2. Within a subsystem, preserve API sort order:
    • getBoundedProjectContext: filesystem list order (stable for createMemoryFileSystem; document that production relies on sorted normalized paths — implementation must sort paths lexicographically to match test determinism).
    • discoverSkills: already sorts skill IDs.
    • searchPersistentMemory: score desc, then id localeCompare.
  3. Tie-break excluded sources by sourceId lexicographic ascending in provenance output.
  4. JSON serialization: stable key order via JSON.stringify on validated objects.

Semantic ranking boundary ​

When semanticRanking: true, ranking scores may be non-deterministic across providers. N3 must:

  • keep ranked items in a separate optional derived source group;
  • never reorder mandatory policy sources based on semantic scores;
  • record provider id in provenance;
  • default semanticRanking: false in all exit-gate fixtures.

8. Trust / security model ​

Provenance ​

Every NeutronContextSource must include:

  • sourceId — stable deterministic id;
  • kind — N1 enum (inspect, memory, skill, policy, evidence, task);
  • trustClass — N1 enum (project, catalog, user, derived);
  • provenance — dotted operation id (e.g. intentloom.context.bounded.v1);
  • included — boolean;
  • exclusionReason — when included: false.

Map protocol TrustClass → N1 trustClass:

Protocol TrustClassN1 trustClass
canonical-policyproject
verified-evidenceproject
user-supplieduser
agent-generatedderived

Catalog skills use catalog. Never map agent-generated → project.

Capabilities ​

N3 is context preparation only:

AuthorityN3
Filesystem read (project)Yes, via existing read-only APIs
Filesystem writeNo
NetworkNo
SecretsExcluded via M1 patterns + bundle excludedSecretLikePaths
Process executionNo
Tool invocationNo
Capability grantNo — profile appears as metadata, not authorization

No-mutation boundary ​

Same invariant as N2: assembly must not change project fingerprint. Tests must compare filesystem digest before/after assembly.


9. Failure / degraded behavior ​

ConditionClassBehavior
Invalid/missing rootBlockingThrow validation error
Invalid sessionIdBlockingThrow validation error
profileName set but profile missingBlockingThrow Profile not found (reuse application error)
role not in profile activeRolesBlockingThrow validation error
taskId set but no checkpoint/summaryWarningOmit task sources; continue
Memory search returns emptyWarningContinue
Skill discovery rejects all skillsWarningBundle with zero skill sources
Budget exhausted with policy remainingWarningInclude partial policy; limitExceeded: true
Unreadable file in bounded contextWarningSkip item (existing M1 behavior)
Semantic provider unavailableFallbackOmit derived rank sources; warning
Malformed skill catalog fileWarningSkip skill; record in decisions → exclusion
Secret-like path detectedExcludedListed in excludedSecretLikePaths; never in payload

Reuse ProtocolValidationError / application Error patterns; do not invent a parallel error taxonomy for N3 v1.


10. Output contract ​

NeutronContextBundle (N1 URN, populated by N3) ​

FieldN3 population
schemaVersionurn:intentloom:schema:neutron-context-bundle:1
rootInput root
sessionIdInput sessionId
estimatedTokensSum of included source estimates
sourcesFull inclusion/exclusion audit trail
excludedSecretLikePathsUnion of M1 secret exclusions + explicit path list

Implementation decision requiring explicit approval (slice 1 PR) ​

Whether to add optional payload digests to NeutronContextSource:

typescript
// Proposed optional fields — not in N1 fixture today
readonly contentDigest?: string;  // sha256 of normalized excerpt
readonly path?: string;           // project-relative when applicable
readonly loadingLevel?: SkillLoadingLevel;

Recommendation: add optional fields in a backward-compatible validator extension; frozen N1 fixture remains valid without them. Full text payloads stay out of the bundle; consumers fetch via existing read APIs using sourceId / path.

NeutronUsageBudget ​

FieldN3 population
contextTokensbundle.estimatedTokens
tokenBudgetinput.maxTokens ?? 4000
limitExceededtrue when truncation occurred
inputTokens / outputTokens0 in assembly-only operation

11. Consumer / handoff ​

text
N3 assembleNeutronContext
  → NeutronContextBundle + NeutronUsageBudget
  → N4 tool router (selects tools within profile/capability envelope)
  → N2/N6 model turn (adapter receives bundle metadata + tool results)
  → N5 task graph / subagents (session-scoped revalidation)
QuestionAnswer
What object does N3 produce?Validated NeutronContextBundle + usage record
Who consumes it?N4 tool router; N2 loop (future integration); N6 Desktop review panel
What can consumers trust?Included sources passed validator + read-only APIs; trustClass/provenance
What must be revalidated?Root, session, profile, role, cancellation state before each model turn or tool call
Who authorizes execution?N4 for tools; existing approval/transaction boundaries for mutation

N3 stops before autonomous execution. Model turns remain read-only until N6+ explicit gates.


12. Minimal implementation sequence ​

Recommended bounded slices (labels are recommendations, not accepted roadmap phases):

Slice 1 — Contract + validator extension ​

ItemDetail
ScopeAssembleNeutronContextInput, optional source fields, validator updates
Packagesprotocol/neutron-runtime, validator/neutron-runtime
DependenciesN1 merged
TestsRequest validation, backward-compatible bundle fixture
Non-goalsAssembly engine, CLI
Review riskLow — schema-only

Slice 2 — Deterministic assembly core ​

ItemDetail
StatusImplemented — see Slice 2 implementation decisions above
ScopeassembleNeutronContext orchestrator, policy + bounded context + skills
Packagesapplication/neutron-context-assembly, application/neutron-context-budget
DependenciesSlice 1
TestsFrozen fixture projects, determinism, secret exclusion, budget truncation
Non-goalsMemory, task, semantic ranking
Review riskMedium — core logic

Slice 3 — Memory + task integration ​

ItemDetail
ScopeAccepted memory, checkpoint/summary sources, profile filtering
Packagesextend assembly modules
TestsprojectId isolation, profile missing, task missing warnings
Non-goalsSemantic ranking default
Review riskMedium — trust boundaries

Slice 4 — N2 integration hook (read-only) ​

ItemDetail
ScopeOptional pre-turn assembly call inside runNeutronN2ReadOnlyLoop
TestsN2 loop receives bundle metadata; still no project mutation
Non-goalsDesktop, daemon RPC
Review riskMedium — touches N2 path

Slice 5 — CLI/daemon exposure (optional, post-N4) ​

ItemDetail
ScopeOnly if a real caller exists beyond tests
Non-goalsDesktop UI

Module file plan (maintainability) ​

ModuleResponsibilityTarget effective SLOC
neutron-context-assembly.tsPublic assembleNeutronContext≤200
neutron-context-collectors.tsSource-specific collectors≤250
neutron-context-budget.tsPriority, reserved slices, truncation≤150
neutron-context-trust.tsTrustClass mapping, provenance ids≤80

Do not create a monolithic context-assembly.ts >400 lines.


13. Test plan ​

LayerRequired tests
ValidatorInvalid input, optional new fields, N1 fixture backward compatibility
Unit — budgetReserved slices, truncation order, limitExceeded flag
Unit — trustMapping table, agent-generated never promoted
Integration — assemblyMulti-source fixture project with skills, memory, task, profile
Integration — secrets.env, .pem, .git never appear; listed in exclusions
Integration — isolationWrong projectId excludes memory items
DeterminismSame input + filesystem → byte-stable JSON bundle
DegradedMissing task, empty memory, budget overflow → warnings not throws
FingerprintProject bytes unchanged after assembly
N2 hook (slice 4)Loop still passes fingerprint check
CLI/daemonOnly when slice 5 authorized

Fixtures: extend tests/fixtures/neutron-runtime/ with context-assembly-project.v1/ tree.


14. Acceptance criteria ​

N3 is complete when:

  1. assembleNeutronContext returns a validated NeutronContextBundle for deterministic fixture projects.
  2. Equivalent state produces stable source selection and ordering across platforms.
  3. Token and item budgets enforce truncation with limitExceeded accuracy.
  4. Canonical policy sources receive priority over documentation and memory.
  5. Secret-like paths never appear in included sources.
  6. Accepted memory respects projectId scoping.
  7. Profile/role constraints filter skills; missing profile fails closed.
  8. No project filesystem mutation during assembly.
  9. No provider-specific imports in core assembly modules.
  10. pnpm verify green including new tests.
  11. All new production files ≤250 effective SLOC or documented exception.
  12. No root barrel growth — subpath exports only.

15. Risks / open decisions ​

#DecisionRecommendationNeeds maintainer sign-off?
1Optional contentDigest / path on NeutronContextSourceAdd backward-compat optional fields in slice 1Yes — schema change
2Default semanticRankingfalse; opt-in onlyNo — brief resolves
3First consumer surfaceApplication API + tests onlyNo — matches N2 pattern
4Persist assembled bundlesDo not persist in N3No — brief resolves
5Sort order for bounded context pathsLexicographic normalize in N3 collectorNo — implementation detail
6N2 integration timingSlice 4 after core assembly provenNo — sequencing recommendation

16. Recommendation ​

READY FOR IMPLEMENTATION AUTHORIZATION

for Slice 1 (contract + validator extension) and Slice 2 (deterministic assembly core) after maintainer acknowledges schema optional-field decision (#1).

Slices 3–5 require separate authorization checkpoints after each slice merges.

Do not start implementation until the maintainer explicitly authorizes Slice 1 in DUTY_WATCH.md or a direct instruction.


References ​