The private draft software-factory/capacity-planning entry evaluates one caller-owned account, native unit and work profile across all current overlapping quota windows. Install the reviewed tarball into your own application. It needs Node 26.8.1 or later, with no runtime npm dependencies or Node type declarations. It has no storage, provider, model, clock callback or Factory dependency. Import and calculation perform no I/O.
A complete caller-owned example
Save this as capacity.mjs and run node capacity.mjs. These are illustrative attributed observations, not live provider measurements. The host must authenticate real sources, retain original admission identities and explicitly commission the future assumptions.
import { forecastCapacity, parseCapacityForecast } from 'software-factory/capacity-planning';
const hash = 'sha256:' + '1'.repeat(64);
const at = '2026-10-01T00:10:00.000Z';
const scope = { namespace: 'my-app', accountId: 'shared', targetProductId: 'reader', workLaneId: 'changes' };
const unit = { kind: 'request', definitionId: 'native-requests', definitionDigest: hash };
const profile = { workClassId: 'small-change', workDefinitionDigest: hash, providerId: 'declared-provider',
modelId: 'declared-model', effortId: 'declared-effort', environmentDigest: hash, reviewDefinitionDigest: hash };
const complete = { state: 'complete', reasons: [] };
const source = { id: 'reviewed-observation', revision: 1, contentDigest: hash };
const inputs = { protocol: 'sf-capacity-inputs/1', scope, unit, horizonEnd: '2026-10-01T00:12:00.000Z',
requestedAdditionalIncrements: 2, cutoff: at, windowCoverage: complete, usageCoverage: complete,
cohortCoverage: complete, sources: [{ ...source, observedAt: at, checkedAt: at,
validUntil: '2026-10-01T00:20:00.000Z', validation: { state: 'validated' } }],
windows: [{ id: 'account-window', revision: 1, startsAt: '2026-10-01T00:00:00.000Z',
resetsAt: '2026-10-01T01:00:00.000Z', observation: { source, observedAt: at,
remaining: { kind: 'range', lower: 100, upper: 100 }, coverage: complete } }],
settledCharges: [], outstandingExposures: [],
samples: [{ id: 'reviewed-change', revision: 1, productId: 'reader', profile, unit, source,
queuedAt: '2026-10-01T00:09:00.000Z', workStartedAt: '2026-10-01T00:09:10.000Z', latestObservedAt: at,
coverage: complete, usage: { kind: 'known', amount: 10, source }, state: 'accepted',
productionFinishedAt: '2026-10-01T00:09:50.000Z', reviewedAt: at,
producerId: 'builder', reviewerId: 'independent', reviewSource: source }] };
const policy = { protocol: 'sf-capacity-policy/1', id: 'explicit-scenario', revision: 1, scope, unit, profile,
comparableProductIds: ['reader'], queuedFrom: '2026-10-01T00:09:00.000Z', queuedUntil: at,
minAcceptedSamples: 1, maxSampleAgeMs: 300000, maxObservationAgeMs: 60000,
maxEvidenceAgeMs: 300000, maxForecastAgeMs: 30000, validUntil: '2026-10-01T00:20:00.000Z',
reserves: [{ id: 'owner', kind: 'owner', beneficiaryId: 'owner', windowIds: ['account-window'], amount: 20 }],
executionMode: 'successive-full-cycle-release', method: 'observed-envelope-successive-release/1',
assumptions: { futureCyclesWithinEnvelope: 'assumed', successiveFullCycleRelease: 'assumed', fixedResidualAllowance: 'assumed' } };
const forecast = forecastCapacity(inputs, policy, at);
const reopened = parseCapacityForecast(JSON.parse(JSON.stringify(forecast)));
console.log(JSON.stringify({ headroom: reopened.headroom, result: reopened.result }));
This prints residual allowance 80–80 requests and a conditional range of two additional accepted changes. The caller deliberately chose a minimum of one sample for this illustration; the library supplies no statistically confident default. A real empirical envelope does not establish that future work obeys it.
Public contract and interpretation
Exports are parseCapacityInputs, parseCapacityPolicy, forecastCapacity, parseCapacityForecast, compareCapacityOutcome, CapacityPlanningError, CAPACITY_LIMITS, CAPACITY_METHOD and their data types. Every entry revalidates strict bounded plain data, copies and deeply freezes its result. The installed declarations give every exact shape. Parsers refuse additional keys, accessors, sparse arrays, unsupported versions and invalid source pins; they do not sandbox arbitrary Proxy code.
A finite result requires a complete explicitly selected cohort, independently accepted samples with complete native usage and queue-to-review times, and all three caller assumptions:
futureCyclesWithinEnvelope: each future increment is accepted with full cost and duration inside the observed min/max envelopes, matching the exact work/model/effort/environment/review profile.successiveFullCycleRelease: queue the first additional increment atasOf; queue each later increment exactly at its predecessor's independent acceptance until the requested batch, horizon or residual allowance stops the scenario. Full cycles never overlap; there is no extra idle gap. Serial production with simultaneous queues does not satisfy this condition.fixedResidualAllowance: hold original exposure ceilings and reserves aside throughout the horizon, without releasing, reclaiming, borrowing or reallocating them into this batch; other use stays within those held allowances. This is a scenario assumption, not a provider reservation or a right to dispatch.
For horizon H, cost envelope [cMin,cMax] and full-cycle time envelope [tMin,tMax], lower is the minimum of requested count, floor(H/tMax) and each window's floor(residualLow/cMax). Upper uses floor(H/tMin) and floor(residualHigh/cMin). Historical sample intervals can overlap; they are individual duration observations, not additive historical throughput. The result is a conditional range, not probability, confidence, deadline, Commitment, grant or execution eligibility.
All current account-wide windows share an observation cutoff and constrain the whole horizon. Each settled post-cutoff charge, unresolved original full ceiling, and applicable reserve appears once per window. Overlapping windows constrain by minimum, never by summing capacity. Provider observations may already include some unresolved consumption; charging its full original ceiling again is deliberately conservative until settlement. The residual allowance upper bound is not an upper bound on actual provider capacity. A later settlement or revised reserve policy needs a newly attributed snapshot, preserving history.
The exact ceiling origin digest is SHA256 of canonical JSON with this shape: {scope:{namespace,accountId},id,productId,workLaneId,admissionId,admittedAt,ceiling:{unit,amount,admissionPolicy:{id,revision,digest}}}. Keys are sorted, arrays retain order and JSON uses ECMAScript numbers. A matching hash checks supplied bytes, not cross-snapshot authority: the host must reject a freshly rehashed replacement of the same original admission. A settled charge and an outstanding exposure cannot share an admission ID; reserve (kind,beneficiaryId,windowId) duplicates also refuse.
Empty windows, missing account coverage, reset crossings, staggered cutoffs, stale observations, unsupported comparison profiles/units, or failed/unfinished samples produce explicit unknowns. Percentage basis points never become tokens, requests, credits, runs or increments. Zero-cost or zero-duration samples cannot imply infinite throughput. Signed deficits remain inspectable and known exhaustion can be exactly zero; unavailable quantities never become zero.
Time, evidence and retained history
Time is an explicit UTC millisecond string in 1970–9999. Evidence obeys observedAt ≤ checkedAt ≤ evaluation time. Fact timestamps cannot exceed the observation supporting them. The sample's primary observedAt equals latestObservedAt; review/failure/usage support lies between its claimed fact and that latest observation. Future or contradictory support refuses. Unfinished samples separately retain confirmed duration latestObservedAt - queuedAt and elapsed age asOf - queuedAt; the latter does not prove the work stayed unfinished. There is no continuous-status assumption in v1.
Evidence freshness ends at observedAt + maxEvidenceAgeMs, quota freshness at its counter observedAt + maxObservationAgeMs, and sample freshness at reviewedAt + maxSampleAgeMs. Validation expiry and all freshness boundaries expire at equality. A fresh checkedAt does not refresh old facts. These rules apply to every state, charge, admission, usage, review, failure and outcome source. Counted acceptedSamples includes only usable comparable reviewed samples; incomplete assessment uses partial/unknown Count semantics.
sf-capacity-forecast/1 embeds exact normalised inputs/policy/time, source assessments, debit ledger, sample assessments, envelope, conditional result and digests. validUntil is the earliest relied-on policy/source/freshness/horizon/reset/max-forecast-age boundary. Unknown completion uses null validUntil to mean no finite current estimate; independently known headroom has its own expiry. All supplied evidence remains visible. Store the artefact yourself; parseCapacityForecast reproduces fixed v1 semantics with embedded time and rejects altered derivations even if the outer digest is recomputed. It consults no present source, clock or policy.
compareCapacityOutcome takes that forecast, an attributable additional accepted count for the same exact scope/profile/horizon/digest, three held | breached | unknown assumption states and explicit comparison time. The outcome host must attest the actual release schedule and unchanged residual allowance, not infer them from a count. Original forecast expiry does not invalidate retrospective calibration: historical input is checked at its own asOf. Later outcome evidence must be currently validated/unexpired and fresh under the original policy's maxEvidenceAgeMs. Incomplete evidence or a breached/unknown assumption yields unknown comparison. The same forecast/outcome/comparison time reproduces the same immutable result. Neither feedback nor a range changes a policy or renews an allowance.
Bounds and remaining work
One account/unit/profile/lane; at most 8 windows, 64 samples, 128 sources, 64 charges, 64 exposures, 32 reserves, 16 comparable Products and 64 requested increments. Native amounts are safe integers up to one trillion; percentage input is 0–10,000 basis points. IDs have 1–63 lowercase alphanumeric/hyphen characters; revisions 1–1,000,000; text 280 characters; elapsed/age/horizon bounds at most 31,536,000,000 ms. Input and complete output are each bounded to 1 MiB/depth 64. Refusal never truncates.
CapacityPlanningError.code is INVALID, LIMIT, CONFLICT or CORRUPT; reason identifies structure/version/identity/scope/reference/duplicate/time/unit/bounds/size/arithmetic/source/digest/derived-result failures. Unknown is an explicit result for well-formed insufficient facts. The runtime closure is capacity-planning/contract, canonical-json, strict-input and errors with buffer/crypto builtins; reporting vocabulary is type-only.
Current scope and evidence: build review. Multi-account/heterogeneous/parallel forecasts, resets, censored estimators, material timing, durable Plan revisions, Commitments and delivery remain separate work. No live provider qualification, broader platform support or E36 completion is established.
