diff --git a/docs/en/development/dsh-handoff-delivery.md b/docs/en/development/dsh-handoff-delivery.md new file mode 100644 index 0000000000..db4b167372 --- /dev/null +++ b/docs/en/development/dsh-handoff-delivery.md @@ -0,0 +1,77 @@ +--- +title: DSH handoff preparation and recovery +description: The internal DSH delivery interface, package format, and recovery and retention rules. +--- + +# DSH handoff preparation and recovery + +This component implements preparation and local delivery records for [RFC #2528](../rfcs/2528-dsh-plugin-ui-and-agent-handoff.md). +The authenticated DSH Host, target preflight, and launch services are separate. This component does not add a +browser route or enable delivery in the DSH UI on its own. + +## Preparing a delivery + +Construct `LocalDeliveryService` from `integrations/dsh/plugins/powercontext/src/handoff/delivery.ts` with an +absolute delivery directory, the Host's real `PreflightGate`, and a connection resolver. The shared types are +in `handoff/contracts.ts`. The Host supplies the authenticated owner and call cancellation signal in +`CallContext`. It verifies the selected session, message, inclusive event cutoff, directory, and workspace +observation time through the gate. The connection resolver must use the verified Server, connection +generation and Scope, or fail. Binding fields are identifiers; the resolver keeps credentials in memory. + +The first request waits for preparation to settle. A concurrent repeat can return the same delivery in +`preparing`; use `get` to read its state. A request key belongs to one owner and one input. A replay with +different input fails. Equivalent requests on the same verified binding reuse the delivery. To replace a +result, supply a new request key and the old `supersedesDeliveryId` after explicit user selection. The old +result and receipt attempt remain available under their original ID. + +| Input | Preparation | +| --- | --- | +| Inspected `workInput` | Validate the existing `CurrentWorkHandoff` fields, evidence and 32 KiB input limit; call `handoff_current_work` once. Save its full Prepared value and boundary receipt. | +| Configured generation and a trusted boundary reader | Capture bounded task evidence using the Source API. Call `prepare_handoff` once, validate the draft and send it unchanged to `finalize_handoff`. Save the complete result and the actual capture receipt. | +| Explicit exact Handoff Revision | Verify the exact `ArtifactReference` in the bound Scope and save that reference. The reference uses the existing integer `revision` field. | +| No usable generation or inspected fields | Report `needs_input`; ask for inspected work fields and prepare a new version. | + +The Host's `BoundaryReader` supplies the selected reply and observations at that boundary. Its underlying +read must honor the requested limits; the collector also enforces 512 events including the selected reply, +256 KiB overall and 32 KiB for workspace evidence, subject to the lower Source and configured model input +limits. It preserves known test statuses, exact citations when supplied, revisions and working tree +observations. It considers at most 16 Host omission entries and records a summary omission if any +entries cannot be included. No observed check means the result is unknown. An explicit check that did +not run is different from a failure, interruption, or missing evidence. The reader must not run tests or replace an +unavailable workspace observation with the current directory state. For configured generation, use a +client configured for the intended generation deadline; the service caps the model call at 90 seconds. +There is no generation fallback or automatic milestone commit. + +## Package integrity and recovery + +The Host uses a private directory on a local filesystem below its user data. The store holds an exclusive +kernel lock on the open directory until the service closes or the Host process exits. It uses macOS +file locking or Linux util-linux `/usr/bin/flock`; an unavailable lock prevents the store from opening. +Legacy PID marker files are ignored. Stop any Host running the PID marker implementation before opening +the same directory with this implementation. + +Records and packages use `powercontext.dsh-delivery.v1` and are stored separately by delivery ID. The +service writes identity, binding and the `content` ACK source ID before dispatch. It persists the expected +size and file checksum before atomically publishing the complete package. Recovery verifies those bytes and +the original source, binding, receipt attempt and carrier before publishing `prepared`. An interruption +without a valid package becomes `unknown`; recovering from a Source or re-finalizing would not recover the +original package. A cancelled call before dispatch stops preparation. Once a call may have run, interruption +can leave its outcome unknown. Cancellation preserves a complete saved package. + +`getForLaunch` checks authorization and package integrity. It returns the exact stored binding, selection, +path, checksum and ACK identity. The Prepared digest is the Core Work digest of the canonical Prepared +value. The package SHA-256 checks the bytes of the whole JSON file. Keep both values; neither can substitute +for the other. Export returns the full validated bytes. If a launch path will be consumed asynchronously, +use `withLaunchBundle` while reading or copying it into a verified location; explicit deletion and pruning +are blocked while that reader holds the path. Call `close` on Host shutdown. + +The default capacity is 100 carrier slots or 50 MiB, with space reserved for in-flight preparations. The +service never evicts pending or pinned packages to make room. Owners can pin, export or explicitly delete +a delivery. Deletion leaves an idempotency tombstone for 30 days. Automatic package expiry requires the +future exact ACK verifier to supply confirmation for that receipt attempt. An unpinned confirmed package can +expire after seven days; its metadata is kept for 30 days after confirmation. Cleanup does not touch Server +records or write an acceptance state. Unsupported record versions are rejected and left on disk. + +Host integration still needs to wire real authenticated boundary reads and connection resolution, map the +safe delivery errors into Host responses, and coordinate path consumption with launch and deletion. Native +target launch and receipt verification require separate acceptance tests. diff --git a/docs/zh/development/dsh-handoff-delivery.md b/docs/zh/development/dsh-handoff-delivery.md new file mode 100644 index 0000000000..08d9c43639 --- /dev/null +++ b/docs/zh/development/dsh-handoff-delivery.md @@ -0,0 +1,60 @@ +--- +title: DSH 交接准备与恢复 +description: DSH 交付的内部接口、交接包格式、恢复与保留规则。 +--- + +# DSH 交接准备与恢复 + +此组件实现 [RFC #2528](../rfcs/2528-dsh-plugin-ui-and-agent-handoff.md) 的交接准备和本地交付记录。DSH Host +认证、目标预检和启动由各自的服务处理。此组件本身不注册浏览器路由,也不会在 DSH 界面启用交付。 + +## 准备交付 + +使用 `integrations/dsh/plugins/powercontext/src/handoff/delivery.ts` 中的 `LocalDeliveryService`,传入交付目录的 +绝对路径、Host 的真实 `PreflightGate` 和连接解析器。共用类型见 `handoff/contracts.ts`。Host 通过 +`CallContext` 传入认证后的所有者和本次调用的取消信号。预检核对选中的会话、消息、包含该事件的截止点、目录和 +工作区观测时间。连接解析器必须使用验证过的 Server、连接代次和 Scope;无法匹配时拒绝请求。绑定中只保存标识, +凭据由解析器保留在内存中。 + +首次请求等待准备结束;并发重复请求可以读到同一交付的 `preparing`,随后通过 `get` 查看状态。幂等键绑定一个 +所有者和一份输入,携带不同输入重放时会拒绝。同一已验证绑定下的等价请求复用交付。用户明确选择创建新版本时, +使用新的请求键并传入旧交付的 `supersedesDeliveryId`。旧结果和接收尝试仍可通过原 ID 查看。 + +| 可用输入 | 准备路径 | +| --- | --- | +| 经检查的 `workInput` | 按现有 `CurrentWorkHandoff` 字段、证据规则和 32 KiB 输入上限校验;调用一次 `handoff_current_work`,保存完整 Prepared 和 boundary receipt。 | +| 已配置生成流程和可信边界读取器 | 通过 Source API 保存有界任务证据,调用一次 `prepare_handoff`,校验 draft 后原样发送给 `finalize_handoff`。保存完整结果和实际采集回执。 | +| 用户明确选择的精确 Handoff Revision | 在已验证的 Scope 中核对精确的 `ArtifactReference` 并保存该引用,沿用整数 `revision` 字段。 | +| 没有可用的生成流程或经检查的字段 | 返回 `needs_input`;用户补充并检查工作字段后创建新版本。 | + +Host 的 `BoundaryReader` 提供选定回复和该边界的观测。底层读取必须遵守传入的限制;采集器也会限制总事件数 +(含选定回复,最多 512 个)、总量(最多 256 KiB)和工作区证据(最多 32 KiB),并遵守更低的 Source 或模型 +输入预算。采集器保留已知测试状态、提供的精确证据引用、revision 和工作区观测。最多处理 16 条 Host 遗漏说明; +如果有说明未能纳入,则记录一条汇总说明。未捕获检查证据时结果未知; +明确未运行、失败、中断和证据缺失各有不同含义。读取器不运行测试,也不能用当前工作区替代缺失的历史观测。 +生成路径需要配置适合生成的客户端超时;服务给模型调用设置 90 秒上限。生成失败后不自动切换路径, +也不会自动提交里程碑。 + +## 包完整性与恢复 + +Host 在本地文件系统的用户数据下使用私有目录。交付服务对已打开的目录持有内核独占锁,直到服务关闭或 Host 进程 +退出。macOS 使用系统文件锁,Linux 使用 util-linux 的 `/usr/bin/flock`;无法获取锁时不会打开交付存储。旧的 +PID 标记文件会被忽略。打开同一目录前,先停止仍在使用 PID 标记的旧 Host。 + +交付记录和包使用 `powercontext.dsh-delivery.v1`,按交付 ID 分开保存。远端调用前先保存身份、绑定和类型为 `content` 的 ACK +source ID。原子发布完整包之前先持久化预期大小和文件校验和。恢复时校验文件字节以及原始边界、绑定、接收尝试 +和载体,通过后才发布 `prepared`。中断时没有有效包则记为 `unknown`;已有 Source 或重新 finalize 无法恢复 +原包。发送前取消会停止准备;发送后中断可能留下未知结果。取消不会删除已经保存的完整包。 + +`getForLaunch` 校验所有者和包完整性,返回已保存的精确绑定、载体选择、路径、校验和及 ACK 身份。Prepared +digest 是 Core Work 对规范化 Prepared 值计算的摘要;包的 SHA-256 校验整个 JSON 文件的字节。两者分别保留。 +导出返回校验后的完整字节。如果启动流程要异步使用路径,请在 `withLaunchBundle` 中读取或复制到验证过的共享位置; +持有路径期间禁止显式删除和自动清理。Host 关闭时调用 `close`。 + +默认上限为 100 个载体记录或 50 MiB,并为正在准备的交付预留空间。容量不足时不会淘汰待接收或固定保留的包。 +所有者可以固定、导出或显式删除交付。删除后保留幂等键标记 30 天。自动清理需要后续的精确 ACK 验证服务为该接收 +尝试提供确认时间;已确认且未固定的包可在七天后清理,元数据保留到确认后 30 天。清理不删除 Server 记录或写入 +接收状态。不支持的记录版本会被拒绝,原文件保留。 + +Host 联调还需接入真实认证、边界读取和连接解析,将交付错误映射到 Host 响应,并协调启动读取与删除。原生目标 +启动和接收验证需要单独验收。 diff --git a/integrations/dsh/plugins/powercontext/scripts/e2e-server.d.mts b/integrations/dsh/plugins/powercontext/scripts/e2e-server.d.mts new file mode 100644 index 0000000000..1545c2056c --- /dev/null +++ b/integrations/dsh/plugins/powercontext/scripts/e2e-server.d.mts @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export function defaultPowerContextRoot(): string | undefined +export function unusedPort(): Promise +export function waitForUrl(url: string, timeoutMs?: number, checkProcess?: () => void): Promise +export function startPowerContextServer(options?: { env?: NodeJS.ProcessEnv }): Promise<{ + baseUrl: string + home: string + root: string + stop: () => Promise +}> diff --git a/integrations/dsh/plugins/powercontext/src/handoff/contracts.ts b/integrations/dsh/plugins/powercontext/src/handoff/contracts.ts new file mode 100644 index 0000000000..fa63503670 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/contracts.ts @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Wire } from './wire.ts' + +// In-process only. The authenticated Host supplies ownerId. +export interface CallContext { + readonly ownerId: string + readonly signal: AbortSignal +} + +export interface SourceBoundary { + readonly sessionId: string + readonly messageId: string + readonly throughSeq: number + readonly cwd: string + /** ISO 8601 time of the selected workspace observation. */ + readonly workspaceObservedAt: string +} + +export interface VerifiedPreflight { + readonly preflightId: string + readonly revision: number + readonly source: SourceBoundary + readonly targetId: string + readonly targetVersion: string + readonly adapterVersion: string + readonly effectiveCwd: string + readonly serverIdentity: string + readonly connectionRef: string + readonly connectionGeneration: number + readonly scopeId: string +} + +export interface ReceiptAttempt { + readonly receiptAttemptId: string + readonly sourceType: Wire<'SourceReference'>['name'] + readonly sourceId: string +} + +export type HandoffSelection = + | { readonly kind: 'prepared'; readonly digest: string } + | { readonly kind: 'revision'; readonly revision: Readonly> & { readonly scope_id: string } } + +export interface LaunchBundle { + readonly deliveryId: string + readonly source: SourceBoundary + readonly binding: VerifiedPreflight + readonly packagePath: string + readonly packageSha256: string + readonly handoffSelection: HandoffSelection + readonly receiptAttempt: ReceiptAttempt +} + +export interface ValidateForPrepareInput { + readonly preflightId: string + readonly expectedRevision: number + readonly source: SourceBoundary +} + +export interface PreflightGate { + validateForPrepare( + context: CallContext, + input: ValidateForPrepareInput, + ): Promise +} + +export type PreparationState = 'preparing' | 'needs_input' | 'prepared' | 'failed' | 'cancelled' | 'unknown' +export type DeliveryErrorCode = + | 'not_found' | 'not_ready' | 'stale_preflight' | 'binding_mismatch' + | 'idempotency_conflict' | 'integration_unavailable' | 'capacity_exceeded' + | 'payload_invalid' | 'outcome_unknown' + +const errors: Record = { + not_found: 'The requested delivery or preflight was not found.', + not_ready: 'The requested operation is not ready.', + stale_preflight: 'Preflight conditions changed; verify the target again.', + binding_mismatch: 'The source boundary or delivery binding does not match.', + idempotency_conflict: 'This request conflicts with an existing delivery.', + integration_unavailable: 'The delivery integration is unavailable.', + capacity_exceeded: 'Delivery storage is full. Export and remove a delivery or increase the limit.', + payload_invalid: 'The delivery input or package is invalid.', + outcome_unknown: 'Preparation may have run, but no complete package can be recovered.', +} + +export function isDeliveryErrorCode(value: unknown): value is DeliveryErrorCode { + return typeof value === 'string' && Object.hasOwn(errors, value) +} + +export class DeliveryError extends Error { + readonly code: DeliveryErrorCode + constructor(code: DeliveryErrorCode) { + super(errors[code]) + this.name = 'DeliveryError' + this.code = code + } +} + +export interface PrepareDeliveryInput extends ValidateForPrepareInput { + readonly requestId: string + readonly workInput?: unknown + /** An exact, explicitly selected Handoff Revision in the verified Scope. */ + readonly revision?: Wire<'ArtifactReference'> + /** Explicitly create a new version, retaining the old delivery. Use a new requestId. */ + readonly supersedesDeliveryId?: string +} + +export interface DeliveryView { + readonly deliveryId: string + readonly preparationState: PreparationState + readonly source: SourceBoundary + readonly binding: VerifiedPreflight + readonly receiptAttempt: ReceiptAttempt + readonly createdAt: string + readonly updatedAt: string + readonly pinned: boolean + readonly expired: boolean + readonly error?: { code: DeliveryErrorCode; message: string } + readonly recoveryActions: readonly ('supply_work_input' | 'create_new_version' | 'export_package')[] + readonly preview?: { objective: string; disposition: Wire<'HandoffDisposition'>; omissionCount: number } +} + +export interface PackageExport { + readonly filename: string + readonly mediaType: 'application/json' + readonly packageSha256: string + readonly bytes: Uint8Array +} + +export interface DeliveryService { + prepare(context: CallContext, input: PrepareDeliveryInput): Promise + get(context: CallContext, deliveryId: string): Promise + getForLaunch(context: CallContext, deliveryId: string): Promise + cancelPreparation(context: CallContext, deliveryId: string): Promise + exportPackage(context: CallContext, deliveryId: string): Promise +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/delivery.ts b/integrations/dsh/plugins/powercontext/src/handoff/delivery.ts new file mode 100644 index 0000000000..807d6cb4eb --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/delivery.ts @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { randomUUID } from 'node:crypto' +import { combineSignals } from '../client.ts' +import { DeliveryError, isDeliveryErrorCode } from './contracts.ts' +import type { CallContext, DeliveryErrorCode, DeliveryService, DeliveryView, LaunchBundle, PackageExport, + PreflightGate, PrepareDeliveryInput, VerifiedPreflight } from './contracts.ts' +import { deliveryIdPattern, receiptIdentity, verifiedBinding } from './identity.ts' +import { boundary, inspectedWork, sameBoundary } from './materials.ts' +import type { BoundaryReader } from './materials.ts' +import { knownPreparationFailure, prepareCarrier, validateCarrier } from './prepare.ts' +import type { Carrier, PreparationConnectionResolver } from './prepare.ts' +import { DELIVERY_SCHEMA, DeliveryStore, MAX_PACKAGE_BYTES, MAX_REQUEST_KEYS } from './store.ts' +import type { DeliveryRecord } from './store.ts' +import { invalid, object, sha256, trimmed, wire } from './wire.ts' + +const DAY = 86_400_000 +const SEVEN_DAYS = 7 * DAY +const THIRTY_DAYS = 30 * DAY +const MAX_METADATA_RECORDS = 1000 +const defaultLimits = { maxDeliveries: 100, maxBytes: 50 * 1024 * 1024 } + +type NormalizedInput = ReturnType +type Operation = { controller: AbortController; done?: Promise } + +export interface DeliveryOptions { + /** Absolute path under trusted Host user data. Parent must already exist. */ + directory: string + preflightGate?: PreflightGate + resolveConnection: PreparationConnectionResolver + readBoundary?: BoundaryReader + limits?: Partial + now?: () => number +} + +function normalize(input: PrepareDeliveryInput) { + const fields = ['requestId', 'preflightId', 'expectedRevision', 'source', 'workInput', 'revision', 'supersedesDeliveryId'] + if (!object(input) || Object.keys(input).some(field => !fields.includes(field)) || !trimmed(input.requestId, 128) || !trimmed(input.preflightId, 256) + || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 1 + || (input.supersedesDeliveryId !== undefined && !deliveryIdPattern.test(input.supersedesDeliveryId))) invalid() + const revision = input.revision === undefined ? undefined : wire('ArtifactReference', input.revision) + if (revision && (revision.family !== 'handoff' || input.workInput !== undefined)) invalid() + return { + requestId: input.requestId, + preflightId: input.preflightId, + expectedRevision: input.expectedRevision, + source: boundary(input.source), + workInput: input.workInput === undefined ? undefined : inspectedWork(input.workInput), + revision, + supersedesDeliveryId: input.supersedesDeliveryId, + } +} + +function key(ownerId: string, requestId: string): string { + return JSON.stringify([ownerId, requestId]) +} + +function sameBinding(a: VerifiedPreflight, b: VerifiedPreflight): boolean { + return JSON.stringify(a) === JSON.stringify(b) // Both are projected in contract order. +} + +function packageData(record: DeliveryRecord, carrier: Carrier) { + return { + schema: DELIVERY_SCHEMA, + deliveryId: record.deliveryId, + source: record.binding.source, + binding: record.binding, + receiptAttempt: record.receiptAttempt, + carrier, + } +} + +function safeError(error: unknown): DeliveryError { + // The injected gate and connection resolver can use different error classes. + // Keep only the shared code and never pass through remote messages or causes. + const code = object(error) ? error.code : undefined + if (isDeliveryErrorCode(code)) return new DeliveryError(code) + if (code === 'ENOSPC' || code === 'EDQUOT') return new DeliveryError('capacity_exceeded') + return new DeliveryError('integration_unavailable') +} + +/** Task 4 supplies the real gate and exact connection resolver when it wires the Host. */ +export class LocalDeliveryService implements DeliveryService { + private readonly store: DeliveryStore + private readonly active = new Map() + private readonly launchReaders = new Map() + private readonly requestIndex = new Map() + private readonly limits: typeof defaultLimits + private readonly options: DeliveryOptions + private closing?: Promise + + constructor(options: DeliveryOptions) { + this.options = options + this.limits = { ...defaultLimits, ...options.limits } + if (Object.values(this.limits).some(limit => !Number.isSafeInteger(limit) || limit < 1) + || this.limits.maxDeliveries > MAX_METADATA_RECORDS) invalid() + try { + this.store = new DeliveryStore(options.directory) + try { + for (const record of this.store.records.values()) { + for (const request of record.requests) { + const indexKey = key(record.ownerId, request.id) + if (this.requestIndex.has(indexKey)) invalid() + this.requestIndex.set(indexKey, { deliveryId: record.deliveryId, fingerprint: request.fingerprint }) + } + if (record.deletedAt || record.expiredAt) this.store.removePackage(record.deliveryId) + else if (record.preparationState === 'preparing') this.recover(record) + } + } catch (error) { + this.store.close() + throw error + } + } catch (error) { + throw safeError(error) + } + } + + private get now(): number { + return this.options.now?.() ?? Date.now() + } + + private updated(record: DeliveryRecord, changes: Partial): DeliveryRecord { + try { + return this.store.put({ ...record, ...changes, updatedAt: new Date(this.now).toISOString() }) + } catch (error) { + throw safeError(error) + } + } + + private caller(context: CallContext): void { + if (this.closing) throw new DeliveryError('integration_unavailable') + if (!trimmed(context.ownerId, 256)) throw new DeliveryError('not_found') + if (context.signal.aborted) throw new DeliveryError('not_ready') + } + + private owned(context: CallContext, deliveryId: string): DeliveryRecord { + this.caller(context) + const record = this.store.records.get(deliveryId) + if (!record || record.ownerId !== context.ownerId || record.deletedAt) throw new DeliveryError('not_found') + return record + } + + private replay(owner: string, request: string, fingerprint: string): DeliveryRecord | undefined { + const replay = this.requestIndex.get(key(owner, request)) + if (!replay) return undefined + if (replay.fingerprint !== fingerprint) throw new DeliveryError('idempotency_conflict') + const record = this.store.records.get(replay.deliveryId) + if (!record || record.deletedAt) throw new DeliveryError('not_found') + return record + } + + private validatedPackage(record: DeliveryRecord) { + if (!record.package || record.expiredAt || record.deletedAt) invalid() + const bytes = this.store.readPackage(record.deliveryId) + if (bytes.length !== record.package.bytes || sha256(bytes) !== record.package.sha256) invalid() + const value: unknown = JSON.parse(bytes.toString('utf8')) + if (!object(value) || value.schema !== DELIVERY_SCHEMA || value.deliveryId !== record.deliveryId + || !object(value.source) || !sameBoundary(boundary(value.source as unknown as VerifiedPreflight['source']), record.binding.source) + || !sameBinding(verifiedBinding(value.binding), record.binding) + || JSON.stringify(receiptIdentity(value.receiptAttempt)) !== JSON.stringify(record.receiptAttempt)) invalid() + const carrier = validateCarrier(value.carrier, record.binding, record.deliveryId) + return { bytes, carrier, sha256: record.package.sha256 } + } + + private recover(record: DeliveryRecord): DeliveryRecord { + let ready = false + try { + this.validatedPackage(record) + ready = true + } catch { + // A boundary Source, or a valid-looking unbound file, cannot recover the original. + } + return this.updated(record, ready ? { preparationState: 'prepared', error: undefined } + : { preparationState: 'unknown', error: 'outcome_unknown' }) + } + + private reconcile(record: DeliveryRecord): DeliveryRecord { + return record.preparationState === 'preparing' && !this.active.has(record.deliveryId) ? this.recover(record) : record + } + + private view(record: DeliveryRecord): DeliveryView { + record = this.reconcile(record) + let preview: DeliveryView['preview'] + if (record.preparationState === 'prepared' && !record.expiredAt) { + try { + const { carrier } = this.validatedPackage(record) + if (carrier.kind === 'prepared') { + const { objective, disposition, omissions } = carrier.prepared.content + preview = { objective, disposition, omissionCount: omissions.length } + } + } catch { + record = this.updated(record, { preparationState: 'unknown', error: 'outcome_unknown' }) + } + } + const recovery: Array = [] + if (record.preparationState === 'prepared' && !record.expiredAt) recovery.push('export_package') + if (record.preparationState === 'needs_input') recovery.push('supply_work_input') + if (record.expiredAt || ['unknown', 'failed', 'cancelled', 'needs_input'].includes(record.preparationState)) { + recovery.push('create_new_version') + } + return structuredClone({ + deliveryId: record.deliveryId, + preparationState: record.preparationState, + source: record.binding.source, + binding: record.binding, + receiptAttempt: record.receiptAttempt, + createdAt: record.createdAt, + updatedAt: record.updatedAt, + pinned: record.pinned, + expired: !!record.expiredAt, + ...(preview ? { preview } : {}), + ...(record.error ? { error: { code: record.error, message: new DeliveryError(record.error).message } } : {}), + recoveryActions: recovery, + }) + } + + private matchingOperation(owner: string, binding: VerifiedPreflight, input: NormalizedInput, fingerprint: string) { + let same: DeliveryRecord | undefined + let active: DeliveryRecord | undefined + let saved: DeliveryRecord | undefined + const records = [...this.store.records.values()].filter(record => record.ownerId === owner + && record.binding.targetId === binding.targetId && sameBoundary(record.binding.source, binding.source)) + const superseded = new Set(records.map(record => record.supersedesDeliveryId)) + for (const record of records) { + if (record.deletedAt || record.expiredAt || superseded.has(record.deliveryId)) continue + if (record.preparationState === 'unknown' || record.preparationState === 'preparing') active ??= record + if (!sameBinding(record.binding, binding)) continue + if (record.preparationState === 'prepared') saved = record + if (record.requests.some(request => request.fingerprint === fingerprint) + && ['prepared', 'preparing', 'needs_input', 'unknown'].includes(record.preparationState)) same = record + } + if (input.supersedesDeliveryId) { + const original = this.store.records.get(input.supersedesDeliveryId) + if (!original || original.deletedAt || original.ownerId !== owner) throw new DeliveryError('not_found') + if (original.binding.targetId !== binding.targetId || !sameBoundary(original.binding.source, binding.source)) { + throw new DeliveryError('binding_mismatch') + } + // A second request for the same replacement reuses it, rather than branching the history. + if (same && same.supersedesDeliveryId === original.deliveryId) return same + if (original.preparationState === 'preparing' || this.active.has(original.deliveryId) + || (active && active.deliveryId !== original.deliveryId)) throw new DeliveryError('not_ready') + if (superseded.has(original.deliveryId)) throw new DeliveryError('idempotency_conflict') + return undefined + } + if (active?.preparationState === 'unknown') { + if (same?.deliveryId === active.deliveryId) return active + throw new DeliveryError('outcome_unknown') + } + if (active && same?.deliveryId !== active.deliveryId) { + throw new DeliveryError(sameBinding(active.binding, binding) ? 'idempotency_conflict' : 'binding_mismatch') + } + if (saved && !same) throw new DeliveryError('idempotency_conflict') + return same + } + + private usage(): { bytes: number; count: number } { + let bytes = 0 + let count = 0 + for (const record of this.store.records.values()) { + if (record.deletedAt || record.expiredAt) continue + if (record.package) { + bytes += record.package.bytes + count++ + } else if (record.preparationState === 'preparing') { + bytes += Math.min(this.limits.maxBytes, MAX_PACKAGE_BYTES) + count++ + } else if (record.preparationState === 'unknown') count++ + } + return { bytes, count } + } + + async prepare(context: CallContext, input: PrepareDeliveryInput): Promise { + this.caller(context) + const normalized = normalize(input) + const { requestId, preflightId, expectedRevision, source } = normalized + const fingerprint = sha256(JSON.stringify({ ...normalized, requestId: undefined })) + const owner = context.ownerId + const replay = this.replay(owner, requestId, fingerprint) + if (replay) return this.view(replay) + const gate = this.options.preflightGate + if (!gate) throw new DeliveryError('integration_unavailable') + let binding: VerifiedPreflight + try { + binding = verifiedBinding(await gate.validateForPrepare(context, { preflightId, expectedRevision, source: { ...source } })) + } catch (error) { + if (context.signal.aborted) throw new DeliveryError('not_ready') + throw safeError(error) + } + this.caller(context) + if (binding.preflightId !== preflightId || !sameBoundary(binding.source, source)) throw new DeliveryError('binding_mismatch') + if (binding.revision !== expectedRevision) throw new DeliveryError('stale_preflight') + + // Everything through reservation and publication of the identity is synchronous. + const concurrentReplay = this.replay(owner, requestId, fingerprint) + if (concurrentReplay) return this.view(concurrentReplay) + const same = this.matchingOperation(owner, binding, normalized, fingerprint) + if (same) { + if (same.requests.length >= MAX_REQUEST_KEYS) throw new DeliveryError('capacity_exceeded') + const updated = this.updated(same, { requests: [...same.requests, { id: requestId, fingerprint }] }) + this.requestIndex.set(key(owner, requestId), { deliveryId: same.deliveryId, fingerprint }) + return this.view(updated) + } + const { bytes, count } = this.usage() + if (count >= this.limits.maxDeliveries || bytes + Math.min(this.limits.maxBytes, MAX_PACKAGE_BYTES) > this.limits.maxBytes + || this.store.records.size >= MAX_METADATA_RECORDS) throw new DeliveryError('capacity_exceeded') + const deliveryId = randomUUID() + const receiptAttemptId = randomUUID() + const record = this.updated({ + schema: DELIVERY_SCHEMA, deliveryId, ownerId: owner, requests: [{ id: requestId, fingerprint }], + binding, receiptAttempt: { receiptAttemptId, sourceType: 'content', sourceId: 'dsh-ack:' + receiptAttemptId }, + preparationState: 'preparing', dispatched: false, pinned: false, + createdAt: new Date(this.now).toISOString(), updatedAt: '', + supersedesDeliveryId: normalized.supersedesDeliveryId, + }, {}) + this.requestIndex.set(key(owner, requestId), { deliveryId, fingerprint }) + const operation: Operation = { controller: new AbortController() } + this.active.set(deliveryId, operation) + const signal = combineSignals([context.signal, operation.controller.signal]) + operation.done = this.run({ ownerId: owner, signal }, record, normalized) + return operation.done + } + + private async run(context: CallContext, initial: DeliveryRecord, input: NormalizedInput): Promise { + const id = initial.deliveryId + const latest = () => this.store.records.get(id)! + const { signal } = context + let final: DeliveryRecord + try { + const carrier = await prepareCarrier(context, initial.binding, input, id, this.options.resolveConnection, + this.options.readBoundary, () => { + signal.throwIfAborted() + if (!latest().dispatched) this.updated(latest(), { dispatched: true }) + }) + signal.throwIfAborted() + if (!carrier) final = this.updated(latest(), { preparationState: 'needs_input' }) + else { + const bytes = Buffer.from(JSON.stringify(packageData(initial, carrier))) + if (bytes.length > this.limits.maxBytes || bytes.length > MAX_PACKAGE_BYTES) { + throw new DeliveryError('capacity_exceeded') + } + const staged = this.updated(latest(), { package: { bytes: bytes.length, sha256: sha256(bytes) } }) + this.store.writePackage(id, bytes) + final = this.updated(staged, { preparationState: 'prepared' }) + } + } catch (error) { + const record = latest() + const known = knownPreparationFailure(error) + if (record.preparationState !== 'preparing') final = record + else if (record.package) final = this.recover(record) + else { + let state: DeliveryRecord['preparationState'] + let code: DeliveryErrorCode | undefined + if (record.dispatched && !known) { + state = 'unknown' + code = error instanceof DeliveryError && error.code === 'capacity_exceeded' ? error.code : 'outcome_unknown' + } else if (signal.aborted) state = 'cancelled' + else { + state = 'failed' + code = (known ?? safeError(error)).code + } + final = this.updated(record, { preparationState: state, error: code }) + } + } finally { + this.active.delete(id) + } + return this.view(final) + } + + async get(context: CallContext, deliveryId: string): Promise { + return this.view(this.owned(context, deliveryId)) + } + + async list(context: CallContext): Promise { + this.caller(context) + return [...this.store.records.values()].filter(record => record.ownerId === context.ownerId && !record.deletedAt) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)).map(record => this.view(record)) + } + + private saved(record: DeliveryRecord) { + record = this.reconcile(record) + if (record.expiredAt) throw new DeliveryError('not_found') + if (record.preparationState !== 'prepared') { + throw new DeliveryError(record.preparationState === 'unknown' ? 'outcome_unknown' : 'not_ready') + } + try { + return this.validatedPackage(record) + } catch { + this.updated(record, { preparationState: 'unknown', error: 'outcome_unknown' }) + throw new DeliveryError('outcome_unknown') + } + } + + private launchBundle(record: DeliveryRecord): LaunchBundle { + const { carrier, sha256 } = this.saved(record) + return structuredClone({ + deliveryId: record.deliveryId, + source: record.binding.source, + binding: record.binding, + packagePath: this.store.packagePath(record.deliveryId), + packageSha256: sha256, + handoffSelection: carrier.kind === 'prepared' ? { kind: 'prepared', digest: carrier.digest } + : { kind: 'revision', revision: { scope_id: record.binding.scopeId, ...carrier.revision } }, + receiptAttempt: record.receiptAttempt, + }) + } + + private holdPath(deliveryId: string): () => void { + this.launchReaders.set(deliveryId, (this.launchReaders.get(deliveryId) ?? 0) + 1) + return () => { + const remaining = this.launchReaders.get(deliveryId)! - 1 + if (remaining) this.launchReaders.set(deliveryId, remaining) + else this.launchReaders.delete(deliveryId) + } + } + + async getForLaunch(context: CallContext, deliveryId: string): Promise { + const bundle = this.launchBundle(this.owned(context, deliveryId)) + // A concurrent delete in the same turn must not unlink a path being returned. + queueMicrotask(this.holdPath(deliveryId)) + return bundle + } + + /** Use when a later asynchronous step needs the path to remain on disk. */ + async withLaunchBundle( + context: CallContext, deliveryId: string, use: (bundle: LaunchBundle) => Promise, + ): Promise { + const bundle = this.launchBundle(this.owned(context, deliveryId)) + const release = this.holdPath(deliveryId) + try { + return await use(bundle) + } finally { + release() + } + } + + async exportPackage(context: CallContext, deliveryId: string): Promise { + const { bytes, sha256 } = this.saved(this.owned(context, deliveryId)) + return { bytes, packageSha256: sha256, mediaType: 'application/json', filename: deliveryId + '.json' } + } + + async cancelPreparation(context: CallContext, deliveryId: string): Promise { + let record = this.owned(context, deliveryId) + if (record.preparationState === 'preparing') { + if (record.package) record = this.recover(record) + else record = this.updated(record, record.dispatched + ? { preparationState: 'unknown', error: 'outcome_unknown' } + : { preparationState: 'cancelled' }) + this.active.get(deliveryId)?.controller.abort() + } else if (record.preparationState === 'needs_input') { + record = this.updated(record, { preparationState: 'cancelled' }) + } + return this.view(record) + } + + async pin(context: CallContext, deliveryId: string, pinned: boolean): Promise { + const record = this.owned(context, deliveryId) + if (record.expiredAt) throw new DeliveryError('not_found') + if (typeof pinned !== 'boolean') invalid() + return this.view(this.updated(record, { pinned })) + } + + async delete(context: CallContext, deliveryId: string): Promise { + const record = this.owned(context, deliveryId) + if (this.active.has(deliveryId) || this.launchReaders.has(deliveryId)) throw new DeliveryError('not_ready') + this.updated(record, { deletedAt: new Date(this.now).toISOString(), package: undefined }) + try { + this.store.removePackage(deliveryId) + } catch (error) { + throw safeError(error) + } + } + + /** Only the future exact ACK verifier may supply confirmedAt. No ACK state is written here. */ + async prune( + context: CallContext, + confirmedAt?: (bundle: LaunchBundle) => Promise, + ): Promise { + this.caller(context) + for (const original of [...this.store.records.values()]) { + this.caller(context) + if (original.ownerId !== context.ownerId || original.pinned && !original.deletedAt + || this.active.has(original.deliveryId) || this.launchReaders.has(original.deliveryId)) continue + const id = original.deliveryId + const age = this.now - Date.parse(original.deletedAt ?? original.expiredAt ?? original.updatedAt) + if ((original.deletedAt || original.expiredAt || ['failed', 'cancelled', 'needs_input'].includes(original.preparationState)) + && age >= THIRTY_DAYS) { + try { + this.store.forget(id) + for (const request of original.requests) this.requestIndex.delete(key(original.ownerId, request.id)) + } catch (error) { + throw safeError(error) + } + } else if (confirmedAt && original.preparationState === 'prepared' && !original.expiredAt && !original.deletedAt) { + let at: number | undefined + try { + at = await this.withLaunchBundle(context, id, confirmedAt) + } catch (error) { + if (error instanceof DeliveryError && error.code === 'outcome_unknown') continue + throw safeError(error) + } + this.caller(context) + const current = this.store.records.get(id) + if (current !== original || this.launchReaders.has(id) || !Number.isSafeInteger(at) || at === undefined + || at < Date.parse(original.createdAt) || this.now - at < SEVEN_DAYS) continue + this.updated(original, { expiredAt: new Date(at).toISOString(), package: undefined }) + try { + this.store.removePackage(id) + } catch (error) { + throw safeError(error) + } + } + } + } + + /** Dispose on Host shutdown. Requests that may have run recover as unknown. */ + close(): Promise { + if (this.launchReaders.size) return Promise.reject(new DeliveryError('not_ready')) + return this.closing ??= (async () => { + for (const operation of this.active.values()) operation.controller.abort() + await Promise.allSettled([...this.active.values()].map(operation => operation.done)) + this.store.close() + })() + } +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/http.generated.ts b/integrations/dsh/plugins/powercontext/src/handoff/http.generated.ts new file mode 100644 index 0000000000..f6dc78f142 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/http.generated.ts @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// generated from openapi/powercontext.yaml; do not edit. + +export const HANDOFF_HTTP_SCHEMAS = { + ArtifactReference: {"type":"object","additionalProperties":false,"required":["family","artifact_id","revision"],"properties":{"family":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[\\x21-\\x7E]+$"},"artifact_id":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[\\x21-\\x7E]+$"},"revision":{"type":"integer","minimum":1}}}, + CaptureContentSourceResponse: {"type":"object","additionalProperties":false,"required":["status","source","position"],"properties":{"status":{"$ref":"CaptureStatus"},"source":{"$ref":"SourceReference"},"position":{"type":"integer","minimum":1}}}, + CaptureStatus: {"type":"string","enum":["accepted"]}, + CurrentWorkHandoff: {"type":"object","additionalProperties":false,"required":["schema","trust","objective","state","disposition","next_action","omissions"],"properties":{"schema":{"type":"string","enum":["powercontext.current-work-handoff.v1"]},"trust":{"type":"string","enum":["untrusted_input"]},"objective":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"state":{"type":"array","minItems":1,"maxItems":64,"items":{"$ref":"WorkClaim"}},"disposition":{"$ref":"HandoffDisposition"},"next_action":{"$ref":"WorkClaim","nullable":true},"omissions":{"type":"array","maxItems":64,"items":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"}}}}, + HandoffArtifactCitation: {"type":"object","additionalProperties":false,"required":["kind","artifact_ref"],"properties":{"kind":{"type":"string","enum":["artifact"]},"artifact_ref":{"$ref":"ArtifactReference"}}}, + HandoffCitation: {"oneOf":[{"$ref":"HandoffSourceCitation"},{"$ref":"HandoffArtifactCitation"}]}, + HandoffContent: {"type":"object","additionalProperties":false,"required":["schema","objective","state","disposition","next_action","omissions"],"properties":{"generation":{"$ref":"HandoffGenerationMetadata","nullable":true},"schema":{"$ref":"HandoffSchema"},"objective":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"state":{"type":"array","minItems":1,"maxItems":64,"items":{"$ref":"HandoffStatement"}},"disposition":{"$ref":"HandoffDisposition"},"next_action":{"$ref":"HandoffStatement","nullable":true},"omissions":{"type":"array","maxItems":64,"items":{"$ref":"HandoffOmission"}}}}, + HandoffDisposition: {"type":"string","enum":["continuable","blocked","complete"]}, + HandoffDraft: {"type":"object","additionalProperties":false,"required":["objective","state","disposition","next_action","omissions"],"properties":{"generation":{"$ref":"HandoffGenerationEnvelope","nullable":true},"objective":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"state":{"type":"array","minItems":1,"maxItems":64,"items":{"$ref":"HandoffStatement"}},"disposition":{"$ref":"HandoffDisposition"},"next_action":{"$ref":"HandoffStatement","nullable":true},"omissions":{"type":"array","maxItems":64,"items":{"$ref":"HandoffOmission"}}}}, + HandoffGenerationEnvelope: {"type":"object","additionalProperties":false,"required":["receipt"],"properties":{"receipt":{"type":"string","minLength":1,"maxLength":8192}}}, + HandoffGenerationMetadata: {"type":"object","additionalProperties":false,"required":["scope_id","prompt_key","selection","artifact","definition_version","builtin_version","compiled_digest","original_draft_digest","edit_status"],"properties":{"scope_id":{"type":"string","minLength":1,"maxLength":256},"prompt_key":{"$ref":"HandoffPromptKey"},"selection":{"type":"string","enum":["built_in","artifact"]},"artifact":{"$ref":"ArtifactReference","nullable":true},"definition_version":{"type":"string","minLength":1,"maxLength":256},"builtin_version":{"type":"string","minLength":1,"maxLength":256},"compiled_digest":{"type":"string","pattern":"^[0-9a-f]{64}$"},"original_draft_digest":{"type":"string","pattern":"^[0-9a-f]{64}$"},"edit_status":{"type":"string","enum":["unchanged","edited"]}}}, + HandoffOmission: {"type":"object","additionalProperties":false,"required":["text","citation"],"properties":{"text":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"citation":{"$ref":"HandoffCitation","nullable":true}}}, + HandoffPromptKey: {"type":"string","enum":["handoff.generate"]}, + HandoffSchema: {"type":"string","enum":["powercontext.handoff.v1"]}, + HandoffSourceCitation: {"type":"object","additionalProperties":false,"required":["kind","source_ref"],"properties":{"kind":{"type":"string","enum":["source"]},"source_ref":{"$ref":"SourceReference"}}}, + HandoffStatement: {"type":"object","additionalProperties":false,"required":["text","citations"],"properties":{"text":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"citations":{"type":"array","minItems":1,"maxItems":32,"items":{"$ref":"HandoffCitation"}}}}, + PreparedHandoff: {"type":"object","additionalProperties":false,"required":["schema","scope_id","base","content"],"properties":{"generation":{"$ref":"HandoffGenerationEnvelope","nullable":true},"schema":{"$ref":"PreparedHandoffSchema"},"scope_id":{"type":"string"},"base":{"$ref":"ArtifactReference","nullable":true},"content":{"$ref":"HandoffContent"}}}, + PreparedHandoffSchema: {"type":"string","enum":["powercontext.prepared-handoff.v1"]}, + PreparedWorkHandoff: {"type":"object","additionalProperties":false,"required":["boundary","handoff"],"properties":{"boundary":{"$ref":"WorkSourceReceipt"},"handoff":{"$ref":"PreparedHandoff"}}}, + SourceLineRangeLocator: {"type":"object","additionalProperties":false,"required":["kind","start_line","end_line"],"x-powercontext-source-line-range":true,"properties":{"kind":{"type":"string","enum":["line_range"]},"start_line":{"type":"integer","minimum":1},"end_line":{"type":"integer","minimum":1},"heading_path":{"type":"string","nullable":true,"maxLength":1024}}}, + SourceLocator: {"oneOf":[{"$ref":"SourceSequenceLocator"},{"$ref":"SourceLineRangeLocator"}]}, + SourceReference: {"type":"object","additionalProperties":false,"required":["name","source_id"],"properties":{"name":{"type":"string"},"source_id":{"type":"string"},"locator":{"$ref":"SourceLocator","nullable":true}}}, + SourceSequenceLocator: {"type":"object","additionalProperties":false,"required":["kind","sequence"],"properties":{"kind":{"type":"string","enum":["sequence"]},"sequence":{"type":"integer","minimum":0}}}, + WorkClaim: {"type":"object","additionalProperties":false,"required":["text","basis","evidence"],"properties":{"text":{"type":"string","minLength":1,"maxLength":8192,"pattern":".*\\S.*"},"basis":{"$ref":"WorkClaimBasis"},"evidence":{"type":"array","maxItems":31,"items":{"$ref":"HandoffCitation"}}}}, + WorkClaimBasis: {"type":"string","enum":["declared","verified"]}, + WorkSourceKind: {"type":"string","enum":["work-contract","handoff-boundary","handoff-receipt","task-outcome"]}, + WorkSourceReceipt: {"type":"object","additionalProperties":false,"required":["kind","source","position","content_digest"],"properties":{"kind":{"$ref":"WorkSourceKind"},"source":{"$ref":"SourceReference"},"position":{"type":"integer","minimum":1},"content_digest":{"type":"string","minLength":71,"maxLength":71,"pattern":"^sha256:[0-9a-f]{64}$"}}}, +} as const diff --git a/integrations/dsh/plugins/powercontext/src/handoff/identity.ts b/integrations/dsh/plugins/powercontext/src/handoff/identity.ts new file mode 100644 index 0000000000..16889b582b --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/identity.ts @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ReceiptAttempt, VerifiedPreflight } from './contracts.ts' +import { boundary } from './materials.ts' +import { invalid, object, trimmed } from './wire.ts' + +export const deliveryIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +export const checksumPattern = /^[0-9a-f]{64}$/ + +export function verifiedBinding(value: unknown): VerifiedPreflight { + if (!object(value)) invalid() + const { preflightId, revision, source, targetId, targetVersion, adapterVersion, effectiveCwd, + serverIdentity, connectionRef, connectionGeneration, scopeId } = value + if (!trimmed(preflightId, 256) || typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 1 + || !object(source) || !trimmed(targetId, 256) || !trimmed(targetVersion, 256) || !trimmed(adapterVersion, 256) + || !trimmed(effectiveCwd, 4096) || effectiveCwd.includes('\0') || !trimmed(serverIdentity, 256) + || !trimmed(connectionRef, 256) || (typeof connectionGeneration !== 'number' || !Number.isSafeInteger(connectionGeneration) || connectionGeneration < 0) || !trimmed(scopeId, 256)) invalid() + // Pick only the shared contract. Never spread credentials or other Host-private fields to disk. + return Object.freeze({ preflightId, revision, + source: Object.freeze(boundary(source as unknown as VerifiedPreflight['source'])), + targetId, targetVersion, adapterVersion, effectiveCwd, serverIdentity, connectionRef, connectionGeneration, scopeId }) +} + +export function receiptIdentity(value: unknown): ReceiptAttempt { + if (!object(value) || typeof value.receiptAttemptId !== 'string' || !deliveryIdPattern.test(value.receiptAttemptId) + || value.sourceType !== 'content' || value.sourceId !== 'dsh-ack:' + value.receiptAttemptId) invalid() + return { receiptAttemptId: value.receiptAttemptId, sourceType: value.sourceType, sourceId: value.sourceId } +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/materials.ts b/integrations/dsh/plugins/powercontext/src/handoff/materials.ts new file mode 100644 index 0000000000..99ca1a92ba --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/materials.ts @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { CallContext, SourceBoundary } from './contracts.ts' +import { DeliveryError } from './contracts.ts' +import { hasSecretContent } from '../secrets.ts' +import { invalid, trimmed, wire } from './wire.ts' +import type { Wire } from './wire.ts' + +export const MAX_EVENTS = 512 +export const MAX_MATERIAL_BYTES = 256 * 1024 +export const MAX_WORKSPACE_BYTES = 32 * 1024 +export const MAX_WORK_INPUT_BYTES = 32 * 1024 + +type Citation = Wire<'HandoffCitation'> + +export type WorkEvent = { + sessionId: string + seq: number + observedAt?: string + evidence?: Citation[] +} & ( + | { kind: 'objective' | 'constraint' | 'completed' | 'next_action' | 'unresolved_error'; text: string } + | { kind: 'check'; command: string; status: 'passed' | 'failed' | 'interrupted' | 'not_run' | 'unknown'; + exitCode?: number; revision?: string; workspaceObservedAt?: string; details?: string } +) + +export interface BoundaryEvidence { + source: SourceBoundary + objective: string | null + selectedReply: { messageId: string; seq: number; text: string } + /** Recent or relevant evidence first. The reader must bound the underlying Host reads too. */ + events: Iterable | AsyncIterable + workspace: { observedAt: string; revision: string | null; uncommittedChanges: string | null } | null + omissions?: readonly string[] +} + +/** Reads trusted Host observations at this exact boundary, never a live/latest reply or workspace substitute. */ +export type BoundaryReader = ( + context: CallContext, source: SourceBoundary, limits: { maxEvents: number; maxBytes: number; maxWorkspaceBytes: number }, +) => Promise + +export function boundary(value: SourceBoundary): SourceBoundary { + if (!value || !trimmed(value.sessionId, 256) || !trimmed(value.messageId, 256) + || !Number.isSafeInteger(value.throughSeq) || value.throughSeq < 0 || !trimmed(value.cwd, 4096) + || value.cwd.includes('\0') || !trimmed(value.workspaceObservedAt, 64) + || !Number.isFinite(Date.parse(value.workspaceObservedAt))) invalid() + const { sessionId, messageId, throughSeq, cwd, workspaceObservedAt } = value + return { sessionId, messageId, throughSeq, cwd, workspaceObservedAt } +} + +export function sameBoundary(a: SourceBoundary, b: SourceBoundary): boolean { + return a.sessionId === b.sessionId && a.messageId === b.messageId && a.throughSeq === b.throughSeq + && a.cwd === b.cwd && a.workspaceObservedAt === b.workspaceObservedAt +} + +function secret(value: unknown): boolean { + return hasSecretContent('capture_content_source', value) +} + +export function inspectedWork(value: unknown): Wire<'CurrentWorkHandoff'> { + const work = wire('CurrentWorkHandoff', value) + if (!trimmed(work.objective, 8192) || !work.omissions.every(item => trimmed(item, 8192)) + || new Set(work.omissions).size !== work.omissions.length + || [ ...work.state, ...(work.next_action ? [work.next_action] : []) ].some(claim => + !trimmed(claim.text, 8192) || (claim.basis === 'verified') !== (claim.evidence.length > 0)) + || secret(work) || Buffer.byteLength(JSON.stringify(work)) > MAX_WORK_INPUT_BYTES) invalid() + return work +} + +async function* boundedEvents(events: BoundaryEvidence['events']) { + let remaining = MAX_EVENTS - 1 // The selected reply counts toward the bound. + for await (const event of events) { + yield event + if (--remaining === 0) return + } +} + +export async function collectMaterials(context: CallContext, source: SourceBoundary, read: BoundaryReader, limit: number) { + // The HTTP Source also has a 200,000-character limit. Reserve space for metadata and omissions. + const maxBytes = Math.min(limit, MAX_MATERIAL_BYTES, 192 * 1024) + const evidence = await read(context, source, { + maxEvents: MAX_EVENTS - 1, maxBytes, maxWorkspaceBytes: Math.min(maxBytes, MAX_WORKSPACE_BYTES), + }) + context.signal.throwIfAborted() + const { selectedReply, objective } = evidence + if (!sameBoundary(source, evidence.source) || selectedReply.messageId !== source.messageId + || !Number.isSafeInteger(selectedReply.seq) || selectedReply.seq < 0 || selectedReply.seq > source.throughSeq) { + throw new DeliveryError('binding_mismatch') + } + const omissions = new Set() + const note = (text: string) => { omissions.add(text) } + const available = (text: string | null, max: number) => typeof text === 'string' + && text.length <= max && !/[\uD800-\uDFFF]/u.test(text) && !secret(text) && Buffer.byteLength(text) <= max + if (!trimmed(objective, 8192) || !available(objective, Math.min(8192, maxBytes / 4))) { + return undefined // Editable work fields are required. Do not capture or guess an objective. + } + const reply = { messageId: selectedReply.messageId, seq: selectedReply.seq, + text: available(selectedReply.text, maxBytes / 3) ? selectedReply.text : null } + if (reply.text === null) note('The selected reply was unavailable within the content and input limits.') + let workspace = null + if (evidence.workspace?.observedAt === source.workspaceObservedAt) { + const { observedAt, revision, uncommittedChanges } = evidence.workspace + workspace = { observedAt, revision: available(revision, 256) ? revision : null, + uncommittedChanges: available(uncommittedChanges, Math.min(MAX_WORKSPACE_BYTES, maxBytes / 4)) ? uncommittedChanges : null } + if (Buffer.byteLength(JSON.stringify(workspace)) > MAX_WORKSPACE_BYTES) workspace.uncommittedChanges = null + if (workspace.revision === null || workspace.uncommittedChanges === null) note('Workspace revision or uncommitted changes were not available.') + } else { + note('The workspace observation at the selected time was not available.') + } + const events: WorkEvent[] = [] + const seen = new Set([selectedReply.seq]) + const content = { source, objective, selectedReply: reply, workspace, events, omissions: [] as string[] } + let remaining = maxBytes - Buffer.byteLength(JSON.stringify(content)) - 1024 + if (remaining < 0) return undefined + let count = 1 + let checksObserved = false + for await (const event of boundedEvents(evidence.events)) { + context.signal.throwIfAborted() + if (++count === MAX_EVENTS) note('The session evidence window reached the event limit.') + if (event.sessionId !== source.sessionId || !Number.isSafeInteger(event.seq) + || event.seq < 0 || event.seq > source.throughSeq) throw new DeliveryError('binding_mismatch') + if (seen.has(event.seq)) continue + seen.add(event.seq) + const { sessionId, seq, observedAt, evidence: refs, kind } = event + const base = { sessionId, seq, observedAt: trimmed(observedAt, 64) ? observedAt : undefined, + evidence: refs?.slice(0, 32).map(ref => wire('HandoffCitation', ref)) } + let item: WorkEvent + if (kind === 'check') { + checksObserved = true + const { command, status, details, exitCode, revision, workspaceObservedAt } = event + if (!available(command, 8192)) { + note('A check was observed but its command could not be included.') + continue + } + if (!['passed', 'failed', 'interrupted', 'not_run', 'unknown'].includes(status)) invalid() + item = { ...base, kind, command, status, + details: details && available(details, 8192) ? details : undefined, + revision: revision && available(revision, 256) ? revision : undefined, + workspaceObservedAt: trimmed(workspaceObservedAt, 64) ? workspaceObservedAt : undefined, + exitCode: Number.isSafeInteger(exitCode) ? exitCode : undefined } + if (details && item.details === undefined) note('Some check details could not be included.') + } else { + if (!available(event.text, 8192)) { + note('Some task evidence was omitted because of content or input limits.') + continue + } + item = { ...base, kind, text: event.text } + } + const bytes = Buffer.byteLength(JSON.stringify(item)) + 1 + if (secret(item) || bytes > remaining) { + note(kind === 'check' && item.kind === 'check' && item.status === 'failed' + ? 'At least one observed failure could not fit the input limits or contained sensitive material.' + : 'Some task evidence was omitted because of content or input limits.') + continue + } + remaining -= bytes + events.push(item) + } + if (!checksObserved) note('No check evidence was available; whether checks ran is unknown.') + if (workspace && events.some(event => event.kind === 'check' + && (event.revision && workspace.revision && event.revision !== workspace.revision + || event.workspaceObservedAt && event.workspaceObservedAt !== workspace.observedAt))) { + note('Some checks describe a different revision or workspace state from the selected observation.') + } + if (events.some(event => event.kind === 'check' && !event.revision && !event.workspaceObservedAt)) { + note('Some checks could not be tied to an exact workspace state.') + } + const hostOmissions = evidence.omissions ?? [] + const maxHostOmissions = 16 + let hostOmissionsTruncated = hostOmissions.length > maxHostOmissions + for (const text of hostOmissions.slice(0, maxHostOmissions)) { + const size = typeof text === 'string' ? Buffer.byteLength(JSON.stringify(text)) + 1 : 0 + if (available(text, 256) && size <= remaining) { + remaining -= size + note(text) + } else { + hostOmissionsTruncated = true + } + } + if (hostOmissionsTruncated) note('Additional omissions reported by the Host could not be included.') + content.omissions = [...omissions] + const serialized = JSON.stringify(content) + if (Buffer.byteLength(serialized) > maxBytes) invalid() + return { objective, serialized } +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/prepare.ts b/integrations/dsh/plugins/powercontext/src/handoff/prepare.ts new file mode 100644 index 0000000000..8a071083c3 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/prepare.ts @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { combineSignals } from '../client.ts' +import type { JsonObject, PowerContextClient } from '../client.ts' +import { RequestNotSentError, ServerResponseError } from '../errors.ts' +import { hasSecretContent } from '../secrets.ts' +import type { CallContext, PrepareDeliveryInput, VerifiedPreflight } from './contracts.ts' +import { DeliveryError } from './contracts.ts' +import { collectMaterials } from './materials.ts' +import type { BoundaryReader } from './materials.ts' +import { invalid, object, preparedDigest, wire } from './wire.ts' +import type { Wire } from './wire.ts' + +export type Carrier = + | { kind: 'prepared'; digest: string; prepared: Wire<'PreparedHandoff'>; + sourceReceipts: [Wire<'WorkSourceReceipt'> | Wire<'CaptureContentSourceResponse'>] } + | { kind: 'revision'; revision: Wire<'ArtifactReference'> } + +export interface PreparationConnection { + client: Pick + /** Opt in only when the trusted connection has a configured generation pipeline. */ + generation?: { maxInputBytes: number; maxOutputBytes?: number } +} + +/** Resolve the client for the exact saved binding. Never fall back to a default connection. */ +export type PreparationConnectionResolver = ( + context: CallContext, binding: VerifiedPreflight, +) => Promise + +export async function prepareCarrier( + context: CallContext, + binding: VerifiedPreflight, + input: Omit & { workInput?: Wire<'CurrentWorkHandoff'> }, + deliveryId: string, + resolve: PreparationConnectionResolver, + readBoundary: BoundaryReader | undefined, + markDispatched: () => void, +): Promise { + const { client, generation } = await resolve(context, binding) + const scope = binding.scopeId + const call = async (operation: string, payload: JsonObject, mayWrite = false, signal = context.signal) => { + signal.throwIfAborted() + if (hasSecretContent(operation, payload)) invalid() + if (mayWrite) markDispatched() + const result = await client.request(operation, { ...payload, scope_id: scope }, signal) + if (result.kind !== 'json') invalid() + return result.value + } + if (input.revision) { + const ref = input.revision + const result = await call('get_artifact_revision', ref) + if (!object(result) || result.scope_id !== scope || result.family !== ref.family + || result.artifact_id !== ref.artifact_id || result.revision !== ref.revision) invalid() + if (!object(result.content) || result.content.schema !== 'powercontext.handoff.v1') invalid() + return { kind: 'revision', revision: ref } + } + + const sourceId = 'dsh-delivery:' + deliveryId + if (input.workInput) { + const result = wire('PreparedWorkHandoff', await call('handoff_current_work', { + source_id: sourceId, handoff: input.workInput, + }, true)) + return validateCarrier({ kind: 'prepared', digest: preparedDigest(result.handoff), prepared: result.handoff, + sourceReceipts: [result.boundary] }, binding, deliveryId) + } + if (!generation || !readBoundary) return undefined + if (!Number.isSafeInteger(generation.maxInputBytes) || generation.maxInputBytes < 1024 + || (generation.maxOutputBytes !== undefined && (!Number.isSafeInteger(generation.maxOutputBytes) + || generation.maxOutputBytes < 512 || generation.maxOutputBytes > 32768))) { + throw new DeliveryError('integration_unavailable') + } + const materials = await collectMaterials(context, binding.source, readBoundary, generation.maxInputBytes) + if (!materials) return undefined + const receipt = wire('CaptureContentSourceResponse', await call('capture_content_source', { + source_id: sourceId, content: materials.serialized, metadata: { origin: 'dsh', kind: 'handoff-input' }, + }, true)) + if (receipt.source.name !== 'content' || receipt.source.source_id !== sourceId) invalid() + const draft = wire('HandoffDraft', await call('prepare_handoff', { + objective: materials.objective, + evidence: [{ kind: 'source', source_ref: receipt.source }], + max_bytes: generation.maxOutputBytes ?? 8000, + }, true, combineSignals([context.signal, AbortSignal.timeout(90_000)]))) + // Core validates and checks the draft's exact evidence on finalize. Keep the receipt and the + // draft unchanged; never send data returned by the model if it matches the plugin secret filter. + const prepared = wire('PreparedHandoff', await call('finalize_handoff', { draft }, true)) + return validateCarrier({ kind: 'prepared', digest: preparedDigest(prepared), prepared, + sourceReceipts: [receipt] }, binding, deliveryId) +} + +export function validateCarrier(value: unknown, binding: VerifiedPreflight, deliveryId: string): Carrier { + if (!object(value)) invalid() + if (value.kind === 'revision') { + const revision = wire('ArtifactReference', value.revision) + if (revision.family !== 'handoff') invalid() + return { kind: 'revision', revision } + } + if (value.kind !== 'prepared' || !Array.isArray(value.sourceReceipts) || value.sourceReceipts.length !== 1) invalid() + const prepared = wire('PreparedHandoff', value.prepared) + if (prepared.scope_id !== binding.scopeId || (prepared.base !== null && prepared.base.family !== 'handoff') + || (prepared.content.generation && prepared.content.generation.scope_id !== binding.scopeId)) { + throw new DeliveryError('binding_mismatch') + } + const digest = preparedDigest(prepared) + if (value.digest !== digest || hasSecretContent('commit_handoff', { handoff: prepared })) invalid() + const receipt = value.sourceReceipts[0] + if (!object(receipt)) invalid() + const actual = 'kind' in receipt ? wire('WorkSourceReceipt', receipt) : wire('CaptureContentSourceResponse', receipt) + if (('kind' in actual && actual.kind !== 'handoff-boundary') + || actual.source.name !== 'content' || actual.source.source_id !== 'dsh-delivery:' + deliveryId + || (actual.source.locator?.kind === 'sequence' && actual.source.locator.sequence !== actual.position)) invalid() + return { kind: 'prepared', digest, prepared, sourceReceipts: [actual] } +} + +export function knownPreparationFailure(error: unknown): DeliveryError | undefined { + if (error instanceof RequestNotSentError) return new DeliveryError('integration_unavailable') + if (error instanceof ServerResponseError && error.statusCode >= 400 && error.statusCode < 500 + && error.statusCode !== 408 && error.statusCode !== 499) { + if (error.statusCode === 404) return new DeliveryError('not_found') + return new DeliveryError([400, 409, 422].includes(error.statusCode) ? 'payload_invalid' : 'integration_unavailable') + } + return undefined +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/store.ts b/integrations/dsh/plugins/powercontext/src/handoff/store.ts new file mode 100644 index 0000000000..0658e20a00 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/store.ts @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { spawnSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { constants, closeSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, + realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs' +import type { Stats } from 'node:fs' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { DeliveryError, isDeliveryErrorCode } from './contracts.ts' +import type { DeliveryErrorCode, PreparationState, ReceiptAttempt, VerifiedPreflight } from './contracts.ts' +import { checksumPattern, deliveryIdPattern, receiptIdentity, verifiedBinding } from './identity.ts' +import { invalid, object, trimmed } from './wire.ts' + +export const DELIVERY_SCHEMA = 'powercontext.dsh-delivery.v1' +export const MAX_PACKAGE_BYTES = 1024 * 1024 + 32 * 1024 // Existing client response limit + envelope. +const MAX_RECORD_BYTES = 64 * 1024 +export const MAX_REQUEST_KEYS = 64 +const DARWIN_O_EXLOCK = 0x20 // ; not exported by Node. + +export interface StoredPackage { + sha256: string + bytes: number +} + +export interface DeliveryRecord { + schema: typeof DELIVERY_SCHEMA + deliveryId: string + ownerId: string + requests: { id: string; fingerprint: string }[] + binding: VerifiedPreflight + receiptAttempt: ReceiptAttempt + preparationState: PreparationState + createdAt: string + updatedAt: string + pinned: boolean + dispatched: boolean + error?: DeliveryErrorCode + supersedesDeliveryId?: string + package?: StoredPackage + expiredAt?: string + deletedAt?: string +} + +const states = new Set(['preparing', 'needs_input', 'prepared', 'failed', 'cancelled', 'unknown']) + +function date(value: unknown): value is string { + return typeof value === 'string' && Number.isFinite(Date.parse(value)) +} + +function decodeRecord(value: unknown, id: string): DeliveryRecord { + if (!object(value) || value.schema !== DELIVERY_SCHEMA || value.deliveryId !== id + || !trimmed(value.ownerId, 256) || typeof value.preparationState !== 'string' || !states.has(value.preparationState) + || !date(value.createdAt) || !date(value.updatedAt) || typeof value.pinned !== 'boolean' + || typeof value.dispatched !== 'boolean' || !Array.isArray(value.requests) + || value.requests.length < 1 || value.requests.length > MAX_REQUEST_KEYS + || value.requests.some(key => !object(key) || !trimmed(key.id, 128) + || typeof key.fingerprint !== 'string' || !checksumPattern.test(key.fingerprint)) + || (value.error !== undefined && !isDeliveryErrorCode(value.error)) + || (value.expiredAt !== undefined && !date(value.expiredAt)) + || (value.deletedAt !== undefined && !date(value.deletedAt)) + || (value.supersedesDeliveryId !== undefined && (typeof value.supersedesDeliveryId !== 'string' + || !deliveryIdPattern.test(value.supersedesDeliveryId)))) invalid() + if (value.package !== undefined && (!object(value.package) || typeof value.package.sha256 !== 'string' + || !checksumPattern.test(value.package.sha256) || typeof value.package.bytes !== 'number' + || !Number.isSafeInteger(value.package.bytes) || value.package.bytes < 1 || value.package.bytes > MAX_PACKAGE_BYTES)) invalid() + return { ...value, binding: verifiedBinding(value.binding), + receiptAttempt: receiptIdentity(value.receiptAttempt) } as unknown as DeliveryRecord +} + +function errno(error: unknown, code: string): boolean { + return object(error) && error.code === code +} + +function privateEntry(stat: Stats, directory: boolean): void { + if ((directory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1) + || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) invalid() +} + +/** + * The open directory descriptor holds the Host's exclusive lock until close or process exit. + * Every transaction is synchronous and runs to completion + * between awaits; each delivery's files are separate and normal requests never scan the disk. + */ +export class DeliveryStore { + readonly records = new Map() + private readonly root: string + private readonly rootStat: Stats + private rootFd: number | undefined + + constructor(directory: string) { + const darwin = process.platform === 'darwin' + if ((!darwin && process.platform !== 'linux') || !isAbsolute(directory) || !process.getuid || !constants.O_NOFOLLOW) { + throw new DeliveryError('integration_unavailable') + } + const path = resolve(directory) + this.root = join(realpathSync(dirname(path)), basename(path)) + try { + mkdirSync(this.root, { mode: 0o700 }) + } catch (error) { + if (!errno(error, 'EEXIST')) throw error + } + this.rootStat = lstatSync(this.root) + privateEntry(this.rootStat, true) + const fd = openSync(this.root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW + | constants.O_NONBLOCK | (darwin ? DARWIN_O_EXLOCK : 0)) + this.rootFd = fd + try { + const opened = fstatSync(fd) + privateEntry(opened, true) + if (opened.ino !== this.rootStat.ino || opened.dev !== this.rootStat.dev) invalid() + if (!darwin) { + // util-linux flock locks the inherited open file description, which we keep + // after the helper exits. It does not open or replace a separate lock file. + const lock = spawnSync('/usr/bin/flock', ['--nonblock', '3'], { + stdio: ['ignore', 'ignore', 'ignore', fd], env: { LANG: 'C' }, cwd: '/', timeout: 1000, + }) + if (lock.status !== 0) throw new DeliveryError('integration_unavailable') + } + this.checkRoot() + // Legacy PID markers are inert; only the kernel lock establishes ownership. + for (const name of readdirSync(this.root)) { + const id = name.slice(0, -'.record.json'.length) + if (name.endsWith('.record.json') && deliveryIdPattern.test(id)) { + const record = decodeRecord(JSON.parse(this.read(name, MAX_RECORD_BYTES).toString('utf8')), id) + this.records.set(id, record) + } else if (/^\.write-[0-9a-f-]{36}$/.test(name)) { + this.unlink(name) // An interrupted atomic write was never published. + } + } + } catch (error) { + this.close() + throw error + } + } + + private checkRoot(): number { + if (this.rootFd === undefined) throw new DeliveryError('integration_unavailable') + const stat = lstatSync(this.root) + privateEntry(stat, true) + if (stat.ino !== this.rootStat.ino || stat.dev !== this.rootStat.dev) invalid() + return this.rootFd + } + + private read(name: string, maximum: number): Buffer { + this.checkRoot() + const fd = openSync(join(this.root, name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) + try { + const stat = fstatSync(fd) + privateEntry(stat, false) + if (stat.size <= 0 || stat.size > maximum) invalid() + const bytes = Buffer.alloc(stat.size) + let offset = 0 + while (offset < bytes.length) { + const size = readSync(fd, bytes, offset, bytes.length - offset, null) + if (!size) invalid() + offset += size + } + if (readSync(fd, Buffer.alloc(1), 0, 1, null) !== 0) invalid() + return bytes + } finally { + closeSync(fd) + } + } + + private syncDirectory(): void { + fsyncSync(this.checkRoot()) + } + + private unlink(name: string): void { + this.checkRoot() + try { + unlinkSync(join(this.root, name)) + } catch (error) { + if (!errno(error, 'ENOENT')) throw error + } + } + + private write(name: string, value: Buffer, replace: boolean): void { + this.checkRoot() + const path = join(this.root, name) + try { + const old = lstatSync(path) + if (!replace) invalid() + privateEntry(old, false) + } catch (error) { + if (!errno(error, 'ENOENT')) throw error + } + const temporary = '.write-' + randomUUID() + const fd = openSync(join(this.root, temporary), 'wx', 0o600) + try { + try { + writeFileSync(fd, value) + fsyncSync(fd) + } finally { + closeSync(fd) + } + renameSync(join(this.root, temporary), path) + this.syncDirectory() + } finally { + this.unlink(temporary) + } + } + + put(record: DeliveryRecord): DeliveryRecord { + const bytes = Buffer.from(JSON.stringify(record)) + if (bytes.length > MAX_RECORD_BYTES) throw new DeliveryError('capacity_exceeded') + this.write(record.deliveryId + '.record.json', bytes, this.records.has(record.deliveryId)) + this.records.set(record.deliveryId, record) + return record + } + + packagePath(id: string): string { + return join(this.root, id + '.package.json') + } + + readPackage(id: string): Buffer { + return this.read(id + '.package.json', MAX_PACKAGE_BYTES) + } + + writePackage(id: string, bytes: Buffer): void { + if (bytes.length > MAX_PACKAGE_BYTES) invalid() + this.write(id + '.package.json', bytes, false) + } + + removePackage(id: string): void { + this.unlink(id + '.package.json') + this.syncDirectory() + } + + forget(id: string): void { + this.removePackage(id) + this.unlink(id + '.record.json') + this.syncDirectory() + this.records.delete(id) + } + + close(): void { + const fd = this.rootFd + this.rootFd = undefined + if (fd !== undefined) closeSync(fd) + } +} diff --git a/integrations/dsh/plugins/powercontext/src/handoff/wire.ts b/integrations/dsh/plugins/powercontext/src/handoff/wire.ts new file mode 100644 index 0000000000..6ae2dd2696 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/handoff/wire.ts @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createHash } from 'node:crypto' +import { HANDOFF_HTTP_SCHEMAS } from './http.generated.ts' +import { DeliveryError } from './contracts.ts' + +type Schemas = typeof HANDOFF_HTTP_SCHEMAS +type SchemaName = keyof Schemas +type Shape = { [K in keyof P as K extends R ? K : never]: Value } + & { [K in keyof P as K extends R ? never : K]?: Value } +type Value = S extends { nullable: true } ? NonNull | null : NonNull +type NonNull = + S extends { $ref: infer K extends SchemaName } ? Wire + : S extends { enum: readonly (infer E)[] } ? E + : S extends { oneOf: readonly (infer O)[] } ? Value + : S extends { type: 'object'; properties: infer P; required: readonly (infer R)[] } ? Shape + : S extends { type: 'array'; items: infer I } ? Value[] + : S extends { type: 'string' } ? string + : S extends { type: 'integer' } ? number + : never + +export type Wire = Value + +type Schema = { + $ref?: SchemaName + type?: 'object' | 'array' | 'string' | 'integer' + nullable?: boolean + enum?: readonly string[] + oneOf?: readonly Schema[] + properties?: Record + required?: readonly string[] + items?: Schema + minLength?: number + maxLength?: number + minItems?: number + maxItems?: number + minimum?: number + pattern?: string + 'x-powercontext-source-line-range'?: boolean +} + +export function object(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +export function invalid(): never { + throw new DeliveryError('payload_invalid') +} + +export function trimmed(value: unknown, max: number): value is string { + return typeof value === 'string' && value.length > 0 && value === value.trim() + && [...value].length <= max && !/[\uD800-\uDFFF]/u.test(value) +} + +function project(schema: Schema, value: unknown, core = false, name?: SchemaName): unknown { + if (value === null && schema.nullable) return null + if (schema.$ref) return project(HANDOFF_HTTP_SCHEMAS[schema.$ref], value, core, schema.$ref) + if (schema.oneOf) { + for (const option of schema.oneOf) { + try { + return project(option, value, core) + } catch (error) { + if (!(error instanceof DeliveryError)) throw error + } + } + return invalid() + } + if (schema.type === 'object') { + const properties = schema.properties! + const required = schema.required! + if (!object(value) || Object.keys(value).some(key => !Object.hasOwn(properties, key)) + || required.some(key => !Object.hasOwn(value, key))) invalid() + const entries = [] + for (const [key, field] of Object.entries(properties)) { + if (!Object.hasOwn(value, key)) continue + const child = project(field, value[key], core) + // Core omits null generation, Source locator and line heading (Pydantic exclude_if). + if (core && child === null && !required.includes(key)) continue + entries.push([core && name === 'SourceReference' && key === 'name' ? 'source_type' : key, child]) + } + if (schema['x-powercontext-source-line-range']) { + const lines = Number(value.end_line) - Number(value.start_line) + 1 + if (lines < 1 || lines > 200) invalid() + } + if (name === 'SourceReference' && (!trimmed(value.name, 256) || !trimmed(value.source_id, 256))) invalid() + return Object.fromEntries(entries) + } + if (schema.type === 'array') { + if (!Array.isArray(value) || value.length < (schema.minItems ?? 0) + || value.length > (schema.maxItems ?? Infinity)) invalid() + return Array.from(value, item => project(schema.items!, item, core)) + } + if (schema.type === 'integer') { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < (schema.minimum ?? 0)) invalid() + return value + } + if (typeof value !== 'string' || /[\uD800-\uDFFF]/u.test(value)) invalid() + if (schema.maxLength !== undefined && [...value].length > schema.maxLength) invalid() + if (schema.minLength !== undefined && [...value].length < schema.minLength) invalid() + if (schema.pattern && !new RegExp(schema.pattern, 'u').test(value)) invalid() + if (schema.enum && !schema.enum.includes(value)) invalid() + return value +} + +export function wire(name: K, value: unknown): Wire { + return project(HANDOFF_HTTP_SCHEMAS[name], value, false, name) as Wire +} + +export function sha256(value: string | Uint8Array): string { + return createHash('sha256').update(value).digest('hex') +} + +export function preparedDigest(value: Wire<'PreparedHandoff'>): string { + // Core's work.content_digest is model-order JSON, not sorted keys / JCS. + const core = project(HANDOFF_HTTP_SCHEMAS.PreparedHandoff, value, true, 'PreparedHandoff') + return 'sha256:' + sha256(JSON.stringify(core)) +} diff --git a/integrations/dsh/plugins/powercontext/tests/e2e/handoff-delivery.spec.ts b/integrations/dsh/plugins/powercontext/tests/e2e/handoff-delivery.spec.ts new file mode 100644 index 0000000000..94c679bd0f --- /dev/null +++ b/integrations/dsh/plugins/powercontext/tests/e2e/handoff-delivery.spec.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { PowerContextClient } from '../../src/client.ts' +import { LocalDeliveryService } from '../../src/handoff/delivery.ts' +import type { SourceBoundary } from '../../src/handoff/contracts.ts' +import { wire } from '../../src/handoff/wire.ts' +import { startPowerContextServer } from '../../scripts/e2e-server.mjs' + +it('round trips a complete current-work Handoff and a selected exact Revision through the real Server', async () => { + const server = await startPowerContextServer({ env: { POWERCONTEXT_SERVER_ACCESS_MODE: 'disabled' } }) + const parent = mkdtempSync(join(tmpdir(), 'dsh-handoff-http-')) + let service: LocalDeliveryService | undefined + try { + const client = new PowerContextClient({ baseUrl: server.baseUrl, requestTimeoutMs: 5000 }) + const defaultScope = await client.request('get_default_scope') + expect(defaultScope.kind).toBe('json') + if (defaultScope.kind !== 'json') throw new Error('missing default scope') + const { scope_id: scopeId } = defaultScope.value as { scope_id: string } + const source: SourceBoundary = { + sessionId: 'http-fixture', messageId: 'reply-3', throughSeq: 12, cwd: parent, + workspaceObservedAt: new Date().toISOString(), + } + const context = { ownerId: 'http-owner', signal: new AbortController().signal } + const input = { requestId: 'http-prepare', source, preflightId: 'http-preflight', expectedRevision: 1 } + service = new LocalDeliveryService({ + directory: join(parent, 'deliveries'), + preflightGate: { validateForPrepare: async (_ctx, selected) => ({ + source: selected.source, preflightId: selected.preflightId, revision: selected.expectedRevision, + targetId: 'fixture', targetVersion: 'fixture', adapterVersion: 'fixture', + effectiveCwd: parent, scopeId, serverIdentity: 'test-server', connectionRef: 'fixture', connectionGeneration: 1, + }) }, + resolveConnection: async () => ({ client }), + }) + + const ready = await service.prepare(context, { ...input, workInput: { + schema: 'powercontext.current-work-handoff.v1', trust: 'untrusted_input', + objective: '交接真实 HTTP 回包 😀', + state: [{ basis: 'declared', text: 'The fixture checked the public Work endpoint.', evidence: [] }], + disposition: 'blocked', next_action: null, omissions: ['Host launch was not exercised.'], + } }) + expect(ready).toMatchObject({ preparationState: 'prepared', preview: { objective: '交接真实 HTTP 回包 😀' } }) + const first = await service.getForLaunch(context, ready.deliveryId) + expect(first.handoffSelection).toMatchObject({ kind: 'prepared', digest: expect.stringMatching(/^sha256:/) }) + const { bytes } = await service.exportPackage(context, ready.deliveryId) + const { carrier } = JSON.parse(Buffer.from(bytes).toString()) + expect(carrier.sourceReceipts).toEqual([expect.objectContaining({ kind: 'handoff-boundary', + source: expect.objectContaining({ name: 'content', source_id: 'dsh-delivery:' + ready.deliveryId }), + })]) + const result = await client.request('continue_handoff', { scope_id: scopeId, selection: 'prepared', prepared: carrier.prepared }) + expect(result).toMatchObject({ kind: 'json', value: { status: 'resolved', selection: 'prepared' } }) + + // Set up a milestone explicitly as test data. The delivery service never commits one. + const commit = await client.request('commit_handoff', { scope_id: scopeId, handoff: carrier.prepared }) + if (commit.kind !== 'json') throw new Error('expected committed Handoff') + const revision = wire('ArtifactReference', (commit.value as { reference: unknown }).reference) + const selected = await service.prepare(context, { ...input, requestId: 'http-exact', revision, + supersedesDeliveryId: ready.deliveryId }) + expect(selected.preparationState).toBe('prepared') + expect((await service.getForLaunch(context, selected.deliveryId)).handoffSelection) + .toEqual({ kind: 'revision', revision: { scope_id: scopeId, ...revision } }) + } finally { + try { + await service?.close() + await server.stop() + } finally { + rmSync(parent, { recursive: true, force: true }) + rmSync(server.home, { recursive: true, force: true }) + } + } +}, 60_000) diff --git a/integrations/dsh/plugins/powercontext/tests/fixtures/handoff-digests.json b/integrations/dsh/plugins/powercontext/tests/fixtures/handoff-digests.json new file mode 100644 index 0000000000..d7269c79dc --- /dev/null +++ b/integrations/dsh/plugins/powercontext/tests/fixtures/handoff-digests.json @@ -0,0 +1,194 @@ +[ + { + "wire": { + "content": { + "omissions": [ + { + "citation": null, + "text": "工具结果未捕获。" + } + ], + "next_action": null, + "disposition": "blocked", + "state": [ + { + "citations": [ + { + "source_ref": { + "locator": null, + "source_id": "会话 😀", + "name": "content" + }, + "kind": "source" + } + ], + "text": "检查结果:中断;Café\n下一行\t\\\"" + } + ], + "objective": "跨 Agent 交接 😀", + "schema": "powercontext.handoff.v1", + "generation": null + }, + "scope_id": "项目", + "base": null, + "generation": null, + "schema": "powercontext.prepared-handoff.v1" + }, + "digest": "sha256:50844e2950af053d0bba58da7ebd151e3e2236cd4662410381ffe51480b7cf9c" + }, + { + "wire": { + "content": { + "omissions": [ + { + "citation": null, + "text": "工具结果未捕获。" + } + ], + "next_action": { + "citations": [ + { + "source_ref": { + "locator": null, + "source_id": "会话 😀", + "name": "content" + }, + "kind": "source" + }, + { + "kind": "source", + "source_ref": { + "name": "content", + "source_id": "零", + "locator": { + "kind": "sequence", + "sequence": 0 + } + } + }, + { + "kind": "source", + "source_ref": { + "name": "file", + "source_id": "行号", + "locator": { + "kind": "line_range", + "start_line": 1, + "end_line": 2, + "heading_path": null + } + } + }, + { + "kind": "source", + "source_ref": { + "name": "file", + "source_id": "标题", + "locator": { + "kind": "line_range", + "start_line": 8, + "end_line": 8, + "heading_path": "章节 😀" + } + } + }, + { + "kind": "artifact", + "artifact_ref": { + "revision": 2, + "artifact_id": "ref", + "family": "experience" + } + } + ], + "text": "检查结果:中断;Café\n下一行\t\\\"" + }, + "disposition": "blocked", + "state": [ + { + "citations": [ + { + "source_ref": { + "locator": null, + "source_id": "会话 😀", + "name": "content" + }, + "kind": "source" + }, + { + "kind": "source", + "source_ref": { + "name": "content", + "source_id": "零", + "locator": { + "kind": "sequence", + "sequence": 0 + } + } + }, + { + "kind": "source", + "source_ref": { + "name": "file", + "source_id": "行号", + "locator": { + "kind": "line_range", + "start_line": 1, + "end_line": 2, + "heading_path": null + } + } + }, + { + "kind": "source", + "source_ref": { + "name": "file", + "source_id": "标题", + "locator": { + "kind": "line_range", + "start_line": 8, + "end_line": 8, + "heading_path": "章节 😀" + } + } + }, + { + "kind": "artifact", + "artifact_ref": { + "revision": 2, + "artifact_id": "ref", + "family": "experience" + } + } + ], + "text": "检查结果:中断;Café\n下一行\t\\\"" + } + ], + "objective": "跨 Agent 交接 😀", + "schema": "powercontext.handoff.v1", + "generation": { + "edit_status": "unchanged", + "original_draft_digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "compiled_digest": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "builtin_version": "1", + "definition_version": "1", + "artifact": null, + "selection": "built_in", + "prompt_key": "handoff.generate", + "scope_id": "项目" + } + }, + "scope_id": "项目", + "base": { + "revision": 3, + "artifact_id": "current", + "family": "handoff" + }, + "generation": { + "receipt": "test-generation.receipt" + }, + "schema": "powercontext.prepared-handoff.v1" + }, + "digest": "sha256:abab96e7dd8e96d2821be7afacc7276bd6782bb80fd32c943ae05de52611d89d" + } +] diff --git a/integrations/dsh/plugins/powercontext/tests/handoff-delivery.spec.ts b/integrations/dsh/plugins/powercontext/tests/handoff-delivery.spec.ts new file mode 100644 index 0000000000..0e7b73768e --- /dev/null +++ b/integrations/dsh/plugins/powercontext/tests/handoff-delivery.spec.ts @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { spawn } from 'node:child_process' +import { once } from 'node:events' +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { PowerContextClient } from '../src/client.ts' +import type { CallContext, PrepareDeliveryInput, SourceBoundary, VerifiedPreflight } from '../src/handoff/contracts.ts' +import { LocalDeliveryService } from '../src/handoff/delivery.ts' +import type { DeliveryOptions } from '../src/handoff/delivery.ts' +import type { BoundaryReader, WorkEvent } from '../src/handoff/materials.ts' +import { preparedDigest, sha256, wire } from '../src/handoff/wire.ts' +import type { Wire } from '../src/handoff/wire.ts' + +const work: Wire<'CurrentWorkHandoff'> = { + schema: 'powercontext.current-work-handoff.v1', trust: 'untrusted_input', + objective: '修复回归 😀', + state: [{ text: 'The check failed on the selected revision.', basis: 'declared', evidence: [] }], + disposition: 'continuable', + next_action: { text: 'Inspect the failing assertion.', basis: 'declared', evidence: [] }, + omissions: ['Exit status unavailable'], +} + +const source: SourceBoundary = { + sessionId: 'session-a', messageId: 'reply-1', throughSeq: 1000, cwd: '/source/worktree', + workspaceObservedAt: '2026-11-12T03:24:00.000Z', +} + +function bindingFor(selected: SourceBoundary, preflightId = 'preflight-a', revision = 1): VerifiedPreflight { + return { preflightId, revision, source: selected, targetId: 'codex', targetVersion: '1', + adapterVersion: '1', effectiveCwd: selected.cwd, serverIdentity: 'local-server', connectionRef: 'profile-a', + connectionGeneration: 2, scopeId: 'scope-a' } +} + +function input(overrides: Partial = {}): PrepareDeliveryInput { + return { source, preflightId: 'preflight-a', expectedRevision: 1, requestId: 'req-1', workInput: work, ...overrides } +} + +const caller = (ownerId = 'owner-a', signal = new AbortController().signal): CallContext => ({ ownerId, signal }) + +function response(value: unknown, status = 200) { + return Response.json(value, { status }) +} + +function statement(text: string, ref: Wire<'SourceReference'>) { + return { text, citations: [{ kind: 'source', source_ref: ref }] } +} + +function responseForCurrent(body: { source_id: string; scope_id: string; handoff: typeof work }) { + const source = { name: 'content', source_id: body.source_id, locator: { kind: 'sequence', sequence: 2 } } + return { + boundary: { kind: 'handoff-boundary', source, position: 2, content_digest: 'sha256:' + 'a'.repeat(64) }, + handoff: { + schema: 'powercontext.prepared-handoff.v1', scope_id: body.scope_id, base: null, generation: null, + content: { + generation: null, schema: 'powercontext.handoff.v1', objective: body.handoff.objective, + state: body.handoff.state.map(claim => statement(claim.text, wire('SourceReference', source))), + disposition: body.handoff.disposition, + next_action: null, omissions: body.handoff.omissions.map(text => ({ text, citation: null })), + }, + }, + } +} + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +describe('local DSH handoff deliveries', () => { + let parent: string + let directory: string + let service: LocalDeliveryService + const gate = { validateForPrepare: vi.fn(async ( + _ctx: CallContext, { source, preflightId, expectedRevision }: Pick, + ) => bindingFor(source, preflightId, expectedRevision)) } + const fetch = vi.fn(async (url: string, request: RequestInit) => { + expect(url.endsWith('/v1/work/handoffs/prepare-current')).toBe(true) + return response(responseForCurrent(JSON.parse(request.body as string))) + }) + const client = new PowerContextClient({ baseUrl: 'http://127.0.0.1:9000', requestTimeoutMs: 5000, fetch }) + const resolveConnection = vi.fn(async () => ({ client })) + + function open(overrides: Partial = {}) { + service = new LocalDeliveryService({ directory, preflightGate: gate, resolveConnection, ...overrides }) + return service + } + + beforeEach(() => { + parent = mkdtempSync(join(tmpdir(), 'dsh-delivery-')) + directory = join(parent, 'deliveries') + gate.validateForPrepare.mockClear() + fetch.mockClear() + resolveConnection.mockClear() + }) + + afterEach(async () => { + try { + await service?.close() + } finally { + rmSync(parent, { recursive: true, force: true }) + } + }) + + it.each(['not_ready', 'stale_preflight', 'binding_mismatch', 'not_found'] as const)( + 'does no capture or generation when the gate rejects with %s', async code => { + open() + gate.validateForPrepare.mockRejectedValueOnce(Object.assign(new Error('private remote message'), { code })) + await expect(service.prepare(caller(), input())).rejects.toMatchObject({ code }) + expect(resolveConnection).not.toHaveBeenCalled() + expect(fetch).not.toHaveBeenCalled() + expect(readdirSync(directory).filter(name => !name.startsWith('.'))).toEqual([]) + }, + ) + + it('fails closed without a gate and rejects a substituted reply or revision', async () => { + open({ preflightGate: undefined }) + await expect(service.prepare(caller(), input())).rejects.toMatchObject({ code: 'integration_unavailable' }) + await service.close() + open() + gate.validateForPrepare.mockResolvedValueOnce(bindingFor({ ...source, messageId: 'latest' })) + await expect(service.prepare(caller(), input())).rejects.toMatchObject({ code: 'binding_mismatch' }) + gate.validateForPrepare.mockResolvedValueOnce(bindingFor(source, 'preflight-a', 2)) + await expect(service.prepare(caller(), input())).rejects.toMatchObject({ code: 'stale_preflight' }) + expect(fetch).not.toHaveBeenCalled() + }) + + it('rejects input identity overrides, false evidence and over-budget work before dispatch', async () => { + open() + for (const workInput of [ + { ...work, scope_id: 'other' }, + { ...work, state: [{ text: 'Unsupported claim', basis: 'verified', evidence: [] }] }, + { ...work, omissions: Array.from({ length: 64 }, (_, i) => '😀'.repeat(200) + i) }, + ]) { + await expect(service.prepare(caller(), input({ workInput }))).rejects.toMatchObject({ code: 'payload_invalid' }) + } + expect(fetch).not.toHaveBeenCalled() + }) + + it('persists the entire result, reopens without remote work, and keeps the ACK identity', async () => { + open() + expect(() => open()).toThrowError(expect.objectContaining({ code: 'integration_unavailable' })) + const owner = caller() + const prepared = await service.prepare(owner, input()) + expect(prepared).toMatchObject({ preparationState: 'prepared', source, + preview: { objective: work.objective, omissionCount: 1 }, receiptAttempt: { sourceType: 'content' } }) + const first = await service.getForLaunch(owner, prepared.deliveryId) + const exported = await service.exportPackage(owner, prepared.deliveryId) + const contents = JSON.parse(Buffer.from(exported.bytes).toString()) + expect(contents).toMatchObject({ + source, binding: bindingFor(source), carrier: { kind: 'prepared', sourceReceipts: [{ + kind: 'handoff-boundary', source: { name: 'content', source_id: 'dsh-delivery:' + prepared.deliveryId }, position: 2, + }], prepared: { base: null, generation: null, content: { next_action: null, generation: null } } }, + }) + expect(first.packageSha256).toBe(sha256(exported.bytes)) + expect(first.handoffSelection).toEqual({ kind: 'prepared', digest: contents.carrier.digest }) + expect(contents.carrier.digest).not.toBe('sha256:' + first.packageSha256) + expect(statSync(first.packagePath).mode & 0o777).toBe(0o600) + expect(statSync(directory).mode & 0o777).toBe(0o700) + await service.close() + open() + expect(await service.getForLaunch(owner, prepared.deliveryId)).toEqual(first) + expect(await service.prepare(owner, input())).toMatchObject({ deliveryId: prepared.deliveryId }) + expect(await service.cancelPreparation(owner, prepared.deliveryId)).toMatchObject({ preparationState: 'prepared' }) + expect(await service.exportPackage(owner, prepared.deliveryId)).toEqual(exported) + expect(fetch).toHaveBeenCalledTimes(1) + await expect(service.getForLaunch(caller('other'), prepared.deliveryId)).rejects.toMatchObject({ code: 'not_found' }) + await expect(service.cancelPreparation(caller('other'), prepared.deliveryId)).rejects.toMatchObject({ code: 'not_found' }) + await expect(service.exportPackage(caller('other'), prepared.deliveryId)).rejects.toMatchObject({ code: 'not_found' }) + }) + + it('recovers the verified original package if the Host stopped before publishing prepared', async () => { + open() + const owner = caller() + const ready = await service.prepare(owner, input()) + const first = await service.getForLaunch(owner, ready.deliveryId) + await service.close() + + // The durable file and its checksum exist, but the last metadata transition did not happen. + const path = join(directory, ready.deliveryId + '.record.json') + const staged = JSON.parse(readFileSync(path, 'utf8')) + writeFileSync(path, JSON.stringify({ ...staged, preparationState: 'preparing' })) + open() + expect(await service.getForLaunch(owner, ready.deliveryId)).toEqual(first) + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('isolates sessions and reply boundaries in the same Scope', async () => { + open() + const owner = caller() + const selections = [source, { ...source, sessionId: 'session-b' }, { ...source, messageId: 'reply-2', throughSeq: 1020 }] + const views = await Promise.all(selections.map((source, i) => + service.prepare(owner, input({ source, requestId: 'request-' + i })))) + expect(new Set(views.map(view => view.deliveryId)).size).toBe(3) + expect(new Set(views.map(view => view.receiptAttempt.sourceId)).size).toBe(3) + for (const [i, view] of views.entries()) { + expect(await service.getForLaunch(owner, view.deliveryId)).toMatchObject({ + source: selections[i], binding: { scopeId: 'scope-a' }, + }) + } + }) + + it('deduplicates concurrent requests and persists an alias for each request key', async () => { + open() + const entered = deferred() + const release = deferred() + fetch.mockImplementationOnce(async (_url, init) => { + entered.resolve() + await release.promise + return response(responseForCurrent(JSON.parse(init.body as string))) + }) + const owner = caller() + const first = service.prepare(owner, input()) + await entered.promise + try { + const same = await service.prepare(owner, input()) + const alias = await service.prepare(owner, input({ requestId: 'alias' })) + expect(same).toMatchObject({ deliveryId: alias.deliveryId, preparationState: 'preparing' }) + await expect(service.getForLaunch(owner, same.deliveryId)).rejects.toMatchObject({ code: 'not_ready' }) + await expect(service.prepare(owner, input({ requestId: 'alias', workInput: undefined }))) + .rejects.toMatchObject({ code: 'idempotency_conflict' }) + } finally { + release.resolve() + } + const view = await first + await service.close() + open() + expect(await service.prepare(owner, input({ requestId: 'alias' }))).toMatchObject({ deliveryId: view.deliveryId }) + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('preserves an unknown result and only reruns for an explicit new version', async () => { + open() + fetch.mockRejectedValueOnce(new Error('connection lost after dispatch')) + const owner = caller() + const unknown = await service.prepare(owner, input()) + expect(unknown).toMatchObject({ preparationState: 'unknown', error: { code: 'outcome_unknown' } }) + await service.close() + open() + expect(await service.prepare(owner, input({ requestId: 'retry' }))).toMatchObject({ + deliveryId: unknown.deliveryId, preparationState: 'unknown', receiptAttempt: unknown.receiptAttempt, + }) + await expect(service.prepare(owner, input({ requestId: 'different-preflight', preflightId: 'preflight-b' }))) + .rejects.toMatchObject({ code: 'outcome_unknown' }) + expect(fetch).toHaveBeenCalledTimes(1) + const replacement = await service.prepare(owner, input({ requestId: 'new', supersedesDeliveryId: unknown.deliveryId })) + expect(replacement).toMatchObject({ preparationState: 'prepared' }) + expect(replacement.receiptAttempt.sourceId).not.toBe(unknown.receiptAttempt.sourceId) + expect(await service.get(owner, unknown.deliveryId)).toMatchObject({ preparationState: 'unknown' }) + }) + + it.skipIf(Number(process.versions.node.split('.')[0]) < 22).each([ + ['the new Host', process.pid], ['an unrelated live process', process.ppid], + ])('recovers after a crash when a legacy marker names %s', async (_process, reusedPid) => { + const url = new URL('../src/handoff/delivery.ts', import.meta.url).href + const script = ` + import { LocalDeliveryService } from ${JSON.stringify(url)} + const binding = ${JSON.stringify(bindingFor(source))} + const service = new LocalDeliveryService({ + directory: process.argv[1], + preflightGate: { validateForPrepare: async () => binding }, + resolveConnection: async () => ({ client: { + request() { + process.stdout.write('dispatched') + return new Promise(() => setInterval(() => {}, 1000)) + }, + } }), + }) + await service.prepare( + { ownerId: 'owner-a', signal: new AbortController().signal }, + ${JSON.stringify(input())}, + ) + ` + const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '--experimental-strip-types', '--input-type=module', '-e', script, directory], + { stdio: ['ignore', 'pipe', 'pipe'] }) + const exited = once(child, 'exit') + try { + const event = await Promise.race([ + once(child.stdout, 'data').then(([data]) => String(data)), + once(child.stderr, 'data').then(([data]) => String(data)), + exited.then(([code]) => 'exited: ' + code), + ]) + expect(event).toBe('dispatched') + expect(() => open()).toThrowError(expect.objectContaining({ code: 'integration_unavailable' })) + } finally { + child.kill('SIGKILL') + await exited + } + + // Simulate PID reuse without relying on the kernel to recycle the child PID. + writeFileSync(join(directory, '.host-' + reusedPid), '', { mode: 0o600 }) + open() + const owner = caller() + const [view] = await service.list(owner) + expect(view).toMatchObject({ preparationState: 'unknown', error: { code: 'outcome_unknown' } }) + expect(await service.prepare(owner, input())).toMatchObject({ + deliveryId: view.deliveryId, receiptAttempt: view.receiptAttempt, preparationState: 'unknown', + }) + await expect(service.getForLaunch(owner, view.deliveryId)).rejects.toMatchObject({ code: 'outcome_unknown' }) + expect(fetch).not.toHaveBeenCalled() + }) + + it('distinguishes missing input and a definitive rejection from an unknown result', async () => { + open() + const owner = caller() + const needsInput = await service.prepare(owner, input({ workInput: undefined })) + expect(needsInput).toMatchObject({ preparationState: 'needs_input', recoveryActions: ['supply_work_input', 'create_new_version'] }) + expect(fetch).not.toHaveBeenCalled() + fetch.mockResolvedValueOnce(response({ error: { message: 'raw Server text' } }, 422)) + const failed = await service.prepare(owner, input({ requestId: 'fixed', supersedesDeliveryId: needsInput.deliveryId })) + expect(failed).toMatchObject({ preparationState: 'failed', error: { code: 'payload_invalid' } }) + expect(failed.error?.message).not.toContain('raw Server text') + }) + + it('cancels before dispatch without a write and treats an interrupted dispatch as unknown', async () => { + const entered = deferred() + const release = deferred() + open({ resolveConnection: async () => { + entered.resolve() + await release.promise + return { client } + } }) + const owner = caller() + const first = service.prepare(owner, input()) + await entered.promise + try { + const [preparing] = await service.list(owner) + expect(await service.cancelPreparation(owner, preparing.deliveryId)).toMatchObject({ preparationState: 'cancelled' }) + } finally { + release.resolve() + } + expect(await first).toMatchObject({ preparationState: 'cancelled' }) + expect(fetch).not.toHaveBeenCalled() + const dispatched = deferred() + fetch.mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { + init.signal!.addEventListener('abort', () => reject(init.signal!.reason), { once: true }) + dispatched.resolve() + })) + const second = service.prepare(owner, input({ requestId: 'new' })) + await dispatched.promise + const pending = await service.prepare(owner, input({ requestId: 'new' })) + expect(await service.cancelPreparation(owner, pending.deliveryId)).toMatchObject({ preparationState: 'unknown' }) + expect(await second).toMatchObject({ preparationState: 'unknown' }) + }) + + it.each(['bytes', 'missing', 'symlink'])('refuses launch and export if the saved file is %s', async damage => { + open() + const owner = caller() + const ready = await service.prepare(owner, input()) + const bundle = await service.getForLaunch(owner, ready.deliveryId) + const bytes = readFileSync(bundle.packagePath) + rmSync(bundle.packagePath) + if (damage === 'bytes') writeFileSync(bundle.packagePath, Buffer.concat([bytes, Buffer.from(' ')]), { mode: 0o600 }) + if (damage === 'symlink') { + const outside = join(parent, 'outside') + writeFileSync(outside, bytes, { mode: 0o600 }) + symlinkSync(outside, bundle.packagePath) + } + await expect(service.getForLaunch(owner, ready.deliveryId)).rejects.toMatchObject({ code: 'outcome_unknown' }) + await expect(service.exportPackage(owner, ready.deliveryId)).rejects.toMatchObject({ code: 'outcome_unknown' }) + expect(await service.get(owner, ready.deliveryId)).toMatchObject({ preparationState: 'unknown' }) + }) + + it('checks an explicitly selected exact revision and stores only its reference', async () => { + open() + const revision = { family: 'handoff', artifact_id: 'current', revision: 3 } + fetch.mockImplementationOnce(async (url, init) => { + expect(url).toContain('/v1/scopes/scope-a/artifacts/handoff/current/revisions/3') + expect(init.method).toBe('GET') + return response({ ...revision, scope_id: 'scope-a', content: { schema: 'powercontext.handoff.v1' } }) + }) + const owner = caller() + const view = await service.prepare(owner, input({ workInput: undefined, revision })) + const bundle = await service.getForLaunch(owner, view.deliveryId) + expect(bundle.handoffSelection).toEqual({ kind: 'revision', revision: { ...revision, scope_id: 'scope-a' } }) + const exported = await service.exportPackage(owner, view.deliveryId) + expect(JSON.parse(Buffer.from(exported.bytes).toString()).carrier).toEqual({ kind: 'revision', revision }) + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('captures bounded evidence and stores the actual generated receipt and final payload', async () => { + const calls: string[] = [] + const checks: WorkEvent[] = ['passed', 'failed', 'interrupted', 'not_run', 'unknown'].map((status, seq) => ({ + sessionId: source.sessionId, seq, kind: 'check', command: 'check ' + seq, + status: status as Extract['status'], + observedAt: source.workspaceObservedAt, ...(seq === 1 ? { revision: 'old', exitCode: 1 } : {}), + })) + let reads = 0 + const readBoundary: BoundaryReader = async (_context, selected, budget) => { + expect(selected).toEqual(source) + expect(budget).toEqual({ maxEvents: 511, maxBytes: 6000, maxWorkspaceBytes: 6000 }) + return { source: selected, objective: work.objective, + selectedReply: { messageId: source.messageId, seq: 999, text: 'The tool results are available.' }, + workspace: { observedAt: source.workspaceObservedAt, revision: 'new', uncommittedChanges: ' M file.ts' }, + events: (function* () { + for (const check of checks) { reads++; yield check } + for (let seq = 5; seq < 900; seq++) { + reads++ + yield { sessionId: source.sessionId, seq, kind: 'completed', text: 'x'.repeat(900) } + } + })(), + } + } + let captured: Wire<'CaptureContentSourceResponse'> + fetch.mockImplementationOnce(async (url, init) => { + calls.push(url) + const body = JSON.parse(init.body as string) + const material = JSON.parse(body.content) + expect(body.scope_id).toBe('scope-a') + expect(material.events.slice(0, 5)).toEqual(checks) + expect(material.workspace).toEqual({ revision: 'new', observedAt: source.workspaceObservedAt, uncommittedChanges: ' M file.ts' }) + expect(material.omissions).toEqual(expect.arrayContaining([expect.stringContaining('event limit'), expect.stringContaining('different revision')])) + expect(Buffer.byteLength(body.content)).toBeLessThanOrEqual(6000) + captured = { status: 'accepted', source: { name: 'content', source_id: body.source_id, locator: null }, position: 8 } + return response(captured, 202) + }).mockImplementationOnce(async (url, init) => { + calls.push(url) + const body = JSON.parse(init.body as string) + expect(body.evidence).toEqual([{ kind: 'source', source_ref: captured.source }]) + return response({ objective: work.objective, state: [statement('Known failure', captured.source)], + disposition: 'continuable', next_action: null, omissions: [], generation: { receipt: 'generation-origin' } }) + }).mockImplementationOnce(async (url, init) => { + calls.push(url) + const { draft } = JSON.parse(init.body as string) + return response({ schema: 'powercontext.prepared-handoff.v1', scope_id: 'scope-a', base: null, + generation: draft.generation, content: { schema: 'powercontext.handoff.v1', objective: draft.objective, + state: draft.state, disposition: draft.disposition, next_action: draft.next_action, omissions: [] } }) + }) + open({ readBoundary, resolveConnection: async () => ({ client, generation: { maxInputBytes: 6000 } }) }) + const owner = caller() + const view = await service.prepare(owner, input({ workInput: undefined })) + expect(view.preparationState).toBe('prepared') + expect(reads).toBe(511) + expect(calls.map(url => new URL(url).pathname)).toEqual(['/v1/sources/content', '/v1/handoff/prepare', '/v1/handoff/finalize']) + const result = JSON.parse(Buffer.from((await service.exportPackage(owner, view.deliveryId)).bytes).toString()) + expect(result.carrier.sourceReceipts).toEqual([captured!]) + expect(result.carrier.prepared.generation.receipt).toBe('generation-origin') + }) + + it.each([16, 17])('discloses truncation of %i Host omissions in the captured source', async count => { + const omissions = Array.from({ length: count }, (_, i) => 'Host omission ' + (i + 1)) + const readBoundary: BoundaryReader = async (_context, selected) => ({ + source: selected, objective: work.objective, + selectedReply: { messageId: selected.messageId, seq: selected.throughSeq, text: 'Selected reply' }, + events: [], workspace: { observedAt: selected.workspaceObservedAt, revision: 'abc', uncommittedChanges: '' }, + omissions, + }) + let captured: unknown + fetch.mockImplementationOnce(async (_url, init) => { + captured = JSON.parse(JSON.parse(init.body as string).content) + return response({}, 422) + }) + open({ readBoundary, resolveConnection: async () => ({ client, generation: { maxInputBytes: 6000 } }) }) + await service.prepare(caller(), input({ workInput: undefined })) + expect(captured).toMatchObject({ omissions: [ + 'No check evidence was available; whether checks ran is unknown.', + ...omissions.slice(0, 16), + ...(count > 16 ? ['Additional omissions reported by the Host could not be included.'] : []), + ] }) + }) + + it('records unavailable evidence without inventing an unrun check or substituting another reply', async () => { + const reader: BoundaryReader = async (_context, selected) => ({ + source: selected, objective: work.objective, + selectedReply: { messageId: selected.messageId, seq: selected.throughSeq, text: 'Selected reply' }, + events: [], workspace: null, + }) + const readBoundary = vi.fn(reader) + open({ readBoundary, resolveConnection: async () => ({ client, generation: { maxInputBytes: 6000 } }) }) + const owner = caller() + readBoundary.mockResolvedValueOnce({ ...(await reader(owner, source, { + maxBytes: 6000, maxWorkspaceBytes: 6000, maxEvents: 511, + })), selectedReply: { messageId: 'some-other-reply', seq: 999, text: 'Different reply' } }) + expect(await service.prepare(owner, input({ workInput: undefined }))).toMatchObject({ + preparationState: 'failed', error: { code: 'binding_mismatch' }, + }) + expect(fetch).not.toHaveBeenCalled() + let observed: unknown + fetch.mockImplementationOnce(async (_url, init) => { + observed = JSON.parse(JSON.parse(init.body as string).content) + return response({}, 422) + }) + await service.prepare(owner, input({ requestId: 'correct-boundary', workInput: undefined })) + expect(observed).toMatchObject({ events: [], workspace: null, omissions: expect.arrayContaining([ + expect.stringContaining('whether checks ran is unknown'), + expect.stringContaining('workspace observation'), + ]) }) + }) + + it('protects unconfirmed and pinned packages, and serializes deletion with a path consumer', async () => { + let now = Date.parse(source.workspaceObservedAt) + open({ now: () => now, limits: { maxDeliveries: 1 } }) + const owner = caller() + const first = await service.prepare(owner, input()) + const second = input({ requestId: 'second', source: { ...source, sessionId: 'other-session' } }) + const confirmedAt = now + 1000 + now += 10 * 86_400_000 + await service.prune(owner) // No proof of receipt. + await service.pin(owner, first.deliveryId, true) + await service.prune(owner, async () => confirmedAt) + await expect(service.prepare(owner, second)).rejects.toMatchObject({ code: 'capacity_exceeded' }) + const exported = await service.exportPackage(owner, first.deliveryId) + const reading = service.getForLaunch(owner, first.deliveryId) + await expect(service.delete(owner, first.deliveryId)).rejects.toMatchObject({ code: 'not_ready' }) + expect(sha256(readFileSync((await reading).packagePath))).toBe(exported.packageSha256) + await service.withLaunchBundle(owner, first.deliveryId, async bundle => { + await expect(service.delete(owner, first.deliveryId)).rejects.toMatchObject({ code: 'not_ready' }) + expect(sha256(readFileSync(bundle.packagePath))).toBe(exported.packageSha256) + }) + await service.pin(owner, first.deliveryId, false) + await service.prune(owner, async () => confirmedAt) + expect(await service.get(owner, first.deliveryId)).toMatchObject({ expired: true }) + await expect(service.getForLaunch(owner, first.deliveryId)).rejects.toMatchObject({ code: 'not_found' }) + expect(await service.prepare(owner, second)).toMatchObject({ preparationState: 'prepared' }) + now += 30 * 86_400_000 + await service.prune(owner) + await expect(service.get(owner, first.deliveryId)).rejects.toMatchObject({ code: 'not_found' }) + }) + + it('rejects a symlinked store and an unsupported envelope without rewriting it', async () => { + const outside = join(parent, 'outside') + mkdirSync(outside, { mode: 0o700 }) + symlinkSync(outside, directory) + expect(() => open()).toThrowError(expect.objectContaining({ code: 'payload_invalid' })) + rmSync(directory) + open() + const result = await service.prepare(caller(), input()) + await service.close() + const record = join(directory, result.deliveryId + '.record.json') + const original = readFileSync(record) + const future = JSON.stringify({ schema: 'powercontext.dsh-delivery.v2' }) + writeFileSync(record, future) + expect(() => open()).toThrowError(expect.objectContaining({ code: 'payload_invalid' })) + expect(readFileSync(record, 'utf8')).toBe(future) + writeFileSync(record, original) + expect(await open().get(caller(), result.deliveryId)).toMatchObject({ preparationState: 'prepared' }) + }) +}) + +it('matches Python Core digest vectors across wire names, Unicode, ordering and nulls', () => { + const fixtures = JSON.parse(readFileSync(new URL('./fixtures/handoff-digests.json', import.meta.url), 'utf8')) + for (const fixture of fixtures) { + const value = wire('PreparedHandoff', fixture.wire) + expect(preparedDigest(value)).toBe(fixture.digest) + const shuffled = Object.fromEntries(Object.entries(fixture.wire).reverse()) + expect(preparedDigest(wire('PreparedHandoff', shuffled))).toBe(fixture.digest) + } +}) diff --git a/scripts/generate_js_operations.py b/scripts/generate_js_operations.py index 7a61f758ab..c2de84abf4 100644 --- a/scripts/generate_js_operations.py +++ b/scripts/generate_js_operations.py @@ -31,6 +31,7 @@ ROOT / "integrations" / "pi" / "plugins" / "powercontext" / "src" / "operations.generated.ts", ) MCP_GENERATED_PATH = ROOT / "integrations" / "dsh" / "plugins" / "powercontext" / "src" / "mcp-operations.generated.ts" +HANDOFF_GENERATED_PATH = MCP_GENERATED_PATH.with_name("handoff") / "http.generated.ts" DRIFT_MESSAGE = "Generated JS operations drifted; run 'make js-api-generate' and review the result." HTTP_METHODS = ("get", "post", "put", "patch", "delete") LICENSE_HEADER = """\ @@ -109,17 +110,55 @@ def main() -> None: contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8")) source = render_operations_source(contract) mcp_source = render_mcp_operations_source() + handoff_source = render_handoff_schemas(contract) if args.check: current = [path.read_text(encoding="utf-8") if path.is_file() else "" for path in GENERATED_PATHS] if any(item.replace("\r\n", "\n") != source.replace("\r\n", "\n") for item in current): raise SystemExit(DRIFT_MESSAGE) if not MCP_GENERATED_PATH.is_file() or MCP_GENERATED_PATH.read_text(encoding="utf-8") != mcp_source: raise SystemExit(DRIFT_MESSAGE) + if not HANDOFF_GENERATED_PATH.is_file() or HANDOFF_GENERATED_PATH.read_text(encoding="utf-8") != handoff_source: + raise SystemExit(DRIFT_MESSAGE) return for path in GENERATED_PATHS: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(source, encoding="utf-8", newline="\n") MCP_GENERATED_PATH.write_text(mcp_source, encoding="utf-8", newline="\n") + HANDOFF_GENERATED_PATH.write_text(handoff_source, encoding="utf-8", newline="\n") + + +def render_handoff_schemas(doc: dict[str, Any]) -> str: + """Export the existing wire schemas used by the DSH delivery service.""" + + schemas = doc["components"]["schemas"] + definitions: dict[str, Any] = {} + + def select(value: dict[str, Any]) -> dict[str, Any]: + result = {key: item for key, item in value.items() if key not in {"description", "title", "discriminator"}} + if "$ref" in result: + name = result["$ref"].rsplit("/", 1)[1] + result["$ref"] = name + if name not in definitions: + definitions[name] = select(schemas[name]) + if "properties" in result: + result["properties"] = {key: select(item) for key, item in result["properties"].items()} + if "items" in result: + result["items"] = select(result["items"]) + for key in ("oneOf", "allOf"): + if key in result: + result[key] = [select(item) for item in result[key]] + return result + + for name in ("CurrentWorkHandoff", "PreparedWorkHandoff", "HandoffDraft", "CaptureContentSourceResponse"): + definitions[name] = select(schemas[name]) + lines = "\n".join( + f" {name}: {json.dumps(value, ensure_ascii=False, separators=(',', ':'))}," + for name, value in sorted(definitions.items()) + ) + return ( + f"{LICENSE_HEADER}// generated from openapi/powercontext.yaml; do not edit.\n\n" + f"export const HANDOFF_HTTP_SCHEMAS = {{\n{lines}\n}} as const\n" + ) def render_mcp_operations_source() -> str: diff --git a/tests/test_dsh_handoff_digest.py b/tests/test_dsh_handoff_digest.py new file mode 100644 index 0000000000..b0d77a919f --- /dev/null +++ b/tests/test_dsh_handoff_digest.py @@ -0,0 +1,32 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import json +from pathlib import Path + +from powercontext.builtin.work.models import content_digest +from powercontext.http import PreparedHandoff +from powercontext.server.mapping import runtime_prepared_handoff + + +def test_dsh_prepared_digest_vectors_match_core() -> None: + fixtures = ( + Path(__file__).resolve().parents[1] + / "integrations/dsh/plugins/powercontext/tests/fixtures/handoff-digests.json" + ) + for vector in json.loads(fixtures.read_text(encoding="utf-8")): + prepared = runtime_prepared_handoff(PreparedHandoff.model_validate(vector["wire"])) + assert content_digest(prepared) == vector["digest"]