From 293216db64ee61f77b56fa50db94c792a629bb4b Mon Sep 17 00:00:00 2001 From: MYCF711 Date: Mon, 9 Nov 2026 11:09:46 +0800 Subject: [PATCH 1/4] fix(inline-tools): let agent/created await the bash mount A global PTC executor resolves its SDK right after agent creation. The listener returned nothing, so the first admission could see a face without bash (step 1 missing, step 2 present). Return the in-flight reconcile task so the serial agent/created emission waits for it. --- package.json | 2 +- src/inline-tools.js | 25 ++- tests/global-ptc-created.mjs | 293 +++++++++++++++++++++++++++++++++++ 3 files changed, 318 insertions(+), 2 deletions(-) create mode 100644 tests/global-ptc-created.mjs diff --git a/package.json b/package.json index 1fba5ea..531bf4e 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "icon.svg" ], "scripts": { - "test": "node --test tests/smoke.mjs tests/private-executor.mjs tests/client-regressions.mjs tests/bridge-regressions.mjs tests/runtime-regressions.mjs tests/host-regressions.mjs tests/compatibility-regressions.mjs tests/path-tool.mjs tests/native-output.mjs tests/native-executor.mjs tests/ops-adopt.mjs tests/terminal-cancel.mjs tests/review-core-regressions.mjs tests/review-native-regressions.mjs tests/terminal-bundle.mjs tests/audit-regressions.mjs", + "test": "node --test tests/smoke.mjs tests/private-executor.mjs tests/client-regressions.mjs tests/bridge-regressions.mjs tests/runtime-regressions.mjs tests/host-regressions.mjs tests/compatibility-regressions.mjs tests/path-tool.mjs tests/native-output.mjs tests/native-executor.mjs tests/ops-adopt.mjs tests/terminal-cancel.mjs tests/review-core-regressions.mjs tests/review-native-regressions.mjs tests/terminal-bundle.mjs tests/audit-regressions.mjs tests/global-ptc-created.mjs", "test:preview": "node --import ./tests/host-loader.mjs --import ./tests/preview-env.mjs --test tests/preview.mjs tests/bridge-preview.mjs tests/runtime-preview.mjs tests/host-preview.mjs tests/path-preview.mjs tests/native-output-preview.mjs tests/native-preview.mjs tests/native-integration-preview.mjs tests/review-native-preview.mjs tests/audit-preview.mjs", "version": "node -e \"const fs=require('fs');const m=JSON.parse(fs.readFileSync('dsh.plugin.json','utf8'));const v=JSON.parse(fs.readFileSync('package.json','utf8')).version;m.version=v;fs.writeFileSync('dsh.plugin.json',JSON.stringify(m,null,2)+'\\n')\" && git add dsh.plugin.json" }, diff --git a/src/inline-tools.js b/src/inline-tools.js index d42d46b..002a9f6 100644 --- a/src/inline-tools.js +++ b/src/inline-tools.js @@ -636,6 +636,14 @@ export function mountInlineTools(ctx, deps) { } } } + // The own bash mount is ASYNCHRONOUS (private executor import, class-plugin + // mount in the agent scope, registry read-back). Hand the in-flight task + // back so the SERIAL `agent/created` emission can WAIT for it: the global + // PTC executor resolves its SDK right after creation, and a listener that + // returned nothing let that first admission see a face without bash (step + // 1 missing, step 2 present). When a scope is already owned (or no bash is + // wanted) there is nothing to wait for. + return state.pending } const teardown = async (agent) => { @@ -666,7 +674,22 @@ export function mountInlineTools(ctx, deps) { }, 'dsh-gitbash-shell: inline tool patching') try { - ctx.on('agent/created', ({ agent } = {}) => { try { reconcile(agent) } catch { /* never break agent creation */ } }) + // RETURN the reconcile promise. DSH announces a new agent through the + // SERIAL `agent/created` event (`@deepseek-ai/dsh-agent` announce() awaits + // `ctx.serial(carrier, 'agent/created', …)`), so the returned promise makes + // `agents.create()` wait for this agent's own bash registration. Without + // it the global PTC executor resolved its SDK on a face that did not carry + // bash yet (step 1 missing, step 2 present). + ctx.on('agent/created', ({ agent } = {}) => { + try { + const pending = reconcile(agent) + // Wait for the registration, but never turn a registration failure + // into a failed `agents.create()`: provideBash already logs its own + // failures, and the host's serial emission rejects the whole + // announcement when a listener rejects. + return pending && typeof pending.then === 'function' ? pending.catch(() => {}) : pending + } catch { /* never break agent creation */ } + }) ctx.on('agent/disposed', ({ agent } = {}) => teardown(agent).catch((error) => { log(`agent bash tool cleanup failed: ${error?.message ?? error}`) })) diff --git a/tests/global-ptc-created.mjs b/tests/global-ptc-created.mjs new file mode 100644 index 0000000..64892a2 --- /dev/null +++ b/tests/global-ptc-created.mjs @@ -0,0 +1,293 @@ +/** + * Global PTC first-step Bash race (regression guard for the 0.51.0 fix). + * + * THE HOST CONTRACT. `ctx.agents.create()` announces a new agent through the + * SERIAL `agent/created` event: `@deepseek-ai/dsh-agent`'s `announce()` does + * `await this.ctx.serial(entry.carrier, 'agent/created', …)`, so a listener + * that RETURNS its promise makes agent creation itself wait. The global PTC + * executor resolves its SDK tool set immediately after creation; while the + * own-Git-Bash registration was in flight that first admission had no `bash` + * and the tool appeared one step later (step 1 missing, step 2 present). + * + * WHAT IS REAL HERE. `mountInlineTools`, the real per-agent `reconcile`, the + * real `startBash`/`provideBash` chain, the real `createBashToolModule` from + * src/bash-tool.js, the real tools-registry read-back (`schemas(agent)`) and + * the real `agent/disposed` teardown. THE ONLY STUB is the private executor + * import (`./shell.js`, whose base class is `@deepseek-ai/dsh-bash-sandbox`): + * that host peer is not installed in a unit-test checkout, so it is redirected + * to a tiny data-URL module and the fake executor scope models an executor + * mount that takes a few milliseconds — exactly the real cost that used to + * lose the race. No production profile, no model request, no filesystem write. + */ + +import test from 'node:test' +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' + +const SHELL_STUB_URL = `data:text/javascript,${encodeURIComponent( + 'export class GitBashSandboxExecutor { static Config = {} }', +)}` + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier === './shell.js' && typeof context.parentURL === 'string' + && context.parentURL.endsWith('/src/inline-tools.js')) { + return { url: SHELL_STUB_URL, shortCircuit: true } + } + return nextResolve(specifier, context) + }, +}) + +const resolvedThenable = () => ({ + then(resolve, reject) { return Promise.resolve().then(resolve, reject) }, +}) + +/** Base host face before this plugin acts: the official win32 composition. */ +const BASE_FACE = ['pwsh', 'read', 'edit'] + +function createRegistry() { + const masks = new WeakMap() + const registrations = new Map() + const calls = new Map() + return { + restrict(agent, deny) { + const mask = masks.get(agent) ?? new Set() + for (const name of deny) mask.add(name) + masks.set(agent, mask) + return () => { for (const name of deny) mask.delete(name) } + }, + register(agent, definition) { + const name = definition?.name + const list = registrations.get(agent) ?? [] + const entry = { name } + list.push(entry) + registrations.set(agent, list) + const seen = calls.get(agent) ?? [] + seen.push(name) + calls.set(agent, seen) + let live = true + return () => { + if (!live) return + live = false + const index = list.indexOf(entry) + if (index >= 0) list.splice(index, 1) + } + }, + schemas(agent) { + const mask = masks.get(agent) ?? new Set() + const names = [...BASE_FACE, ...(registrations.get(agent) ?? []).map((entry) => entry.name)] + return [...new Set(names)].filter((name) => !mask.has(name)).map((name) => ({ name })) + }, + registerCalls(agent, name) { + return (calls.get(agent) ?? []).filter((entry) => entry === name).length + }, + activeCount() { + let total = 0 + for (const list of registrations.values()) total += list.length + return total + }, + } +} + +/** + * A faithful "serial" emission: DSH's `ctx.serial` awaits each listener in + * order, so a listener that returns its promise delays the caller. + */ +function createFixture({ mountDelayMs = 50 } = {}) { + const listeners = new Map() + const effects = [] + const logs = [] + const registry = createRegistry() + const agentByCtx = new WeakMap() + const scopesByAgent = new WeakMap() + const executorScopes = [] + const hostModules = { + '@deepseek-ai/dsh-tools': { defineTool: (options) => ({ ...options }) }, + '@deepseek-ai/dsh-sandbox': {}, + '@deepseek-ai/dsh-llm': {}, + } + const rootCtx = { + baseUrl: 'file:///fixture/', + on(name, callback) { + const list = listeners.get(name) ?? [] + list.push(callback) + listeners.set(name, list) + return () => {} + }, + effect(callback) { effects.push(callback()) }, + isolate(name) { return { isolated: name } }, + loader: { internal: { async import(name) { return hostModules[name] ?? {} } } }, + } + + const createScope = (parent) => { + if (parent?.isolated === 'shell') { + let instance + const scope = { + disposed: 0, + // Models the real executor-mount cost (module import + class plugin + // mount) that the created-time race used to hide behind. + fiber: new Promise((resolve) => setTimeout(resolve, mountDelayMs)), + ctx: { + loader: { internal: { async import() { return {} } } }, + plugin() { + instance = { + bashPath: 'C:/fixture/Git/bin/bash.exe', + sandboxMode: undefined, + resolve: (request) => request, + execute: async () => { throw new Error('fixture executor must not execute') }, + } + return resolvedThenable() + }, + get(name) { return name === 'shell' ? instance : undefined }, + }, + async dispose() { scope.disposed += 1 }, + } + executorScopes.push(scope) + return scope + } + const agent = agentByCtx.get(parent) + if (!agent) throw new Error('unknown scope owner (createScope must receive an agent ctx)') + const state = { disposed: 0 } + const registrations = [] + const facadeTools = { + register(definition) { + const dispose = registry.register(agent, definition) + registrations.push(dispose) + return dispose + }, + schemas: (who) => registry.schemas(who), + definitions: () => [], + executable: () => undefined, + } + const scopeCtx = { + get(name) { return name === 'tools' ? facadeTools : undefined }, + inject() { /* no jobs service in this fixture */ }, + systemPrompt: { section() {}, getSectionOrder() { return 100 } }, + tools: facadeTools, + } + const scope = { + ctx: scopeCtx, + fiber: Promise.resolve(), + state, + async dispose() { + state.disposed += 1 + for (const dispose of registrations.splice(0)) dispose() + }, + } + // cordis' `ctx.plugin(mod)` starts a fiber asynchronously; provideBash + // awaits it, then reads the registry back. Run apply synchronously and + // expose the same thenable/dispose shape. + scopeCtx.plugin = (impl) => { + impl.apply(scopeCtx, {}) + return { + then(resolve, reject) { return Promise.resolve().then(resolve, reject) }, + async dispose() { await scope.dispose() }, + } + } + scopesByAgent.set(agent, scope) + return scope + } + + // Import AFTER the resolve hook is installed, so the stubbed executor module + // is the one provideBash's dynamic import() sees. + const mounting = import('../src/inline-tools.js').then(({ mountInlineTools }) => { + mountInlineTools(rootCtx, { + tools: () => registry, + agents: () => ({ list: () => [] }), + createScope, + pwshEnabled: () => false, + experimentalEnabled: () => true, + log: (message) => logs.push(message), + }) + return { mountInlineTools } + }) + + const createAgent = (id) => { + const agent = { id, ctx: undefined } + agent.ctx = { + tools: { restrict: ({ deny }) => registry.restrict(agent, deny) }, + get: () => undefined, + } + agentByCtx.set(agent.ctx, agent) + return agent + } + + const emitCreated = async (agent) => { + const returned = [] + for (const callback of listeners.get('agent/created') ?? []) returned.push(await callback({ agent })) + return returned + } + const emitDisposed = async (agent) => { + for (const callback of listeners.get('agent/disposed') ?? []) await callback({ agent }) + } + const preExecute = (agent, name = 'bash') => { + const callback = (listeners.get('tools/pre-execute') ?? [])[0] + return callback?.({ agent, name }, () => ({ kind: 'allow' })) + } + + return { + ready: mounting, + registry, + logs, + effects, + executorScopes, + createAgent, + emitCreated, + emitDisposed, + preExecute, + scopeOf: (agent) => scopesByAgent.get(agent), + } +} + +test('global PTC first step: agent/created waits for the own Bash registration', async () => { + const fixture = createFixture() + await fixture.ready + const agent = fixture.createAgent('agent-created-waits') + + // The serial `agent/created` emission: its completion is what + // `ctx.agents.create()` awaits before the caller can resolve the SDK. + await fixture.emitCreated(agent) + + const names = fixture.registry.schemas(agent).map((schema) => schema.name) + assert.ok( + names.includes('bash'), + `admission after agent/created lacks bash (face: [${names.join(', ')}]); ` + + 'the created listener resolved before the own Bash registration', + ) + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 1, 'exactly one own bash registration') +}) + +test('global PTC: no duplicate registration on later reconciles, and dispose leaks nothing', async () => { + const fixture = createFixture() + await fixture.ready + const agent = fixture.createAgent('agent-dispose') + await fixture.emitCreated(agent) + assert.ok(fixture.registry.schemas(agent).some((schema) => schema.name === 'bash')) + + // The lazy pre-execute re-reconcile must not mount a second bash tool while + // the agent-owned scope already exists. + fixture.preExecute(agent) + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 1, 'no duplicate registration') + + await fixture.emitDisposed(agent) + assert.equal(fixture.scopeOf(agent)?.state.disposed, 1, 'the agent-owned scope is disposed once') + assert.equal( + fixture.registry.schemas(agent).some((schema) => schema.name === 'bash'), + false, + 'the own bash registration is withdrawn with the agent', + ) + assert.equal(fixture.registry.activeCount(), 0, 'no registration outlives its agent') + + // A later agent proves the five-step path is still live and that no pending + // task from the disposed agent muddied the state. + const second = fixture.createAgent('agent-after-dispose') + await fixture.emitCreated(second) + assert.equal(fixture.registry.registerCalls(second, 'bash'), 1) + assert.equal(fixture.registry.activeCount(), 1) + await fixture.emitDisposed(second) + assert.equal(fixture.registry.activeCount(), 0) + + // Plugin-level ownership: the shared private executor scope goes away too. + for (const effect of fixture.effects.reverse()) await effect() + assert.equal(fixture.executorScopes[0]?.disposed, 1, 'the private executor scope is released on plugin dispose') +}) From f46416589b78791371baf3fa98feaa8ea6b8d3b9 Mon Sep 17 00:00:00 2001 From: MYCF711 Date: Mon, 9 Nov 2026 11:13:46 +0800 Subject: [PATCH 2/4] feat: add a globalPtcSdk row switch (default OFF) A deployment that wants every agent to reach its tools through the PTC run_code SDK needs the ROOT executor switched. That is a profile-patch decision (bundle patches are read before the profile patch file) and a row-level `disabled` that configEditor cannot write, so the switch writes it the way the persistent-terminal adoption already does: parseDocument, targeted edits, an atomic write, verify-by-reread and rollback. Default OFF writes nothing and never removes rows the user added. Turning it OFF again lifts only the rows this switch wrote, matched by exact value; a row the user shaped differently is left alone. What it writes: - tool-executor-native: disabled true - tool-executor-ptc: disabled false - preset-minimal restated with persona.complete:false, because a complete persona erases the PTC SDK at assembly (re-align that block when DSH is upgraded). --- package.json | 2 +- src/global-ptc.js | 408 +++++++++++++++++++++++++++++++++++++++++++ src/index.js | 65 +++++++ tests/global-ptc.mjs | 211 ++++++++++++++++++++++ 4 files changed, 685 insertions(+), 1 deletion(-) create mode 100644 src/global-ptc.js create mode 100644 tests/global-ptc.mjs diff --git a/package.json b/package.json index 531bf4e..e5172ba 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "icon.svg" ], "scripts": { - "test": "node --test tests/smoke.mjs tests/private-executor.mjs tests/client-regressions.mjs tests/bridge-regressions.mjs tests/runtime-regressions.mjs tests/host-regressions.mjs tests/compatibility-regressions.mjs tests/path-tool.mjs tests/native-output.mjs tests/native-executor.mjs tests/ops-adopt.mjs tests/terminal-cancel.mjs tests/review-core-regressions.mjs tests/review-native-regressions.mjs tests/terminal-bundle.mjs tests/audit-regressions.mjs tests/global-ptc-created.mjs", + "test": "node --test tests/smoke.mjs tests/private-executor.mjs tests/client-regressions.mjs tests/bridge-regressions.mjs tests/runtime-regressions.mjs tests/host-regressions.mjs tests/compatibility-regressions.mjs tests/path-tool.mjs tests/native-output.mjs tests/native-executor.mjs tests/ops-adopt.mjs tests/terminal-cancel.mjs tests/review-core-regressions.mjs tests/review-native-regressions.mjs tests/terminal-bundle.mjs tests/audit-regressions.mjs tests/global-ptc-created.mjs tests/global-ptc.mjs", "test:preview": "node --import ./tests/host-loader.mjs --import ./tests/preview-env.mjs --test tests/preview.mjs tests/bridge-preview.mjs tests/runtime-preview.mjs tests/host-preview.mjs tests/path-preview.mjs tests/native-output-preview.mjs tests/native-preview.mjs tests/native-integration-preview.mjs tests/review-native-preview.mjs tests/audit-preview.mjs", "version": "node -e \"const fs=require('fs');const m=JSON.parse(fs.readFileSync('dsh.plugin.json','utf8'));const v=JSON.parse(fs.readFileSync('package.json','utf8')).version;m.version=v;fs.writeFileSync('dsh.plugin.json',JSON.stringify(m,null,2)+'\\n')\" && git add dsh.plugin.json" }, diff --git a/src/global-ptc.js b/src/global-ptc.js new file mode 100644 index 0000000..1cf14b9 --- /dev/null +++ b/src/global-ptc.js @@ -0,0 +1,408 @@ +/** + * dsh-gitbash-shell — global PTC SDK adoption (row switch, default OFF). + * + * WHY THIS EXISTS + * A deployment that wants every agent to reach its tools through the PTC + * `run_code` SDK instead of a per-tool native face needs the ROOT executor + * switched: `tool-executor-native` off, `tool-executor-ptc` on. That is a + * profile-patch decision (bundle patches are read BEFORE the profile patch + * file), and a `preset-minimal` restatement is required on top of it because + * minimal's `persona.complete: true` erases the SDK at assembly. + * + * Hand-editing that patch is exactly what this plugin's own AGENTS.md forbids + * users to do, so the switch writes it the way the official editor would: + * `yaml`'s parseDocument (comments and !!js expressions survive untouched), + * targeted edits on known rows, a re-parse self-check, an atomic write, a + * verify-by-reread and a rollback to the previous bytes on any mismatch. + * + * WHY NOT configEditor + * Measured on packages/boot/config-editor: `entries()` only sees + * include-mounted TOP-LEVEL rows and `edit()` only writes a config key, never + * a row-level `disabled`. The same wall is documented in terminal-bundle.js; + * the channel here is therefore the patch file, with the official editor's + * own care. + * + * WHAT IS NEVER DONE + * - A row the user wrote with a DIFFERENT value is never overwritten — every + * one of those states stands down with a reason (kept-user-choice). + * - A non-literal row (for example `disabled: !!js …`) is never replaced by + * a literal. + * - Nothing is written when the switch is OFF, and OFF never removes rows + * the user added. + * + * @module dsh-gitbash-shell/global-ptc + */ + +import { readPatchRow, findRow } from './terminal-bundle.js' + +/** Root executor row that runs each tool natively on the wire. */ +export const EXECUTOR_NATIVE_ROW = 'tool-executor-native' +/** Root executor row that runs each tool through the PTC run_code SDK. */ +export const EXECUTOR_PTC_ROW = 'tool-executor-ptc' +/** The preset whose complete persona erases the SDK when left at the default. */ +export const MINIMAL_PRESET_ROW = 'preset-minimal' + +/** + * Official 0.2.2-rc.1 `preset-minimal` restatement. + * + * `complete: true` would restore only the persona after prompt assembly and + * erase the PTC SDK declarations, so minimal would publish `run_code` without + * any callable SDK behind it. `complete: false` lets the SDK (and the normal + * prompt sections) survive. Every other row is kept byte-for-byte aligned with + * the pinned official preset — re-align this block when DSH is upgraded. + * + * Kept as a fragment (not a hand-built node) so what lands on disk reads like + * the row a careful human would write. + */ +export const MINIMAL_PRESET_FRAGMENT = `- id: preset-minimal + name: '@deepseek-ai/dsh-agent-preset' + config: + id: minimal + order: 3 + plugins: + - id: persona + name: '@deepseek-ai/dsh-persona' + config: + prefix: You are a helpful software engineer assistant. + complete: false + includeRuntimeContext: false + - id: tool-fs + name: '@deepseek-ai/dsh-tool-fs' + config: + read: false + readImage: true + write: false + edit: false + - id: compaction + name: cordis:group + group: true + isolate: + compaction: true + config: + - id: compaction-basic + name: '@deepseek-ai/dsh-compaction-basic' + - id: command-compact + name: '@deepseek-ai/dsh-command-compact' + - id: persistent-shell + name: cordis:group + group: true + isolate: + terminals: true + config: + - id: pty + name: '@deepseek-ai/dsh-terminal' + - id: terminal-bash + name: '@deepseek-ai/dsh-terminal-bash' + disabled: !!js process.platform === 'win32' + config: + timeoutMs: 300000 + - id: persistent-bash + name: '@deepseek-ai/dsh-tool-bash-persistent' + disabled: !!js process.platform === 'win32' + config: + timeoutMs: 300000 + - id: terminal-pwsh + name: '@deepseek-ai/dsh-terminal-bash' + disabled: !!js process.platform !== 'win32' + config: + shellDialect: pwsh + timeoutMs: 300000 + - id: persistent-pwsh + name: '@deepseek-ai/dsh-tool-pwsh-persistent' + disabled: !!js process.platform !== 'win32' + config: + timeoutMs: 300000 +` + +/** + * Flatten one `preset-minimal` row into the single fact this module decides on. + * @param {unknown} row - a parsed patch entry. + * @returns {{complete?: boolean, opaque?: true}|undefined} + */ +export function readMinimalRow(row) { + if (!row || typeof row !== 'object' || Array.isArray(row)) return undefined + const config = row.config + if (!config || typeof config !== 'object' || Array.isArray(config)) return { opaque: true } + const plugins = config.plugins + // A preset row without a plugin list is not the shape we write; refuse to + // reason about it rather than appending a second, contradictory row. + if (!Array.isArray(plugins)) return { opaque: true } + const persona = plugins.find((entry) => entry && typeof entry === 'object' && entry.id === 'persona') + if (!persona) return { opaque: true } + const complete = persona?.config?.complete + if (complete === true) return { complete: true } + if (complete === false) return { complete: false } + // Unset is the official default (true), so an absent key is NOT our shape. + return complete === undefined ? { complete: true } : { opaque: true } +} + +/** + * Pure decision: should (and how exactly) the profile patch adopt the global + * PTC executor for this host? + * + * One action plus one human reason, every state enumerable and testable — + * mirroring `planTerminalBundleAdopt`. + * + * @param {{enabled?: boolean, rows?: {native?: object, ptc?: object, minimal?: object}}} input + * `rows` are the FLATTENED facts (`readPatchRow` / `readMinimalRow` output). + * @returns {{action: string, reason: string, writeNative?: boolean, writePtc?: boolean, writeMinimal?: boolean}} + */ +export function planGlobalPtcAdopt(input) { + const { enabled, rows } = input ?? {} + if (enabled !== true) { + return { + action: 'skip-disabled', + reason: 'globalPtcSdk is off — the root executor keeps its official shape (native face, no SDK)', + } + } + + const native = rows?.native + const ptc = rows?.ptc + const minimal = rows?.minimal + + // A non-literal value is somebody's condition, not our setting. + if (native?.opaque === true || ptc?.opaque === true || minimal?.opaque === true) { + return { + action: 'kept-user-choice', + reason: 'a root executor or preset row carries a non-literal value (for example !!js) — not replacing an explicit condition with a literal', + } + } + // An explicit row that says the OPPOSITE of what the switch wants. + if (native !== undefined && native.disabled !== true) { + return { + action: 'kept-user-choice', + reason: 'the profile patch explicitly keeps the native root executor — not overriding an explicit user choice', + } + } + if (ptc !== undefined && ptc.disabled !== false) { + return { + action: 'kept-user-choice', + reason: 'the profile patch explicitly disables the PTC root executor — not overriding an explicit user choice', + } + } + if (minimal !== undefined && minimal.complete !== false) { + return { + action: 'kept-user-choice', + reason: 'a user-written preset-minimal row keeps a complete persona; restating it would overwrite that choice', + } + } + + const writeNative = native === undefined + const writePtc = ptc === undefined + const writeMinimal = minimal === undefined + if (!writeNative && !writePtc && !writeMinimal) { + return { + action: 'unchanged', + reason: 'the profile patch already runs every agent through the global PTC SDK (native off, ptc on, minimal restated with complete:false)', + } + } + return { + action: 'adopt', + reason: `writing the global PTC SDK overrides (${[ + writeNative ? 'native off' : undefined, + writePtc ? 'ptc on' : undefined, + writeMinimal ? 'minimal restated' : undefined, + ].filter(Boolean).join(', ')})`, + writeNative, + writePtc, + writeMinimal, + } +} + +/** + * Extract the current override rows for the three ids this module owns. + * @param {object} yaml - the eemeli yaml module (unused, kept for symmetry). + * @param {object} document - a yaml parseDocument result. + * @returns {{native?: object, ptc?: object, minimal?: object, indices?: {native: number, ptc: number, minimal: number}}} + */ +export function currentGlobalPtcRows(yaml, document) { + const out = {} + const indices = { native: -1, ptc: -1, minimal: -1 } + const items = document?.contents?.items + if (!Array.isArray(items)) return { ...out, indices } + + items.forEach((item, index) => { + if (!item || typeof item !== 'object') return + const id = typeof item.get === 'function' ? item.get('id') : item.id + if (id === EXECUTOR_NATIVE_ROW) { + indices.native = index + out.native = readPatchRow(toPlain(item)) + } else if (id === EXECUTOR_PTC_ROW) { + indices.ptc = index + out.ptc = readPatchRow(toPlain(item)) + } else if (id === MINIMAL_PRESET_ROW) { + indices.minimal = index + out.minimal = readMinimalRow(toPlain(item)) + } + }) + return { ...out, indices } +} + +/** Convert a yaml node to plain JS data (no anchors, no tags). */ +function toPlain(node) { + if (node && typeof node.toJSON === 'function') { + try { return node.toJSON() } catch { return undefined } + } + return node +} + +/** + * Apply (or lift) the global PTC SDK override through the profile patch file. + * + * @param {{readFile: (file: string) => Promise, writeFileAtomic: (file: string, data: string) => Promise, yaml: () => Promise}} io + * @param {{patchPath: string, enabled?: boolean, lift?: boolean}} input + * @returns {Promise<{action: string, status: string, reason?: string, detail?: string, wrote?: string[]}>} + */ +export async function adoptGlobalPtcPatch(io, input) { + const done = (action, status, reason, extra = {}) => ({ action, status, reason, ...extra }) + const { patchPath, enabled, lift } = input ?? {} + + let yamlModule + try { + yamlModule = await io.yaml() + } catch (error) { + return done('skip-modules', 'skip-modules', undefined, { detail: `the yaml document module is unavailable (${error?.message ?? error})` }) + } + if (typeof yamlModule?.parseDocument !== 'function' || typeof yamlModule?.isSeq !== 'function') { + return done('skip-modules', 'skip-modules', undefined, { detail: 'the yaml document module lacks parseDocument/isSeq' }) + } + + let before + try { + before = await io.readFile(patchPath) + } catch (error) { + if (error?.code !== 'ENOENT') { + return done('skip-read', 'skip-read', undefined, { detail: `the profile patch could not be read (${error?.message ?? error})` }) + } + before = '[]\n' + } + + const parse = (text) => yamlModule.parseDocument(text, { + customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value) => value }], + }) + + const document = parse(before) + if (Array.isArray(document?.errors) && document.errors.length > 0) { + return done('skip-parse', 'skip-parse', undefined, { detail: 'the profile patch has YAML errors; refusing to edit a broken document' }) + } + if (!yamlModule.isSeq(document?.contents)) { + return done('skip-shape', 'skip-shape', undefined, { detail: 'the profile patch is not a YAML sequence; refusing to edit an unknown shape' }) + } + + const { indices } = currentGlobalPtcRows(yamlModule, document) + + // LIFT: remove only rows whose value is EXACTLY ours. A row the user edited + // since is left alone — turning the switch off must not delete their work. + if (lift === true) { + const snapshot = currentGlobalPtcRows(yamlModule, document) + const remove = [] + if (snapshot.native?.disabled === true) remove.push(indices.native) + if (snapshot.ptc?.disabled === false) remove.push(indices.ptc) + if (snapshot.minimal?.complete === false) remove.push(indices.minimal) + if (remove.length === 0) { + return done('unchanged', 'unchanged', 'no global PTC rows of ours are present; nothing changed') + } + document.contents.flow = false + // Splice from the highest index down so earlier indices still hold. + for (const index of remove.sort((a, b) => b - a)) { + try { document.contents.items.splice(index, 1) } catch { /* reported below */ } + } + const after = String(document) + const check = parse(after) + if (Array.isArray(check?.errors) && check.errors.length > 0) { + return done('lift', 'write-failed', 'the edited patch did not re-parse cleanly; nothing was written') + } + try { + await io.writeFileAtomic(patchPath, after) + } catch (error) { + return done('lift', 'write-failed', undefined, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) + } + // Verify by re-reading what landed on disk. + try { + const reread = parse(await io.readFile(patchPath)) + const rows = currentGlobalPtcRows(yamlModule, reread) + if (rows.native?.disabled === true || rows.ptc?.disabled === false || rows.minimal?.complete === false) { + await io.writeFileAtomic(patchPath, before) + return done('lift', 'write-failed', undefined, { detail: 'the written patch still carries a global PTC override; rolled back to the previous bytes' }) + } + } catch (error) { + try { await io.writeFileAtomic(patchPath, before) } catch { /* report the primary failure */ } + return done('lift', 'write-failed', undefined, { detail: `the verification read failed (${error?.message ?? error}); rolled back to the previous bytes` }) + } + return done('lift', 'lifted', 'removed the global PTC rows this switch wrote', { wrote: ['lift'] }) + } + + // ADOPT + const rows = currentGlobalPtcRows(yamlModule, document) + const plan = planGlobalPtcAdopt({ enabled, rows }) + if (plan.action !== 'adopt') return done(plan.action, plan.action, plan.reason) + + document.contents.flow = false + const addFragment = (text) => { + const fragment = parse(text) + if (Array.isArray(fragment?.errors) && fragment.errors.length > 0) return undefined + return fragment?.contents?.items?.[0] + } + const wrote = [] + if (plan.writeNative) { + const row = addFragment(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true\n`) + if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the native-executor row fragment did not parse; nothing was written' }) + document.add(row) + wrote.push(EXECUTOR_NATIVE_ROW) + } + if (plan.writePtc) { + const row = addFragment(`- id: ${EXECUTOR_PTC_ROW}\n disabled: false\n`) + if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the ptc-executor row fragment did not parse; nothing was written' }) + document.add(row) + wrote.push(EXECUTOR_PTC_ROW) + } + if (plan.writeMinimal) { + const row = addFragment(MINIMAL_PRESET_FRAGMENT) + if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the preset-minimal fragment did not parse; nothing was written' }) + document.add(row) + wrote.push(MINIMAL_PRESET_ROW) + } + + // Self-check before touching disk: the serialized document must re-parse. + const serialized = String(document) + const check = parse(serialized) + if (Array.isArray(check?.errors) && check.errors.length > 0) { + return done('adopt', 'write-failed', plan.reason, { detail: 'the edited patch did not re-parse cleanly; nothing was written' }) + } + + try { + await io.writeFileAtomic(patchPath, serialized) + } catch (error) { + return done('adopt', 'write-failed', plan.reason, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) + } + + // Verify by re-reading what actually landed on disk. + try { + const reread = parse(await io.readFile(patchPath)) + const after = currentGlobalPtcRows(yamlModule, reread) + const nativeOk = after.native?.disabled === true + const ptcOk = after.ptc?.disabled === false + const minimalOk = after.minimal?.complete === false + if (!nativeOk || !ptcOk || !minimalOk) { + await io.writeFileAtomic(patchPath, before) + return done('adopt', 'write-failed', plan.reason, { detail: 'the written patch did not read back as intended; rolled back to the previous bytes' }) + } + } catch (error) { + try { await io.writeFileAtomic(patchPath, before) } catch { /* report the primary failure */ } + return done('adopt', 'write-failed', plan.reason, { detail: `the verification read failed (${error?.message ?? error}); rolled back to the previous bytes` }) + } + + return done('adopt', 'adopted', plan.reason, { wrote }) +} + +/** + * One line per outcome, terminal-bundle style. + * @param {{action: string, status: string, reason?: string, detail?: string, wrote?: string[]}} result + * @returns {string} + */ +export function globalPtcReport(result) { + if (!result || typeof result !== 'object') return 'global PTC SDK adoption returned nothing' + if (typeof result.detail === 'string' && result.detail !== '') return `global PTC SDK: ${result.status} — ${result.detail}` + if (typeof result.reason === 'string' && result.reason !== '') return `global PTC SDK: ${result.reason}` + return `global PTC SDK: ${result.status}` +} diff --git a/src/index.js b/src/index.js index 0e49453..d745a24 100644 --- a/src/index.js +++ b/src/index.js @@ -38,6 +38,7 @@ import { PRESET_META, minimalPluginsFor, pluginsFor } from './compositions.js' import { loadSchemastery } from './schemastery.js' import { mountInlineTools } from './inline-tools.js' import { adoptTerminalBundlePatch, detectTerminalBundle, terminalBundleReport, terminalDialect } from './terminal-bundle.js' +import { adoptGlobalPtcPatch, globalPtcReport } from './global-ptc.js' import { resolveHostModule } from './bash-tool.js' import { mountFastctx } from './fastctx-bridge.js' import { @@ -500,6 +501,23 @@ export const Config = Schema === null ? undefined : Schema.object({ * stands down entirely when dsh-ops is present. */ fastctxTools: Schema.boolean().default(false).volatile(), + /** + * Run every agent through the GLOBAL PTC run_code SDK instead of a native + * per-tool face (default OFF, and deliberately NOT volatile). + * + * The root executor is a profile-patch decision read at boot, so this is a + * patch write and not a live toggle: an edit remounts the plugin, which is + * the right weight for a change that lands on the next start. OFF writes + * nothing and never removes rows the user added. + * + * What it writes (see src/global-ptc.js): `tool-executor-native` off, + * `tool-executor-ptc` on, and a `preset-minimal` restatement whose + * `persona.complete: false` keeps the SDK from being erased at assembly. + * Every write goes through the same guarded atomic writer the persistent + * terminal adoption uses, and stands down on any row the user shaped + * differently. + */ + globalPtcSdk: Schema.boolean().default(false), }) /** Read one Config value: a Volatile ref, or a plain value from a test. */ @@ -566,6 +584,9 @@ function makeLiveReader(ctx, config) { pwshTool: valueOf(config.pwshTool) === true, // Default OFF (v0.39.4, dsh-ops 0.3.0): FastCtx is dead upstream and dsh-ops ships stronger native ops_* file tools; an explicit true re-enables the bridge. It still stands down when dsh-ops is present. fastctxTools: valueOf(config.fastctxTools) === true, + // Default OFF: the root executor keeps its official native shape until + // the profile patch says otherwise (see src/global-ptc.js). + globalPtcSdk: valueOf(config.globalPtcSdk) === true, } } return { @@ -1843,6 +1864,50 @@ export async function apply(ctx, config = {}) { } } + // ── GLOBAL PTC SDK (row switch, default OFF) ─────────────────────────── + // `globalPtcSdk` asks for the root executor to be PTC for every agent that + // does not explicitly mount a scoped native executor. Like the persistent + // terminal adoption above, that is a PROFILE-PATCH decision (bundle patches + // are read before the profile patch file) and a row-level `disabled` that + // configEditor cannot write — so it rides the same guarded writer, with the + // same atomic write, verify-by-reread and rollback. See src/global-ptc.js + // for the full rationale and the stand-down matrix. + // + // OFF is not a no-op: it LIFTS the rows this switch wrote (matched by exact + // value), so turning the switch back off restores the official native shape + // without ever deleting a row the user shaped differently. + try { + ctx.inject(['profileContext'], (ptcPatchCtx) => { + const run = async () => { + const patchPath = ptcPatchCtx.get('profileContext')?.patchPath + if (typeof patchPath !== 'string' || patchPath.trim() === '') { + console.log(`${TAG} global PTC SDK: no profile patch path — nothing to write`) + return + } + const atomic = await resolveHostModule(ctx, '@deepseek-ai/dsh-atomic-write') + if (typeof atomic?.withFileLock !== 'function' || typeof atomic?.writeFileAtomic !== 'function') { + throw new Error('current host atomic profile-edit capability unavailable') + } + const enabled = valueOf(config.globalPtcSdk) === true + const update = () => adoptGlobalPtcPatch( + { + readFile: (file) => readFileSync(file, 'utf8'), + writeFileAtomic: (file, data) => atomic.writeFileAtomic(file, data, { mode: 0o600 }), + yaml: () => resolveHostModule(ctx, 'yaml'), + }, + { patchPath, enabled, lift: !enabled }, + ) + // Same lock target as the terminal adoption: one serialisation point + // for every profile-patch writer in this plugin. + const result = await atomic.withFileLock(join(dirname(patchPath), 'package.json'), update) + console.log(`${TAG} ${globalPtcReport(result)}`) + } + run().catch((error) => console.log(`${TAG} global PTC SDK wiring failed: ${error?.message ?? error}`)) + }) + } catch (error) { + console.log(`${TAG} global PTC SDK wiring failed: ${error?.message ?? error}`) + } + // ── dsh-better-sidebar terminal adoption (Windows only) ──────────────── // The sidebar resolves its terminal shell through the settings seam per // open; adopt it through that seam (see adoptSidebarShell for rationale). diff --git a/tests/global-ptc.mjs b/tests/global-ptc.mjs new file mode 100644 index 0000000..997c526 --- /dev/null +++ b/tests/global-ptc.mjs @@ -0,0 +1,211 @@ +/** + * dsh-gitbash-shell — global PTC SDK row switch. + * + * Covers the plan matrix (pure) and the patch writer against a real `yaml` + * document module: comment/!!js survival, atomic write, verify-by-reread, + * idempotency and the lift path. Without a resolvable `yaml` the plan matrix + * still runs and the writer part reports SKIP-YAML (same posture as the other + * host-dependent tests). + */ + +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +import { + EXECUTOR_NATIVE_ROW, + EXECUTOR_PTC_ROW, + MINIMAL_PRESET_ROW, + adoptGlobalPtcPatch, + currentGlobalPtcRows, + globalPtcReport, + planGlobalPtcAdopt, + readMinimalRow, +} from '../src/global-ptc.js' + +/** Resolve a real eemeli `yaml` from the machine (host install preferred). */ +async function realYaml() { + const candidates = [] + try { candidates.push(createRequire(import.meta.url).resolve('yaml')) } catch { /* not linked here */ } + if (process.env.DSH_PREVIEW_HOST_DIR) { + candidates.unshift(createRequire(pathToFileURL(join(process.env.DSH_PREVIEW_HOST_DIR, 'package.json'))).resolve('yaml')) + } + for (const candidate of candidates) { + try { return await import(pathToFileURL(candidate).href) } catch { /* next */ } + } + return undefined +} + +const OUR = { + native: { disabled: true }, + ptc: { disabled: false }, + minimal: { complete: false }, +} + +test('plan: the switch being off writes nothing', () => { + const plan = planGlobalPtcAdopt({ enabled: false, rows: {} }) + assert.equal(plan.action, 'skip-disabled') +}) + +test('plan: a fresh patch adopts all three rows', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: {} }) + assert.equal(plan.action, 'adopt') + assert.equal(plan.writeNative, true) + assert.equal(plan.writePtc, true) + assert.equal(plan.writeMinimal, true) +}) + +test('plan: our exact shape is unchanged', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: OUR }) + assert.equal(plan.action, 'unchanged') +}) + +test('plan: an explicit native row stands down', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: { ...OUR, native: { disabled: false } } }) + assert.equal(plan.action, 'kept-user-choice') + assert.match(plan.reason, /native root executor/) +}) + +test('plan: an explicitly disabled ptc row stands down', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: { ...OUR, ptc: { disabled: true } } }) + assert.equal(plan.action, 'kept-user-choice') + assert.match(plan.reason, /disables the PTC root executor/) +}) + +test('plan: a user-written minimal row with complete:true stands down', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: { ...OUR, minimal: { complete: true } } }) + assert.equal(plan.action, 'kept-user-choice') + assert.match(plan.reason, /preset-minimal/) +}) + +test('plan: a non-literal row is never replaced by a literal', () => { + for (const rows of [ + { ...OUR, native: { opaque: true } }, + { ...OUR, ptc: { opaque: true } }, + { ...OUR, minimal: { opaque: true } }, + ]) { + const plan = planGlobalPtcAdopt({ enabled: true, rows }) + assert.equal(plan.action, 'kept-user-choice') + assert.match(plan.reason, /non-literal/) + } +}) + +test('plan: a partial patch writes only the missing rows', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: { native: { disabled: true }, minimal: { complete: false } } }) + assert.equal(plan.action, 'adopt') + assert.equal(plan.writeNative, false) + assert.equal(plan.writePtc, true) + assert.equal(plan.writeMinimal, false) +}) + +test('readMinimalRow: absent complete reads as the official default (true)', () => { + assert.deepEqual(readMinimalRow({ config: { plugins: [{ id: 'persona', config: {} }] } }), { complete: true }) +}) + +test('readMinimalRow: a plugin list without persona is opaque', () => { + assert.deepEqual(readMinimalRow({ config: { plugins: [{ id: 'tool-fs' }] } }), { opaque: true }) +}) + +test('readMinimalRow: a non-list plugin shape is opaque', () => { + assert.deepEqual(readMinimalRow({ config: {} }), { opaque: true }) +}) + +test('report: detail wins over reason', () => { + assert.match(globalPtcReport({ status: 'write-failed', detail: 'boom', reason: 'because' }), /boom/) + assert.match(globalPtcReport({ status: 'skip-disabled', reason: 'off' }), /off/) +}) + +// ── writer ──────────────────────────────────────────────────────────────── + +async function withPatch(t, initial) { + const dir = mkdtempSync(join(tmpdir(), 'dsh-global-ptc-')) + const file = join(dir, 'cordis.patch.yml') + writeFileSync(file, initial) + t.after(() => rmSync(dir, { recursive: true, force: true })) + const yamlModule = await realYaml() + if (!yamlModule) return { skip: true } + const io = { + readFile: async () => readFileSync(file, 'utf8'), + writeFileAtomic: async (_file, data) => writeFileSync(file, data), + yaml: async () => yamlModule, + } + return { io, file, yamlModule, read: () => readFileSync(file, 'utf8') } +} + +test('writer: adopts onto a patch and verifies by reread', async (t) => { + const h = await withPatch(t, '# my patch\n[]\n') + if (h.skip) return t.skip('no yaml module available') + const result = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + assert.equal(result.status, 'adopted') + const text = h.read() + assert.match(text, /tool-executor-native/) + assert.match(text, /tool-executor-ptc/) + assert.match(text, /preset-minimal/) + assert.match(text, /complete: false/) +}) + +test('writer: a second run is idempotent', async (t) => { + const h = await withPatch(t, '[]\n') + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + const first = h.read() + const again = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + assert.equal(again.status, 'unchanged') + assert.equal(h.read(), first) +}) + +test('writer: comments survive the edit', async (t) => { + const h = await withPatch(t, '# keep me\nextends: []\nrows:\n - id: x\n# trailing\n') + if (h.skip) return t.skip('no yaml module available') + // A patch shaped as a mapping is refused, so nothing is written. + const result = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + assert.equal(result.status, 'skip-shape') + assert.equal(h.read(), '# keep me\nextends: []\nrows:\n - id: x\n# trailing\n') +}) + +test('writer: a broken YAML document is refused', async (t) => { + const h = await withPatch(t, '- id: [unclosed\n') + if (h.skip) return t.skip('no yaml module available') + const result = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + assert.ok(['skip-parse', 'skip-shape'].includes(result.status), result.status) +}) + +test('writer: lift removes our rows only', async (t) => { + const h = await withPatch(t, '- id: keep-me\n disabled: true\n') + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + assert.match(h.read(), /tool-executor-native/) + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'lifted') + const text = h.read() + assert.doesNotMatch(text, /tool-executor-native/) + assert.doesNotMatch(text, /tool-executor-ptc/) + assert.doesNotMatch(text, /preset-minimal/) + assert.match(text, /keep-me/) +}) + +test('writer: lift leaves a user row that differs from ours', async (t) => { + const h = await withPatch(t, '[]\n') + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + // The user flips the native row back on; lift must now leave it alone. + const edited = h.read().replace(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true`, `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: false`) + writeFileSync(h.file, edited) + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'lifted') + const text = h.read() + assert.match(text, new RegExp(`${EXECUTOR_NATIVE_ROW}\\n disabled: false`)) +}) + +test('writer: lift on a patch without our rows changes nothing', async (t) => { + const h = await withPatch(t, '- id: untouched\n') + if (h.skip) return t.skip('no yaml module available') + const before = h.read() + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'unchanged') + assert.equal(h.read(), before) +}) From 9b9a65780325aef4aad76e09274abb4475f0d730 Mon Sep 17 00:00:00 2001 From: MYCF711 Date: Mon, 9 Nov 2026 12:20:59 +0800 Subject: [PATCH 3/4] fix(global-ptc): ownership receipt, drop the minimal restatement, await the retry chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review P0 — OFF no longer deletes user-written rows. add src/global-ptc-ownership.js: a receipt beside the patch records exactly which row ids this switch wrote and each written row's canonical fingerprint. Lift deletes a row only when the receipt names it AND the row still fingerprints to the recorded value. No receipt means nothing is owned, so a patch the user hand-wrote before ever toggling the switch is byte-identical after OFF. Covered by the reviewer's reproducer plus an edited-after-write case and an adopt→lift round-trip. Review P1 (minimal) — the preset-minimal restatement is GONE. AGENTS §4l rejects it (freezes the official row set, and the fragment had drifted from minimal.patch.yml's persistent-bash/persistent-pwsh descriptions). The switch now writes only the two executor rows; the module header and CHANGELOG say minimal needs the deployment to own its own restatement. Review P1 (settings) — the settings card grows a Global PTC SDK row with 21 locale entries, labelled "restart to apply". Review P2 — the empty-face retry in inline-tools now returns the retry promise, so the SERIAL agent/created emission waits for the composed face instead of admitting an agent with no shell at all. npm test: 397 pass / 0 fail / 0 skip. --- src/client.js | 53 +++++ src/global-ptc-ownership.js | 120 +++++++++++ src/global-ptc.js | 388 +++++++++++++++--------------------- src/inline-tools.js | 22 +- tests/global-ptc.mjs | 149 +++++++++----- 5 files changed, 446 insertions(+), 286 deletions(-) create mode 100644 src/global-ptc-ownership.js diff --git a/src/client.js b/src/client.js index d7b3b72..f989867 100644 --- a/src/client.js +++ b/src/client.js @@ -148,6 +148,8 @@ window.__ModuleLoader__.load({ "variant.hint": "默认关闭:官方四个模式经行内工具补位直接获得 Git Bash,模式列表保持官方原样。开启后注册四个变体(standard/minimal/ptc/cordis · Git Bash)并停用官方模式的工具补位——两者互斥。钉在变体 id 上的旧会话在关闭升级后需重新选择模式;变更对新会话生效。", "experimental.label": "实验原生执行 / fail-closed", "experimental.hint": "默认开启:Windows 受限或未确定访问模式拒绝 Git Bash,并提供 gitbash_native / gitbash_to_native_path。修改立即作用于现有会话的后续调用。关闭会隐藏并禁用两个工具,恢复明确标注 UNCONFINED 的旧版 Bash:不执行 shell 文件写入限制。如保留拒绝机制,请由用户在会话访问模式控件中选择 danger-full-access。 ⚠ 工具面可见性:保存后需重启 DSH 才会在运行中会话更新;原生工具的执行门禁仍按当前开关立即生效。", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "默认关闭:开启后宿主官方的 pwsh 工具对会话可见——它是真正的 PowerShell(官方解析器自动优先 PowerShell 7),可直接用于 Windows 原生操作(注册表/服务/WMI)。关闭(默认)时该工具被隐藏,主机保持 bash 优先。无需安装任何额外组件;旧 PowerShell 7 旁路工具已随新架构退役。命令仍然首选 bash 工具。 ⚠ 工具面可见性:保存后需重启 DSH 才会在运行中会话更新;不会中途丢工具。", "fctx.label": "FastCtx 文件工具(gb_*)", @@ -236,6 +238,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Off by default: the four OFFICIAL presets get Git Bash through the inline tool patch and the roster stays official. On: register the four variants (standard/minimal/ptc/cordis · Git Bash) and stop patching the official presets — the two are exclusive. A session pinned to a variant id must re-select a preset after upgrading with the switch off. Applies to new sessions.", "experimental.label": "Experimental native execution / fail-closed", "experimental.hint": "Default ON: refuse Windows Git Bash in restricted or unresolved access modes and offer gitbash_native / gitbash_to_native_path. Changes apply to subsequent calls in existing sessions. OFF hides and disables both tools and restores legacy explicitly UNCONFINED Bash; shell file-write restrictions are NOT enforced. To keep refusal enabled, select danger-full-access in the session access-mode control yourself. ⚠ Tool-face visibility: a saved change reaches a running session only after a DSH restart; the native tools' execution gate still follows the current switch immediately.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh tool (official PowerShell)", "pwsh.hint": "Off by default: when on, the host's official pwsh tool becomes visible to sessions — REAL PowerShell (the official resolver prefers PowerShell 7 automatically) for Windows-native work (registry/services/WMI). Off (the default) hides it and keeps the host bash-first. Nothing extra to install; the retired PowerShell 7 side-channel tool is gone. Commands still prefer the bash tool. ⚠ Tool-face visibility: a saved change reaches a running session only after a DSH restart; tools are never dropped mid-session.", "fctx.label": "FastCtx file tools (gb_*)", @@ -334,6 +338,8 @@ window.__ModuleLoader__.load({ "variant.hint": "معطَّل افتراضيًا: تحصل الأنماط الرسمية الأربعة على Git Bash عبر ترقيع الأدوات داخل العملية وتبقى القائمة رسمية. عند التفعيل تُسجَّل الأنماط الأربعة المتغيّرة وتتوقف ترقيع الأنماط الرسمية — الاثنان حصريان متباددان. الجلسة المثبَّتة على معرّف متغيّر تحتاج إعادة اختيار بعد الترقية مع بقاء المفتاح معطَّلًا.", "experimental.label": "التنفيذ الأصلي التجريبي / الرفض الآمن", "experimental.hint": "مفعّل افتراضيًا: يرفض Git Bash على Windows في أوضاع الوصول المقيّدة أو غير المحدّدة، ويتيح gitbash_native وgitbash_to_native_path. يسري التغيير على الاستدعاءات التالية في الجلسات الحالية. إيقافه يخفي الأداتين ويعطّلهما، ويعيد سلوك Bash القديم المعلن بأنه UNCONFINED: لا تُفرض قيود كتابة الملفات عبر shell. للإبقاء على الرفض الآمن، اختر بنفسك danger-full-access من عنصر التحكم في وضع وصول الجلسة.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "أداة pwsh (PowerShell الرسمية)", "pwsh.hint": "مُعطَّلة افتراضيًا: عند التفعيل تصبح أداة pwsh الرسمية للمضيف مرئية للجلسات — وهي PowerShell حقيقية (يفضِّل المُحلِّل الرسمي PowerShell 7 تلقائيًا) لأعمال Windows الأصلية (السجل/الخدمات/WMI). وعند الإيقاف (الافتراضي) تُخفى الأداة ويبقى المضيف يفضِّل bash. لا حاجة لتثبيت أي شيء إضافي؛ أداة PowerShell 7 الجانبية القديمة أُوقفت مع المعمارية الجديدة. مرِّر الأوامر عبر أداة bash كالمعتاد.", "fctx.label": "أدوات ملفات FastCtx (gb_*)", @@ -422,6 +428,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Standardmäßig aus: Die vier OFFIZIELLEN Presets bekommen Git Bash durch den Inline-Tool-Patch, die Liste bleibt offiziell. Ein: Registriert die vier Varianten und stoppt das Patchen der offiziellen Presets — beides schließt sich aus. Eine am Varianten-Id festhängende Sitzung muss nach dem Upgrade neu wählen. Gilt für neue Sitzungen.", "experimental.label": "Experimentelle native Ausführung / sichere Ablehnung", "experimental.hint": "Standardmäßig EIN: Windows Git Bash wird bei eingeschränktem oder ungeklärtem Zugriffsmodus abgelehnt; gitbash_native und gitbash_to_native_path werden angeboten. Änderungen gelten für nachfolgende Aufrufe bestehender Sitzungen. AUS blendet beide Tools aus und deaktiviert sie; Bash kehrt zum ausdrücklich UNCONFINED gekennzeichneten Verhalten zurück, ohne Schreibbeschränkungen der Shell. Um die sichere Ablehnung beizubehalten, wählen Sie selbst danger-full-access in der Zugriffsmodus-Steuerung der Sitzung.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh-Werkzeug (offizielles PowerShell)", "pwsh.hint": "Standardmäßig aus: Beim Einschalten wird das offizielle pwsh-Werkzeug des Hosts für Sitzungen sichtbar — ECHTES PowerShell (der offizielle Resolver bevorzugt PowerShell 7 automatisch) für Windows-natives Arbeiten (Registry/Dienste/WMI). Im Aus-Zustand (der Standard) bleibt es verborgen und der Host bleibt bash-first. Nichts zusätzlich zu installieren; das alte PowerShell-7-Seitenkanal-Werkzeug ist mit der neuen Architektur entfallen. Befehle laufen weiterhin bevorzugt über das bash-Werkzeug.", "fctx.label": "FastCtx-Dateiwerkzeuge (gb_*)", @@ -510,6 +518,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Désactivé par défaut : les quatre presets OFFICIELS obtiennent Git Bash via le correctif d’outils en ligne et la liste reste officielle. Activé : enregistre les quatre variantes et cesse de corriger les presets officiels — les deux s’excluent. Une session attachée à un id de variante doit être rechoisie après mise à niveau. S’applique aux nouvelles sessions.", "experimental.label": "Exécution native expérimentale / refus sécurisé", "experimental.hint": "Activé par défaut : refuse Git Bash sur Windows en mode d’accès restreint ou indéterminé et propose gitbash_native / gitbash_to_native_path. Les changements concernent les appels suivants des sessions existantes. Désactiver masque et désactive les deux outils et rétablit Bash explicitement UNCONFINED, sans restrictions d’écriture de fichiers par le shell. Pour conserver le refus sécurisé, sélectionnez vous-même danger-full-access dans le contrôle du mode d’accès de la session.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Outil pwsh (PowerShell officiel)", "pwsh.hint": "Désactivé par défaut : activé, l'outil pwsh officiel de l'hôte devient visible pour les sessions — du VRAI PowerShell (le résolveur officiel préfère automatiquement PowerShell 7) pour le travail Windows natif (registre/services/WMI). Désactivé (défaut), il reste masqué et l'hôte garde bash en priorité. Rien à installer ; l'ancien outil PowerShell 7 en parallèle a été retiré avec la nouvelle architecture. Passez toujours par l'outil bash en premier.", "fctx.label": "Outils de fichiers FastCtx (gb_*)", @@ -598,6 +608,8 @@ window.__ModuleLoader__.load({ "variant.hint": "डिफ़ॉल्ट रूप से बंद: चार आधिकारिक प्रीसेट को इनलाइन टूल पैच से Git Bash मिलता है और सूची आधिकारिक रहती है। चालू: चार वेरिएंट पंजीकृत होते हैं और आधिकारिक प्रीसेट पैचिंग रुक जाती है — दोनों परस्पर अनन्य हैं। वेरिएंट id पर बंधे सत्र को अपग्रेड के बाद दोबारा चुनना पड़ेगा। नए सत्रों पर लागू।", "experimental.label": "प्रायोगिक नेटिव निष्पादन / सुरक्षित अस्वीकृति", "experimental.hint": "डिफ़ॉल्ट रूप से चालू: सीमित या अनिर्धारित पहुँच मोड में Windows Git Bash को अस्वीकार करता है और gitbash_native / gitbash_to_native_path उपलब्ध कराता है। बदलाव मौजूदा सत्रों की अगली कॉल पर लागू होते हैं। बंद करने पर दोनों टूल छिप जाते हैं और निष्क्रिय हो जाते हैं; Bash का स्पष्ट रूप से UNCONFINED पुराना व्यवहार लौट आता है, जिसमें shell की फ़ाइल लेखन पाबंदियाँ लागू नहीं होतीं। सुरक्षित अस्वीकृति बनाए रखने के लिए सत्र के पहुँच मोड नियंत्रण में स्वयं danger-full-access चुनें।", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh टूल (आधिकारिक PowerShell)", "pwsh.hint": "डिफ़ॉल्ट रूप से बंद: चालू करने पर होस्ट का आधिकारिक pwsh टूल सत्रों के लिए दिखाई देता है — असली PowerShell (आधिकारिक रिज़ॉल्वर स्वतः PowerShell 7 को प्राथमिकता देता है), Windows-नेटिव काम (रजिस्ट्री/सेवाएँ/WMI) के लिए सीधे उपयोगी। बंद (डिफ़ॉल्ट) रहने पर यह छिपा रहता है और होस्ट bash-प्राथमिकता बनाए रखता है। कुछ भी अतिरिक्त इंस्टॉल करने की ज़रूरत नहीं; पुराना PowerShell 7 साइड-चैनल टूल नए आर्किटेक्चर के साथ सेवामुक्त हो गया। कमांड अब भी पहले bash टूल से चलाएँ।", "fctx.label": "FastCtx फ़ाइल उपकरण (gb_*)", @@ -686,6 +698,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Nonaktif secara bawaan: empat preset RESMI mendapat Git Bash melalui patch alat inline dan daftar tetap resmi. Aktif: mendaftarkan empat varian dan berhenti mem-patch preset resmi — keduanya saling eksklusif. Sesi yang terikat pada id varian harus memilih ulang setelah peningkatan. Berlaku untuk sesi baru.", "experimental.label": "Eksekusi native eksperimental / penolakan aman", "experimental.hint": "Aktif secara default: menolak Git Bash Windows pada mode akses terbatas atau belum ditentukan, serta menyediakan gitbash_native / gitbash_to_native_path. Perubahan berlaku pada panggilan berikutnya dalam sesi yang sudah ada. Menonaktifkan menyembunyikan dan menonaktifkan kedua alat, lalu mengembalikan Bash lama yang secara jelas UNCONFINED, tanpa pembatasan penulisan file shell. Untuk mempertahankan penolakan aman, pilih sendiri danger-full-access pada kontrol mode akses sesi.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Alat pwsh (PowerShell resmi)", "pwsh.hint": "Nonaktif secara default: saat aktif, alat pwsh resmi milik host menjadi terlihat bagi sesi — PowerShell ASLI (resolver resmi otomatis memilih PowerShell 7) untuk kerja native Windows (registry/layanan/WMI). Nonaktif (default) menyembunyikannya dan host tetap bash-first. Tidak perlu menginstal apa pun; alat samping PowerShell 7 yang lama sudah dipensiunkan bersama arsitektur baru. Jalankan perintah tetap lewat alat bash terlebih dahulu.", "fctx.label": "Alat berkas FastCtx (gb_*)", @@ -774,6 +788,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Disattivo per impostazione predefinita: i quattro preset UFFICIALI ottengono Git Bash tramite la patch inline degli strumenti e l’elenco resta ufficiale. Attivo: registra le quattro varianti e smette di correggere i preset ufficiali — i due si escludono. Una sessione legata a un id di variante va riscelta dopo l’aggiornamento. Vale per le nuove sessioni.", "experimental.label": "Esecuzione nativa sperimentale / rifiuto sicuro", "experimental.hint": "Attivo per impostazione predefinita: rifiuta Git Bash su Windows con accesso limitato o non determinato e offre gitbash_native / gitbash_to_native_path. Le modifiche valgono per le chiamate successive delle sessioni esistenti. Disattivando si nascondono e disabilitano entrambi gli strumenti e si ripristina Bash esplicitamente UNCONFINED, senza restrizioni di scrittura dei file tramite shell. Per mantenere il rifiuto sicuro, selezionare personalmente danger-full-access nel controllo della modalità di accesso della sessione.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Strumento pwsh (PowerShell ufficiale)", "pwsh.hint": "Disattivo per impostazione predefinita: quando attivo, lo strumento pwsh ufficiale dell'host diventa visibile alle sessioni — VERO PowerShell (il resolver ufficiale preferisce automaticamente PowerShell 7) per lavoro Windows nativo (registro/servizi/WMI). Disattivo (predefinito), resta nascosto e l'host resta bash-first. Nulla da installare in più; il vecchio strumento laterale PowerShell 7 è andato in pensione con la nuova architettura. Instrada comunque i comandi prima tramite lo strumento bash.", "fctx.label": "Strumenti file FastCtx (gb_*)", @@ -862,6 +878,8 @@ window.__ModuleLoader__.load({ "variant.hint": "既定はオフ:公式 4 プリセットはインラインツールパッチで Git Bash を得られ、一覧は公式のまま。オンにすると 4 バリアントを登録し、公式プリセットへのパッチを停止(両者は排他)。バリアント id に固定されたセッションはアップグレード後に再選択が必要。新規セッションに適用。", "experimental.label": "実験的なネイティブ実行 / 安全な拒否", "experimental.hint": "既定でオン:Windows の制限付き、または未確定のアクセスモードでは Git Bash を拒否し、gitbash_native / gitbash_to_native_path を提供します。変更は既存セッションの次の呼び出しから適用されます。オフにすると両ツールを非表示・無効化し、UNCONFINED と明示された従来の Bash に戻ります。シェルによるファイル書き込み制限は適用されません。安全な拒否を維持する場合は、ユーザー自身がセッションのアクセスモード設定で danger-full-access を選択してください。", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh ツール(公式 PowerShell)", "pwsh.hint": "既定はオフ:オンにすると、ホスト公式の pwsh ツールがセッションから見えるようになります — 本物の PowerShell です(公式リゾルバが自動で PowerShell 7 を優先)。レジストリ/サービス/WMI など Windows ネイティブ作業にそのまま使えます。オフ(既定)では非表示のまま、ホストは bash 優先を保ちます。追加インストールは一切不要。旧 PowerShell 7 バイパスツールは新アーキテクチャで退役しました。コマンドは引き続き bash ツールを優先してください。", "fctx.label": "FastCtx ファイルツール(gb_*)", @@ -950,6 +968,8 @@ window.__ModuleLoader__.load({ "variant.hint": "기본 꺼짐: 공식 4개 프리셋이 인라인 도구 패치로 Git Bash를 얻으며 목록은 공식 그대로입니다. 켜면 4개 변형을 등록하고 공식 프리셋 패칭을 중단합니다(상호 배타). 변형 id 에 고정된 세션은 업그레이드 후 다시 선택해야 합니다. 새 세션에 적용.", "experimental.label": "실험적 네이티브 실행 / 안전한 거부", "experimental.hint": "기본값은 켜짐입니다. 제한되거나 확인되지 않은 접근 모드에서 Windows Git Bash를 거부하고 gitbash_native / gitbash_to_native_path를 제공합니다. 변경은 기존 세션의 다음 호출부터 적용됩니다. 끄면 두 도구를 숨기고 비활성화하며, UNCONFINED로 명시된 기존 Bash 동작을 복원합니다. 이때 셸의 파일 쓰기 제한은 적용되지 않습니다. 안전한 거부를 유지하려면 사용자가 세션 접근 모드 설정에서 직접 danger-full-access를 선택하세요.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh 도구(공식 PowerShell)", "pwsh.hint": "기본적으로 꺼짐: 켜면 호스트의 공식 pwsh 도구가 세션에 표시됩니다 — 진짜 PowerShell이며(공식 리졸버가 자동으로 PowerShell 7을 우선), 레지스트리/서비스/WMI 등 Windows 네이티브 작업에 바로 쓸 수 있습니다. 꺼짐(기본값)이면 숨겨진 채로 호스트는 bash 우선을 유지합니다. 추가 설치가 전혀 필요 없습니다. 이전 PowerShell 7 우회 도구는 새 아키텍처와 함께 은퇴했습니다. 명령은 여전히 bash 도구를 먼저 사용하세요.", "fctx.label": "FastCtx 파일 도구(gb_*)", @@ -1038,6 +1058,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Standaard uit: de vier OFFICIËLE presets krijgen Git Bash via de inline-toolpatch en de lijst blijft officieel. Aan: registreert de vier varianten en stopt het patchen van de officiële presets — sluit elkaar uit. Een sessie die aan een variant-id vastzit moet na een upgrade opnieuw kiezen. Geldt voor nieuwe sessies.", "experimental.label": "Experimentele native uitvoering / veilige weigering", "experimental.hint": "Standaard AAN: weigert Windows Git Bash bij beperkte of onbepaalde toegang en biedt gitbash_native / gitbash_to_native_path aan. Wijzigingen gelden voor volgende aanroepen in bestaande sessies. UIT verbergt en deactiveert beide tools en herstelt het expliciet UNCONFINED gemarkeerde Bash-gedrag, zonder beperkingen op schrijven via de shell. Om veilige weigering te behouden, kiest u zelf danger-full-access in de toegangsmodus van de sessie.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh-hulpmiddel (officiële PowerShell)", "pwsh.hint": "Standaard uit: ingeschakeld wordt het officiële pwsh-hulpmiddel van de host zichtbaar voor sessies — ECHTE PowerShell (de officiële resolver geeft automatisch de voorkeur aan PowerShell 7) voor Windows-natief werk (register/services/WMI). Uit (de standaard) blijft het verborgen en blijft de host bash-first. Niets extra te installeren; het oude PowerShell-7-sidechannel-hulpmiddel is met de nieuwe architectuur met pensioen. Voer opdrachten nog steeds bij voorkeur uit via het bash-hulpmiddel.", "fctx.label": "FastCtx-bestandshulpmiddelen (gb_*)", @@ -1126,6 +1148,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Domyślnie wyłączone: cztery OFICJALNE presety dostają Git Bash przez inline-owy patch narzędzi, a lista pozostaje oficjalna. Włączenie rejestruje cztery warianty i zatrzymuje patchowanie oficjalnych presetów — opcje wykluczają się. Sesja przypięta do id wariantu musi zostać wybrana ponownie po aktualizacji. Dotyczy nowych sesji.", "experimental.label": "Eksperymentalne wykonanie natywne / bezpieczna odmowa", "experimental.hint": "Domyślnie WŁĄCZONE: odmawia uruchomienia Git Bash w Windows przy ograniczonym lub nieustalonym dostępie i udostępnia gitbash_native / gitbash_to_native_path. Zmiany dotyczą kolejnych wywołań w istniejących sesjach. Wyłączenie ukrywa i dezaktywuje oba narzędzia oraz przywraca Bash jawnie oznaczony jako UNCONFINED, bez ograniczeń zapisu plików przez powłokę. Aby zachować bezpieczną odmowę, wybierz samodzielnie danger-full-access w ustawieniu trybu dostępu sesji.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Narzędzie pwsh (oficjalny PowerShell)", "pwsh.hint": "Domyślnie wyłączone: po włączeniu oficjalne narzędzie pwsh hosta staje się widoczne dla sesji — PRAWDZIWY PowerShell (oficjalny resolver automatycznie preferuje PowerShell 7) do natywnej pracy w Windows (rejestr/usługi/WMI). Wyłączone (domyślnie) pozostaje ukryte, a host pozostaje bash-first. Niczego nie trzeba dodatkowo instalować; stare narzędzie poboczne PowerShell 7 przeszło na emeryturę wraz z nową architekturą. Polecenia nadal wykonuj najpierw przez narzędzie bash.", "fctx.label": "Narzędzia plików FastCtx (gb_*)", @@ -1214,6 +1238,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Desativado por padrão: os quatro presets OFICIAIS recebem Git Bash pelo patch de ferramentas em linha e a lista permanece oficial. Ativado: registra as quatro variantes e deixa de corrigir os presets oficiais — mutuamente exclusivos. Uma sessão presa a um id de variante precisa ser reescolhida após a atualização. Vale para novas sessões.", "experimental.label": "Execução nativa experimental / recusa segura", "experimental.hint": "Ativado por padrão: recusa Git Bash no Windows em modos de acesso restritos ou indeterminados e oferece gitbash_native / gitbash_to_native_path. As alterações valem para chamadas seguintes nas sessões existentes. Desativar oculta e desativa ambas as ferramentas e restaura o Bash explicitamente UNCONFINED, sem restrições de escrita de arquivos pelo shell. Para manter a recusa segura, selecione você mesmo danger-full-access no controle do modo de acesso da sessão.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Ferramenta pwsh (PowerShell oficial)", "pwsh.hint": "Desativado por padrão: ao ativar, a ferramenta pwsh oficial do host fica visível para as sessões — PowerShell REAL (o resolvedor oficial prefere automaticamente o PowerShell 7) para trabalho nativo do Windows (registro/serviços/WMI). Desativado (o padrão), ela permanece oculta e o host continua bash-first. Nada extra para instalar; a antiga ferramenta paralela PowerShell 7 foi aposentada com a nova arquitetura. Encaminhe os comandos ainda pela ferramenta bash primeiro.", "fctx.label": "Ferramentas de arquivos FastCtx (gb_*)", @@ -1302,6 +1328,8 @@ window.__ModuleLoader__.load({ "variant.hint": "По умолчанию выключено: четыре ОФИЦИАЛЬНЫХ пресета получают Git Bash через встроенный патч инструментов, список остаётся официальным. Включено — регистрирует четыре варианта и прекращает патчить официальные пресеты (взаимоисключающе). Сессия, привязанная к id варианта, после обновления должна выбрать пресет заново. Действует для новых сессий.", "experimental.label": "Экспериментальное нативное выполнение / безопасный отказ", "experimental.hint": "По умолчанию включено: запрещает Git Bash в Windows при ограниченном или неопределённом режиме доступа и предоставляет gitbash_native / gitbash_to_native_path. Изменения действуют для следующих вызовов в текущих сеансах. Выключение скрывает и отключает оба инструмента и возвращает Bash с явной пометкой UNCONFINED: ограничения записи файлов через оболочку не применяются. Чтобы сохранить безопасный отказ, самостоятельно выберите danger-full-access в настройке режима доступа сеанса.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Инструмент pwsh (официальный PowerShell)", "pwsh.hint": "По умолчанию выключено: при включении штатный pwsh-инструмент хоста становится видимым для сессий — НАСТОЯЩИЙ PowerShell (официальный резолвер автоматически предпочитает PowerShell 7) для нативной работы Windows (реестр/службы/WMI). В выключенном состоянии (по умолчанию) он скрыт, и хост остаётся bash-приоритетным. Ничего дополнительно устанавливать не нужно; старый обходной инструмент PowerShell 7 ушёл в отставку вместе с новой архитектурой. Команды по-прежнему выполняйте сначала через инструмент bash.", "fctx.label": "Файловые инструменты FastCtx (gb_*)", @@ -1390,6 +1418,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Av som standard: de fyra OFFICIELLA presetten får Git Bash via inline-verktygspatchen och listan förblir officiell. På: registrerar de fyra varianterna och slutar patcha de officiella presetten — ömsesidigt uteslutande. En session fastnåld på ett variant-id måste väljas om efter uppgradering. Gäller nya sessioner.", "experimental.label": "Experimentell native-körning / säker avvisning", "experimental.hint": "PÅ som standard: avvisar Windows Git Bash vid begränsad eller obestämd åtkomst och erbjuder gitbash_native / gitbash_to_native_path. Ändringar gäller nästa anrop i befintliga sessioner. AV döljer och inaktiverar båda verktygen och återställer Bash med den uttryckliga märkningen UNCONFINED, utan begränsningar för filskrivning via skalet. För att behålla säker avvisning väljer du själv danger-full-access i sessionens åtkomstläge.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh-verktyget (officiell PowerShell)", "pwsh.hint": "Av som standard: när den är på blir hostens officiella pwsh-verktyg synligt för sessioner — ÄKTA PowerShell (den officiella upplösaren föredrar automatiskt PowerShell 7) för Windows-inbyggt arbete (register/tjänster/WMI). Av (standarden) hålls den dold och hosten förblir bash-först. Inget extra att installera; det gamla PowerShell 7-sidokanalverktyget har pensionerats med den nya arkitekturen. Kör kommandon fortfarande via bash-verktyget först.", "fctx.label": "FastCtx-filverktyg (gb_*)", @@ -1478,6 +1508,8 @@ window.__ModuleLoader__.load({ "variant.hint": "ปิดตามค่าเริ่มต้น: พรีเซ็ตทางการทั้งสี่ได้ Git Bash ผ่านแพตช์เครื่องมือในตัว และรายการยังเป็นทางการ เปิด: ลงทะเบียนสี่ตัวย่อยและหยุดแพตช์พรีเซ็ตทางการ — ทั้งสองไม่ใช้ร่วมกันได้ เซสชันที่ตรึงกับ id ย่อยต้องเลือกใหม่หลังอัปเกรด ใช้กับเซสชันใหม่", "experimental.label": "การเรียกใช้แบบเนทีฟเชิงทดลอง / การปฏิเสธอย่างปลอดภัย", "experimental.hint": "เปิดตามค่าเริ่มต้น: ปฏิเสธ Git Bash บน Windows ในโหมดการเข้าถึงที่จำกัดหรือยังไม่ระบุ และให้ใช้ gitbash_native / gitbash_to_native_path การเปลี่ยนแปลงมีผลกับการเรียกครั้งถัดไปในเซสชันเดิม เมื่อปิดจะซ่อนและปิดใช้งานทั้งสองเครื่องมือ พร้อมคืนพฤติกรรม Bash เดิมที่ระบุชัดว่า UNCONFINED โดยไม่บังคับข้อจำกัดการเขียนไฟล์ผ่านเชลล์ หากต้องการคงการปฏิเสธอย่างปลอดภัย ให้ผู้ใช้เลือก danger-full-access เองในตัวควบคุมโหมดการเข้าถึงของเซสชัน", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "เครื่องมือ pwsh (PowerShell ทางการ)", "pwsh.hint": "ปิดอยู่โดยค่าเริ่มต้น: เมื่อเปิด เครื่องมือ pwsh ทางการของโฮสต์จะปรากฏแก่เซสชัน — เป็น PowerShell แท้ (ตัวแก้ไขทางการเลือก PowerShell 7 ให้โดยอัตโนมัติ) ใช้ได้ทันทีสำหรับงาน Windows แบบเนทีฟ (registry/services/WMI) เมื่อปิด (ค่าเริ่มต้น) เครื่องมือจะถูกซ่อนและโฮสต์ยังให้ bash มาก่อน ไม่ต้องติดตั้งอะไรเพิ่ม; เครื่องมือข้างทาง PowerShell 7 เดิมได้เลิกใช้ไปพร้อมสถาปัตยกรรมใหม่ ส่งคำสั่งผ่านเครื่องมือ bash เป็นอันดับแรกเช่นเดิม", "fctx.label": "เครื่องมือไฟล์ FastCtx (gb_*)", @@ -1566,6 +1598,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Varsayılan olarak kapalı: dört RESMİ preset, satır içi araç yamasıyla Git Bash alır; liste resmi kalır. Açık: dört varyantı kaydeder ve resmi presetleri yamalamayı bırakır — ikisi birbirini dışlar. Bir varyant kimliğine bağlı oturum yükseltmeden sonra yeniden seçilmelidir. Yeni oturumlar için geçerlidir.", "experimental.label": "Deneysel yerel yürütme / güvenli ret", "experimental.hint": "Varsayılan olarak AÇIK: kısıtlı veya belirsiz erişim modlarında Windows Git Bash yürütmesini reddeder ve gitbash_native / gitbash_to_native_path araçlarını sunar. Değişiklikler mevcut oturumlardaki sonraki çağrılarda geçerlidir. KAPALI, iki aracı gizler ve devre dışı bırakır; açıkça UNCONFINED olarak işaretlenen eski Bash davranışını geri getirir, kabuk üzerinden dosya yazma kısıtlamaları uygulanmaz. Güvenli reddi korumak için oturumun erişim modu denetiminde danger-full-access seçimini kendiniz yapın.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "pwsh aracı (resmî PowerShell)", "pwsh.hint": "Varsayılan olarak kapalı: açıkken ana makinenin resmî pwsh aracı oturumlara görünür olur — GERÇEK PowerShell (resmî çözümleyici otomatik olarak PowerShell 7'yi tercih eder) Windows-yerel işler (kayıt defteri/hizmetler/WMI) için doğrudan kullanılabilir. Kapalı (varsayılan) kaldığında gizli kalır ve ana makine bash-öncelikli kalır. Ekstra bir şey kurmaya gerek yok; eski PowerShell 7 yan kanal aracı yeni mimariyle birlikte emekli edildi. Komutları yine de önce bash aracıyla çalıştırın.", "fctx.label": "FastCtx dosya araçları (gb_*)", @@ -1654,6 +1688,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Mặc định tắt: bốn preset CHÍNH THỨC nhận Git Bash qua bản vá công cụ nội tuyến và danh sách vẫn chính thức. Bật: đăng ký bốn biến thể và ngừng vá các preset chính thức — hai bên loại trừ nhau. Phiên đang ghim vào id biến thể cần chọn lại sau nâng cấp. Áp dụng cho phiên mới.", "experimental.label": "Thực thi native thử nghiệm / từ chối an toàn", "experimental.hint": "Mặc định BẬT: từ chối Git Bash trên Windows khi chế độ truy cập bị hạn chế hoặc chưa xác định, đồng thời cung cấp gitbash_native / gitbash_to_native_path. Thay đổi áp dụng cho các lần gọi tiếp theo trong phiên hiện có. TẮT sẽ ẩn và vô hiệu hóa cả hai công cụ, khôi phục Bash cũ được ghi rõ là UNCONFINED, không thực thi giới hạn ghi tệp qua shell. Để giữ cơ chế từ chối an toàn, người dùng tự chọn danger-full-access trong điều khiển chế độ truy cập của phiên.", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", "pwsh.label": "Công cụ pwsh (PowerShell chính thức)", "pwsh.hint": "Mặc định tắt: khi bật, công cụ pwsh chính thức của host hiển thị cho các phiên — PowerShell THẬT (bộ phân giải chính thức tự ưu tiên PowerShell 7) dùng ngay cho công việc Windows gốc (registry/services/WMI). Tắt (mặc định) thì nó vẫn bị ẩn và host vẫn ưu tiên bash. Không cần cài thêm gì; công cụ rẽ nhánh PowerShell 7 cũ đã nghỉ hưu cùng kiến trúc mới. Vẫn ưu tiên chạy lệnh qua công cụ bash trước.", "fctx.label": "Công cụ tệp FastCtx (gb_*)", @@ -1742,6 +1778,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改即時作用於現有會話的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由用戶在會話存取模式控制項選擇 danger-full-access。", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對會話可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", @@ -1830,6 +1868,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改即時作用於現有會話的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由用戶在會話存取模式控制項選擇 danger-full-access。", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對會話可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", @@ -1918,6 +1958,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改立即作用於現有工作階段的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由使用者在工作階段存取模式控制項選擇 danger-full-access。", + "gptc.label": "Global PTC SDK (restart to apply)", + "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對工作階段可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", @@ -2571,6 +2613,8 @@ window.__ModuleLoader__.load({ var experimentalOn = snap.value.experimentalNative !== false; // Default OFF (v0.39.4): must match the host's `=== true` reader. var fctxOn = snap.value.fastctxTools === true; + // Default OFF (review P1): must match the host's `=== true` reader. + var gptcOn = snap.value.globalPtcSdk === true; var modeSection = fold("sec.mode", E("div", { className: "gb-row" }, @@ -2612,6 +2656,15 @@ window.__ModuleLoader__.load({ E("button", { type: "button", className: "gb-segBtn" + (!fctxOn ? " gb-segActive" : ""), onClick: function () { if (fctxOn) writeField("fastctxTools", false); } }, t("switch.off")), ), E("p", { className: "gb-hint" }, t("fctx.hint")), + E("div", { className: "gb-row" }, + E("span", { className: "gb-rowLabel" }, t("gptc.label") + ":"), + E("span", { className: "gb-rowValue" }, gptcOn ? t("state.on") : t("state.off")), + ), + E("div", { className: "gb-seg" }, + E("button", { type: "button", className: "gb-segBtn" + (gptcOn ? " gb-segActive" : ""), onClick: function () { if (!gptcOn) writeField("globalPtcSdk", true); } }, t("switch.on")), + E("button", { type: "button", className: "gb-segBtn" + (!gptcOn ? " gb-segActive" : ""), onClick: function () { if (gptcOn) writeField("globalPtcSdk", false); } }, t("switch.off")), + ), + E("p", { className: "gb-hint" }, t("gptc.hint")), ); var peerSnap = { status: "unavailable" }; diff --git a/src/global-ptc-ownership.js b/src/global-ptc-ownership.js new file mode 100644 index 0000000..28df442 --- /dev/null +++ b/src/global-ptc-ownership.js @@ -0,0 +1,120 @@ +/** + * dsh-gitbash-shell — ownership receipt for the global PTC SDK patch rows. + * + * WHY THIS EXISTS (review P0) + * The lift path must never delete a row the USER wrote. Matching on the + * controlled field alone is not enough: a user who hand-wrote + * `tool-executor-native: { disabled: true }` before ever toggling this switch + * has a row that is byte-identical to ours, and "remove only rows whose value + * is ours" would silently delete their file (and their comments, if they had + * added any). + * + * So the writer keeps a RECEIPT next to the patch recording exactly which row + * ids it wrote and the canonical fingerprint of each written row. Lift deletes + * a row only when BOTH hold: + * 1. the receipt names that id, and + * 2. the row as it stands today still fingerprints to the recorded value. + * + * No receipt (fresh profile, or a user who never toggled the switch) means + * nothing is owned and nothing is deleted. A row the user edited afterwards + * fingerprints differently and is left alone — the switch can never take back + * a hand edit. + * + * The receipt lives beside the patch (`.gitbash-global-ptc-ownership.json`), + * is written through the same atomic writer, and is never hand-edited. + * + * @module dsh-gitbash-shell/global-ptc-ownership + */ + +import { createHash } from 'node:crypto' +import { dirname, join } from 'node:path' + +/** Receipt filename, resolved next to the profile patch it describes. */ +export const OWNERSHIP_FILENAME = '.gitbash-global-ptc-ownership.json' + +/** Row ids this switch may own. */ +export const OWNED_ROWS = ['tool-executor-native', 'tool-executor-ptc'] + +/** + * Canonical fingerprint of one written row. + * + * Key order is normalised (sorted, recursively) so a re-serialisation of the + * SAME row never looks like a user edit, while any added/removed/changed key — + * including a `config` block or a comment-bearing sibling — does. + * + * @param {unknown} row - plain data (not a yaml node). + * @returns {string} sha256 hex + */ +export function rowFingerprint(row) { + return createHash('sha256').update(stableStringify(row)).digest('hex') +} + +/** Deterministic JSON with sorted object keys. */ +function stableStringify(value) { + if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null' + if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']' + const keys = Object.keys(value).sort() + return '{' + keys.map((key) => JSON.stringify(key) + ':' + stableStringify(value[key])).join(',') + '}' +} + +/** An empty receipt: nothing owned. */ +export function emptyReceipt() { + return { version: 1, rows: {} } +} + +/** + * Validate a parsed receipt. A malformed receipt is a hard error: guessing + * ownership from a corrupt file is exactly how a user's rows get deleted. + * @param {unknown} value + * @returns {{version: 1, rows: Record}} + */ +export function validateReceipt(value) { + if (!value || typeof value !== 'object' || Array.isArray(value) || value.version !== 1) { + throw new Error('invalid global PTC ownership receipt; refusing to guess ownership') + } + if (!value.rows || typeof value.rows !== 'object' || Array.isArray(value.rows)) { + throw new Error('invalid global PTC ownership receipt rows; refusing to guess ownership') + } + for (const [id, fingerprint] of Object.entries(value.rows)) { + if (!OWNED_ROWS.includes(id)) throw new Error(`unexpected owned row ${id} in the global PTC receipt`) + if (typeof fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(fingerprint)) { + throw new Error(`malformed fingerprint for ${id} in the global PTC receipt`) + } + } + return value +} + +/** + * Build the receipt store for one profile patch. + * + * Serialised per file: two toggles landing together must not interleave a read + * with a write (the same reason the patch writer takes the profile lock). + * + * @param {{readFile: (file: string) => Promise, writeFileAtomic: (file: string, data: string) => Promise}} io + * @param {string} patchPath - the profile patch this receipt describes. + * @returns {{file: string, read: () => Promise<{version: 1, rows: Record}>, write: (value: {version: 1, rows: Record}) => Promise, run: (task: () => Promise) => Promise}} + */ +export function globalPtcOwnership(io, patchPath) { + const file = join(dirname(patchPath), OWNERSHIP_FILENAME) + let serial = Promise.resolve() + return { + file, + run(task) { + const result = serial.then(task) + serial = result.catch(() => {}) + return result + }, + async read() { + try { + return validateReceipt(JSON.parse(await io.readFile(file))) + } catch (error) { + if (error?.code === 'ENOENT') return emptyReceipt() + throw error + } + }, + async write(value) { + validateReceipt(value) + await io.writeFileAtomic(file, JSON.stringify(value, null, 2) + '\n') + }, + } +} diff --git a/src/global-ptc.js b/src/global-ptc.js index 1cf14b9..73d6159 100644 --- a/src/global-ptc.js +++ b/src/global-ptc.js @@ -6,11 +6,7 @@ * `run_code` SDK instead of a per-tool native face needs the ROOT executor * switched: `tool-executor-native` off, `tool-executor-ptc` on. That is a * profile-patch decision (bundle patches are read BEFORE the profile patch - * file), and a `preset-minimal` restatement is required on top of it because - * minimal's `persona.complete: true` erases the SDK at assembly. - * - * Hand-editing that patch is exactly what this plugin's own AGENTS.md forbids - * users to do, so the switch writes it the way the official editor would: + * file), so this module writes it the way the official editor would: * `yaml`'s parseDocument (comments and !!js expressions survive untouched), * targeted edits on known rows, a re-parse self-check, an atomic write, a * verify-by-reread and a rollback to the previous bytes on any mismatch. @@ -22,119 +18,46 @@ * the channel here is therefore the patch file, with the official editor's * own care. * + * OWNERSHIP (review P0) + * Lift never matches on a controlled field alone — see + * `src/global-ptc-ownership.js` for the receipt that records exactly which + * rows this switch wrote and their canonical fingerprints. A row the user + * hand-wrote before ever toggling the switch has no receipt entry and is + * therefore never deleted, even when it is byte-identical to ours. + * + * WHY preset-minimal IS NOT RESTATED (review P1) + * minimal's `persona.complete: true` erases the PTC SDK at assembly, so a + * minimal agent under a global PTC executor publishes `run_code` without a + * callable SDK. The only way to fix that from here is a full restatement of + * the preset, which AGENTS.md §4l rejects (it freezes the official row set at + * the copy moment and drifts on every DSH upgrade; the fragment also omitted + * the persistent-bash/persistent-pwsh descriptions). The switch therefore + * writes ONLY the two executor rows and leaves minimal alone. A deployment + * that needs minimal under PTC must own that restatement itself — the + * CHANGELOG says so explicitly. + * * WHAT IS NEVER DONE - * - A row the user wrote with a DIFFERENT value is never overwritten — every - * one of those states stands down with a reason (kept-user-choice). - * - A non-literal row (for example `disabled: !!js …`) is never replaced by - * a literal. - * - Nothing is written when the switch is OFF, and OFF never removes rows - * the user added. + * - A row the user shaped differently is never overwritten (kept-user-choice). + * - A non-literal row (`disabled: !!js …`) is never replaced by a literal. + * - Nothing is written when the switch is OFF. + * - OFF deletes only rows this switch wrote AND the user has not edited since. * * @module dsh-gitbash-shell/global-ptc */ -import { readPatchRow, findRow } from './terminal-bundle.js' +import { readPatchRow } from './terminal-bundle.js' +import { OWNED_ROWS, globalPtcOwnership, rowFingerprint } from './global-ptc-ownership.js' /** Root executor row that runs each tool natively on the wire. */ export const EXECUTOR_NATIVE_ROW = 'tool-executor-native' /** Root executor row that runs each tool through the PTC run_code SDK. */ export const EXECUTOR_PTC_ROW = 'tool-executor-ptc' -/** The preset whose complete persona erases the SDK when left at the default. */ -export const MINIMAL_PRESET_ROW = 'preset-minimal' -/** - * Official 0.2.2-rc.1 `preset-minimal` restatement. - * - * `complete: true` would restore only the persona after prompt assembly and - * erase the PTC SDK declarations, so minimal would publish `run_code` without - * any callable SDK behind it. `complete: false` lets the SDK (and the normal - * prompt sections) survive. Every other row is kept byte-for-byte aligned with - * the pinned official preset — re-align this block when DSH is upgraded. - * - * Kept as a fragment (not a hand-built node) so what lands on disk reads like - * the row a careful human would write. - */ -export const MINIMAL_PRESET_FRAGMENT = `- id: preset-minimal - name: '@deepseek-ai/dsh-agent-preset' - config: - id: minimal - order: 3 - plugins: - - id: persona - name: '@deepseek-ai/dsh-persona' - config: - prefix: You are a helpful software engineer assistant. - complete: false - includeRuntimeContext: false - - id: tool-fs - name: '@deepseek-ai/dsh-tool-fs' - config: - read: false - readImage: true - write: false - edit: false - - id: compaction - name: cordis:group - group: true - isolate: - compaction: true - config: - - id: compaction-basic - name: '@deepseek-ai/dsh-compaction-basic' - - id: command-compact - name: '@deepseek-ai/dsh-command-compact' - - id: persistent-shell - name: cordis:group - group: true - isolate: - terminals: true - config: - - id: pty - name: '@deepseek-ai/dsh-terminal' - - id: terminal-bash - name: '@deepseek-ai/dsh-terminal-bash' - disabled: !!js process.platform === 'win32' - config: - timeoutMs: 300000 - - id: persistent-bash - name: '@deepseek-ai/dsh-tool-bash-persistent' - disabled: !!js process.platform === 'win32' - config: - timeoutMs: 300000 - - id: terminal-pwsh - name: '@deepseek-ai/dsh-terminal-bash' - disabled: !!js process.platform !== 'win32' - config: - shellDialect: pwsh - timeoutMs: 300000 - - id: persistent-pwsh - name: '@deepseek-ai/dsh-tool-pwsh-persistent' - disabled: !!js process.platform !== 'win32' - config: - timeoutMs: 300000 -` - -/** - * Flatten one `preset-minimal` row into the single fact this module decides on. - * @param {unknown} row - a parsed patch entry. - * @returns {{complete?: boolean, opaque?: true}|undefined} - */ -export function readMinimalRow(row) { - if (!row || typeof row !== 'object' || Array.isArray(row)) return undefined - const config = row.config - if (!config || typeof config !== 'object' || Array.isArray(config)) return { opaque: true } - const plugins = config.plugins - // A preset row without a plugin list is not the shape we write; refuse to - // reason about it rather than appending a second, contradictory row. - if (!Array.isArray(plugins)) return { opaque: true } - const persona = plugins.find((entry) => entry && typeof entry === 'object' && entry.id === 'persona') - if (!persona) return { opaque: true } - const complete = persona?.config?.complete - if (complete === true) return { complete: true } - if (complete === false) return { complete: false } - // Unset is the official default (true), so an absent key is NOT our shape. - return complete === undefined ? { complete: true } : { opaque: true } -} +/** The value this switch writes for each row. */ +const WANTED = new Map([ + [EXECUTOR_NATIVE_ROW, true], + [EXECUTOR_PTC_ROW, false], +]) /** * Pure decision: should (and how exactly) the profile patch adopt the global @@ -143,9 +66,9 @@ export function readMinimalRow(row) { * One action plus one human reason, every state enumerable and testable — * mirroring `planTerminalBundleAdopt`. * - * @param {{enabled?: boolean, rows?: {native?: object, ptc?: object, minimal?: object}}} input - * `rows` are the FLATTENED facts (`readPatchRow` / `readMinimalRow` output). - * @returns {{action: string, reason: string, writeNative?: boolean, writePtc?: boolean, writeMinimal?: boolean}} + * @param {{enabled?: boolean, rows?: {native?: {disabled?: boolean, opaque?: true}, ptc?: {disabled?: boolean, opaque?: true}}}} input + * `rows` are the FLATTENED facts (`readPatchRow` output). + * @returns {{action: string, reason: string, writeNative?: boolean, writePtc?: boolean}} */ export function planGlobalPtcAdopt(input) { const { enabled, rows } = input ?? {} @@ -158,13 +81,12 @@ export function planGlobalPtcAdopt(input) { const native = rows?.native const ptc = rows?.ptc - const minimal = rows?.minimal // A non-literal value is somebody's condition, not our setting. - if (native?.opaque === true || ptc?.opaque === true || minimal?.opaque === true) { + if (native?.opaque === true || ptc?.opaque === true) { return { action: 'kept-user-choice', - reason: 'a root executor or preset row carries a non-literal value (for example !!js) — not replacing an explicit condition with a literal', + reason: 'a root executor row carries a non-literal value (for example !!js) — not replacing an explicit condition with a literal', } } // An explicit row that says the OPPOSITE of what the switch wants. @@ -180,20 +102,13 @@ export function planGlobalPtcAdopt(input) { reason: 'the profile patch explicitly disables the PTC root executor — not overriding an explicit user choice', } } - if (minimal !== undefined && minimal.complete !== false) { - return { - action: 'kept-user-choice', - reason: 'a user-written preset-minimal row keeps a complete persona; restating it would overwrite that choice', - } - } const writeNative = native === undefined const writePtc = ptc === undefined - const writeMinimal = minimal === undefined - if (!writeNative && !writePtc && !writeMinimal) { + if (!writeNative && !writePtc) { return { action: 'unchanged', - reason: 'the profile patch already runs every agent through the global PTC SDK (native off, ptc on, minimal restated with complete:false)', + reason: 'the profile patch already runs every agent through the global PTC SDK (native off, ptc on)', } } return { @@ -201,41 +116,38 @@ export function planGlobalPtcAdopt(input) { reason: `writing the global PTC SDK overrides (${[ writeNative ? 'native off' : undefined, writePtc ? 'ptc on' : undefined, - writeMinimal ? 'minimal restated' : undefined, ].filter(Boolean).join(', ')})`, writeNative, writePtc, - writeMinimal, } } /** - * Extract the current override rows for the three ids this module owns. - * @param {object} yaml - the eemeli yaml module (unused, kept for symmetry). + * Extract the current override rows for the two ids this module owns. * @param {object} document - a yaml parseDocument result. - * @returns {{native?: object, ptc?: object, minimal?: object, indices?: {native: number, ptc: number, minimal: number}}} + * @returns {{native?: object, ptc?: object, raw?: {native?: unknown, ptc?: unknown}, indices?: {native: number, ptc: number}}} */ -export function currentGlobalPtcRows(yaml, document) { +export function currentGlobalPtcRows(document) { const out = {} - const indices = { native: -1, ptc: -1, minimal: -1 } + const raw = {} + const indices = { native: -1, ptc: -1 } const items = document?.contents?.items - if (!Array.isArray(items)) return { ...out, indices } + if (!Array.isArray(items)) return { ...out, raw, indices } items.forEach((item, index) => { if (!item || typeof item !== 'object') return const id = typeof item.get === 'function' ? item.get('id') : item.id if (id === EXECUTOR_NATIVE_ROW) { indices.native = index - out.native = readPatchRow(toPlain(item)) + raw.native = toPlain(item) + out.native = readPatchRow(raw.native) } else if (id === EXECUTOR_PTC_ROW) { indices.ptc = index - out.ptc = readPatchRow(toPlain(item)) - } else if (id === MINIMAL_PRESET_ROW) { - indices.minimal = index - out.minimal = readMinimalRow(toPlain(item)) + raw.ptc = toPlain(item) + out.ptc = readPatchRow(raw.ptc) } }) - return { ...out, indices } + return { ...out, raw, indices } } /** Convert a yaml node to plain JS data (no anchors, no tags). */ @@ -267,6 +179,8 @@ export async function adoptGlobalPtcPatch(io, input) { return done('skip-modules', 'skip-modules', undefined, { detail: 'the yaml document module lacks parseDocument/isSeq' }) } + const ownership = globalPtcOwnership(io, patchPath) + let before try { before = await io.readFile(patchPath) @@ -289,110 +203,132 @@ export async function adoptGlobalPtcPatch(io, input) { return done('skip-shape', 'skip-shape', undefined, { detail: 'the profile patch is not a YAML sequence; refusing to edit an unknown shape' }) } - const { indices } = currentGlobalPtcRows(yamlModule, document) - - // LIFT: remove only rows whose value is EXACTLY ours. A row the user edited - // since is left alone — turning the switch off must not delete their work. + // ── LIFT ──────────────────────────────────────────────────────────────── + // Delete a row only when BOTH hold: the receipt names it (this switch wrote + // it) and the row still fingerprints to what was written (the user has not + // edited it since). No receipt ⇒ nothing is owned ⇒ nothing is deleted. if (lift === true) { - const snapshot = currentGlobalPtcRows(yamlModule, document) - const remove = [] - if (snapshot.native?.disabled === true) remove.push(indices.native) - if (snapshot.ptc?.disabled === false) remove.push(indices.ptc) - if (snapshot.minimal?.complete === false) remove.push(indices.minimal) - if (remove.length === 0) { - return done('unchanged', 'unchanged', 'no global PTC rows of ours are present; nothing changed') - } + return ownership.run(async () => { + const receipt = await ownership.read() + const { raw, indices } = currentGlobalPtcRows(document) + const remove = [] + for (const id of OWNED_ROWS) { + const recorded = receipt.rows[id] + if (typeof recorded !== 'string') continue + const row = id === EXECUTOR_NATIVE_ROW ? raw.native : raw.ptc + const index = id === EXECUTOR_NATIVE_ROW ? indices.native : indices.ptc + if (index < 0 || row === undefined) continue + if (rowFingerprint(row) !== recorded) { + return done('lift', 'kept-user-choice', `${id} was edited after this switch wrote it — leaving the row alone`) + } + remove.push([id, index]) + } + if (remove.length === 0) { + return done('unchanged', 'unchanged', 'no global PTC rows are owned by this switch; nothing changed') + } + document.contents.flow = false + // Splice from the highest index down so earlier indices still hold. + for (const [, index] of remove.slice().sort((a, b) => b[1] - a[1])) { + try { document.contents.items.splice(index, 1) } catch { /* reported below */ } + } + const after = String(document) + const check = parse(after) + if (Array.isArray(check?.errors) && check.errors.length > 0) { + return done('lift', 'write-failed', 'the edited patch did not re-parse cleanly; nothing was written') + } + try { + await io.writeFileAtomic(patchPath, after) + } catch (error) { + return done('lift', 'write-failed', undefined, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) + } + // Drop the lifted ids from the receipt so a second OFF is a no-op. + const nextRows = { ...receipt.rows } + for (const [id] of remove) delete nextRows[id] + try { + await ownership.write({ version: 1, rows: nextRows }) + } catch (error) { + // The patch is already correct; a stale receipt only means a later OFF + // re-checks fingerprints (and finds the rows gone). Report, do not revert. + return done('lift', 'lifted', 'removed the global PTC rows this switch wrote (the receipt could not be updated)', { wrote: remove.map(([id]) => id), detail: `receipt write failed: ${error?.message ?? error}` }) + } + return done('lift', 'lifted', 'removed the global PTC rows this switch wrote', { wrote: remove.map(([id]) => id) }) + }) + } + + // ── ADOPT ─────────────────────────────────────────────────────────────── + const rows = currentGlobalPtcRows(document) + const plan = planGlobalPtcAdopt({ enabled, rows }) + if (plan.action !== 'adopt') return done(plan.action, plan.action, plan.reason) + + return ownership.run(async () => { document.contents.flow = false - // Splice from the highest index down so earlier indices still hold. - for (const index of remove.sort((a, b) => b - a)) { - try { document.contents.items.splice(index, 1) } catch { /* reported below */ } + const addFragment = (text) => { + const fragment = parse(text) + if (Array.isArray(fragment?.errors) && fragment.errors.length > 0) return undefined + return fragment?.contents?.items?.[0] + } + const wrote = [] + if (plan.writeNative) { + const row = addFragment(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true\n`) + if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the native-executor row fragment did not parse; nothing was written' }) + document.add(row) + wrote.push(EXECUTOR_NATIVE_ROW) } - const after = String(document) - const check = parse(after) + if (plan.writePtc) { + const row = addFragment(`- id: ${EXECUTOR_PTC_ROW}\n disabled: false\n`) + if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the ptc-executor row fragment did not parse; nothing was written' }) + document.add(row) + wrote.push(EXECUTOR_PTC_ROW) + } + + // Self-check before touching disk: the serialized document must re-parse. + const serialized = String(document) + const check = parse(serialized) if (Array.isArray(check?.errors) && check.errors.length > 0) { - return done('lift', 'write-failed', 'the edited patch did not re-parse cleanly; nothing was written') + return done('adopt', 'write-failed', plan.reason, { detail: 'the edited patch did not re-parse cleanly; nothing was written' }) } + try { - await io.writeFileAtomic(patchPath, after) + await io.writeFileAtomic(patchPath, serialized) } catch (error) { - return done('lift', 'write-failed', undefined, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) + return done('adopt', 'write-failed', plan.reason, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) } - // Verify by re-reading what landed on disk. + + // Verify by re-reading what actually landed on disk. + let reread try { - const reread = parse(await io.readFile(patchPath)) - const rows = currentGlobalPtcRows(yamlModule, reread) - if (rows.native?.disabled === true || rows.ptc?.disabled === false || rows.minimal?.complete === false) { - await io.writeFileAtomic(patchPath, before) - return done('lift', 'write-failed', undefined, { detail: 'the written patch still carries a global PTC override; rolled back to the previous bytes' }) - } + reread = parse(await io.readFile(patchPath)) } catch (error) { try { await io.writeFileAtomic(patchPath, before) } catch { /* report the primary failure */ } - return done('lift', 'write-failed', undefined, { detail: `the verification read failed (${error?.message ?? error}); rolled back to the previous bytes` }) + return done('adopt', 'write-failed', plan.reason, { detail: `the verification read failed (${error?.message ?? error}); rolled back to the previous bytes` }) } - return done('lift', 'lifted', 'removed the global PTC rows this switch wrote', { wrote: ['lift'] }) - } - - // ADOPT - const rows = currentGlobalPtcRows(yamlModule, document) - const plan = planGlobalPtcAdopt({ enabled, rows }) - if (plan.action !== 'adopt') return done(plan.action, plan.action, plan.reason) - - document.contents.flow = false - const addFragment = (text) => { - const fragment = parse(text) - if (Array.isArray(fragment?.errors) && fragment.errors.length > 0) return undefined - return fragment?.contents?.items?.[0] - } - const wrote = [] - if (plan.writeNative) { - const row = addFragment(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true\n`) - if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the native-executor row fragment did not parse; nothing was written' }) - document.add(row) - wrote.push(EXECUTOR_NATIVE_ROW) - } - if (plan.writePtc) { - const row = addFragment(`- id: ${EXECUTOR_PTC_ROW}\n disabled: false\n`) - if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the ptc-executor row fragment did not parse; nothing was written' }) - document.add(row) - wrote.push(EXECUTOR_PTC_ROW) - } - if (plan.writeMinimal) { - const row = addFragment(MINIMAL_PRESET_FRAGMENT) - if (row === undefined) return done('adopt', 'write-failed', plan.reason, { detail: 'the preset-minimal fragment did not parse; nothing was written' }) - document.add(row) - wrote.push(MINIMAL_PRESET_ROW) - } - - // Self-check before touching disk: the serialized document must re-parse. - const serialized = String(document) - const check = parse(serialized) - if (Array.isArray(check?.errors) && check.errors.length > 0) { - return done('adopt', 'write-failed', plan.reason, { detail: 'the edited patch did not re-parse cleanly; nothing was written' }) - } - - try { - await io.writeFileAtomic(patchPath, serialized) - } catch (error) { - return done('adopt', 'write-failed', plan.reason, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) - } - - // Verify by re-reading what actually landed on disk. - try { - const reread = parse(await io.readFile(patchPath)) - const after = currentGlobalPtcRows(yamlModule, reread) - const nativeOk = after.native?.disabled === true - const ptcOk = after.ptc?.disabled === false - const minimalOk = after.minimal?.complete === false - if (!nativeOk || !ptcOk || !minimalOk) { - await io.writeFileAtomic(patchPath, before) - return done('adopt', 'write-failed', plan.reason, { detail: 'the written patch did not read back as intended; rolled back to the previous bytes' }) + const after = currentGlobalPtcRows(reread) + for (const [id, wanted] of WANTED) { + const fact = id === EXECUTOR_NATIVE_ROW ? after.native : after.ptc + if (fact?.disabled !== wanted) { + try { await io.writeFileAtomic(patchPath, before) } catch { /* report the primary failure */ } + return done('adopt', 'write-failed', plan.reason, { detail: `the written patch did not read back as intended (${id}); rolled back to the previous bytes` }) + } } - } catch (error) { - try { await io.writeFileAtomic(patchPath, before) } catch { /* report the primary failure */ } - return done('adopt', 'write-failed', plan.reason, { detail: `the verification read failed (${error?.message ?? error}); rolled back to the previous bytes` }) - } - return done('adopt', 'adopted', plan.reason, { wrote }) + // Record ownership ONLY for the rows this switch just wrote. A row that + // already existed (even with the same value) is the user's and is never + // claimed — that is what keeps OFF from deleting it. + try { + const receipt = await ownership.read() + const nextRows = { ...receipt.rows } + for (const id of wrote) { + const row = id === EXECUTOR_NATIVE_ROW ? after.raw.native : after.raw.ptc + if (row !== undefined) nextRows[id] = rowFingerprint(row) + } + await ownership.write({ version: 1, rows: nextRows }) + } catch (error) { + // The patch is written and correct; without a receipt the rows simply + // become unowned (OFF will leave them alone). Report, do not revert. + return done('adopt', 'adopted', plan.reason, { wrote, detail: `the ownership receipt could not be written (${error?.message ?? error}); OFF will leave these rows alone` }) + } + return done('adopt', 'adopted', plan.reason, { wrote }) + }) } /** diff --git a/src/inline-tools.js b/src/inline-tools.js index 002a9f6..620aa72 100644 --- a/src/inline-tools.js +++ b/src/inline-tools.js @@ -547,12 +547,22 @@ export function mountInlineTools(ctx, deps) { // a face with NEITHER tool carries no verdict. Five tries at 250ms, then // give up quietly — a slower composition simply gets no inline patch. if (attempt < 5 && !names.includes('bash') && !names.includes('pwsh')) { - const timer = setTimeout(() => { try { reconcile(agent, { attempt: attempt + 1 }) } catch { /* never crash on a timer */ } }, 250) - timer.unref?.() - const state = tracked.get(agent) - if (state) state.timer = timer - else tracked.set(agent, { ...newState(), timer }) - return + // Hand the retry chain back to the caller. `agent/created` is SERIAL and + // awaits whatever the listener returns, so a bare `return` admitted the + // agent against a face that was not wired yet (review P2). Resolve only + // after the retried reconcile settles, so the chain is awaited end to end. + return new Promise((resolve) => { + const timer = setTimeout(() => { + Promise.resolve() + .then(() => reconcile(agent, { attempt: attempt + 1 })) + .catch(() => { /* never crash on a timer */ }) + .finally(() => resolve()) + }, 250) + timer.unref?.() + const state = tracked.get(agent) + if (state) state.timer = timer + else tracked.set(agent, { ...newState(), timer }) + }) } let state = tracked.get(agent) if (state?.timer) { clearTimeout(state.timer); state.timer = undefined } diff --git a/tests/global-ptc.mjs b/tests/global-ptc.mjs index 997c526..e87d363 100644 --- a/tests/global-ptc.mjs +++ b/tests/global-ptc.mjs @@ -3,9 +3,11 @@ * * Covers the plan matrix (pure) and the patch writer against a real `yaml` * document module: comment/!!js survival, atomic write, verify-by-reread, - * idempotency and the lift path. Without a resolvable `yaml` the plan matrix - * still runs and the writer part reports SKIP-YAML (same posture as the other - * host-dependent tests). + * idempotency, and the ownership receipt (review P0) that keeps OFF from + * deleting rows the user hand-wrote before ever toggling the switch. + * + * Without a resolvable `yaml` the plan matrix still runs and the writer part + * reports SKIP-YAML (same posture as the other host-dependent tests). */ import test from 'node:test' @@ -19,13 +21,18 @@ import { pathToFileURL } from 'node:url' import { EXECUTOR_NATIVE_ROW, EXECUTOR_PTC_ROW, - MINIMAL_PRESET_ROW, adoptGlobalPtcPatch, currentGlobalPtcRows, globalPtcReport, planGlobalPtcAdopt, - readMinimalRow, } from '../src/global-ptc.js' +import { + OWNERSHIP_FILENAME, + emptyReceipt, + globalPtcOwnership, + rowFingerprint, + validateReceipt, +} from '../src/global-ptc-ownership.js' /** Resolve a real eemeli `yaml` from the machine (host install preferred). */ async function realYaml() { @@ -43,20 +50,33 @@ async function realYaml() { const OUR = { native: { disabled: true }, ptc: { disabled: false }, - minimal: { complete: false }, } +/** The reviewer's P0 reproducer: a user hand-wrote the same rows. */ +const USER_HANDWRITTEN = `- id: tool-executor-native + disabled: true +- id: tool-executor-ptc + disabled: false +- id: preset-minimal + name: '@deepseek-ai/dsh-agent-preset' + config: + plugins: + - id: persona + name: '@deepseek-ai/dsh-persona' + config: + complete: false +` + test('plan: the switch being off writes nothing', () => { const plan = planGlobalPtcAdopt({ enabled: false, rows: {} }) assert.equal(plan.action, 'skip-disabled') }) -test('plan: a fresh patch adopts all three rows', () => { +test('plan: a fresh patch adopts both executor rows', () => { const plan = planGlobalPtcAdopt({ enabled: true, rows: {} }) assert.equal(plan.action, 'adopt') assert.equal(plan.writeNative, true) assert.equal(plan.writePtc, true) - assert.equal(plan.writeMinimal, true) }) test('plan: our exact shape is unchanged', () => { @@ -76,50 +96,45 @@ test('plan: an explicitly disabled ptc row stands down', () => { assert.match(plan.reason, /disables the PTC root executor/) }) -test('plan: a user-written minimal row with complete:true stands down', () => { - const plan = planGlobalPtcAdopt({ enabled: true, rows: { ...OUR, minimal: { complete: true } } }) - assert.equal(plan.action, 'kept-user-choice') - assert.match(plan.reason, /preset-minimal/) -}) - test('plan: a non-literal row is never replaced by a literal', () => { - for (const rows of [ - { ...OUR, native: { opaque: true } }, - { ...OUR, ptc: { opaque: true } }, - { ...OUR, minimal: { opaque: true } }, - ]) { + for (const rows of [{ ...OUR, native: { opaque: true } }, { ...OUR, ptc: { opaque: true } }]) { const plan = planGlobalPtcAdopt({ enabled: true, rows }) assert.equal(plan.action, 'kept-user-choice') assert.match(plan.reason, /non-literal/) } }) -test('plan: a partial patch writes only the missing rows', () => { - const plan = planGlobalPtcAdopt({ enabled: true, rows: { native: { disabled: true }, minimal: { complete: false } } }) +test('plan: a partial patch writes only the missing row', () => { + const plan = planGlobalPtcAdopt({ enabled: true, rows: { native: { disabled: true } } }) assert.equal(plan.action, 'adopt') assert.equal(plan.writeNative, false) assert.equal(plan.writePtc, true) - assert.equal(plan.writeMinimal, false) }) -test('readMinimalRow: absent complete reads as the official default (true)', () => { - assert.deepEqual(readMinimalRow({ config: { plugins: [{ id: 'persona', config: {} }] } }), { complete: true }) +test('report: detail wins over reason', () => { + assert.match(globalPtcReport({ status: 'write-failed', detail: 'boom', reason: 'because' }), /boom/) + assert.match(globalPtcReport({ status: 'skip-disabled', reason: 'off' }), /off/) }) -test('readMinimalRow: a plugin list without persona is opaque', () => { - assert.deepEqual(readMinimalRow({ config: { plugins: [{ id: 'tool-fs' }] } }), { opaque: true }) +// ── receipt ────────────────────────────────────────────────────────────── + +test('fingerprint: key order does not matter, content does', () => { + assert.equal(rowFingerprint({ a: 1, b: { c: 2, d: 3 } }), rowFingerprint({ b: { d: 3, c: 2 }, a: 1 })) + assert.notEqual(rowFingerprint({ a: 1 }), rowFingerprint({ a: 2 })) + assert.notEqual(rowFingerprint({ a: 1 }), rowFingerprint({ a: 1, extra: true })) }) -test('readMinimalRow: a non-list plugin shape is opaque', () => { - assert.deepEqual(readMinimalRow({ config: {} }), { opaque: true }) +test('receipt: an empty receipt owns nothing', () => { + assert.deepEqual(emptyReceipt(), { version: 1, rows: {} }) }) -test('report: detail wins over reason', () => { - assert.match(globalPtcReport({ status: 'write-failed', detail: 'boom', reason: 'because' }), /boom/) - assert.match(globalPtcReport({ status: 'skip-disabled', reason: 'off' }), /off/) +test('receipt: malformed receipts are refused, never guessed', () => { + assert.throws(() => validateReceipt({ version: 2, rows: {} }), /refusing to guess/) + assert.throws(() => validateReceipt({ version: 1, rows: { 'tool-executor-native': 'nope' } }), /malformed fingerprint/) + assert.throws(() => validateReceipt({ version: 1, rows: { 'some-other-row': 'a'.repeat(64) } }), /unexpected owned row/) }) -// ── writer ──────────────────────────────────────────────────────────────── +// ── writer ────────────────────────────────────────────────────────────── async function withPatch(t, initial) { const dir = mkdtempSync(join(tmpdir(), 'dsh-global-ptc-')) @@ -129,14 +144,23 @@ async function withPatch(t, initial) { const yamlModule = await realYaml() if (!yamlModule) return { skip: true } const io = { - readFile: async () => readFileSync(file, 'utf8'), - writeFileAtomic: async (_file, data) => writeFileSync(file, data), + readFile: async (target) => readFileSync(target, 'utf8'), + writeFileAtomic: async (target, data) => writeFileSync(target, data), yaml: async () => yamlModule, } - return { io, file, yamlModule, read: () => readFileSync(file, 'utf8') } + return { + io, + dir, + file, + yamlModule, + read: () => readFileSync(file, 'utf8'), + receipt: () => { + try { return JSON.parse(readFileSync(join(dir, OWNERSHIP_FILENAME), 'utf8')) } catch { return undefined } + }, + } } -test('writer: adopts onto a patch and verifies by reread', async (t) => { +test('writer: adopts onto a patch and records ownership', async (t) => { const h = await withPatch(t, '# my patch\n[]\n') if (h.skip) return t.skip('no yaml module available') const result = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) @@ -144,8 +168,8 @@ test('writer: adopts onto a patch and verifies by reread', async (t) => { const text = h.read() assert.match(text, /tool-executor-native/) assert.match(text, /tool-executor-ptc/) - assert.match(text, /preset-minimal/) - assert.match(text, /complete: false/) + const receipt = h.receipt() + assert.deepEqual(Object.keys(receipt.rows).sort(), [EXECUTOR_NATIVE_ROW, EXECUTOR_PTC_ROW].sort()) }) test('writer: a second run is idempotent', async (t) => { @@ -158,15 +182,6 @@ test('writer: a second run is idempotent', async (t) => { assert.equal(h.read(), first) }) -test('writer: comments survive the edit', async (t) => { - const h = await withPatch(t, '# keep me\nextends: []\nrows:\n - id: x\n# trailing\n') - if (h.skip) return t.skip('no yaml module available') - // A patch shaped as a mapping is refused, so nothing is written. - const result = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) - assert.equal(result.status, 'skip-shape') - assert.equal(h.read(), '# keep me\nextends: []\nrows:\n - id: x\n# trailing\n') -}) - test('writer: a broken YAML document is refused', async (t) => { const h = await withPatch(t, '- id: [unclosed\n') if (h.skip) return t.skip('no yaml module available') @@ -174,7 +189,7 @@ test('writer: a broken YAML document is refused', async (t) => { assert.ok(['skip-parse', 'skip-shape'].includes(result.status), result.status) }) -test('writer: lift removes our rows only', async (t) => { +test('writer: lift removes only rows this switch wrote', async (t) => { const h = await withPatch(t, '- id: keep-me\n disabled: true\n') if (h.skip) return t.skip('no yaml module available') await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) @@ -184,21 +199,28 @@ test('writer: lift removes our rows only', async (t) => { const text = h.read() assert.doesNotMatch(text, /tool-executor-native/) assert.doesNotMatch(text, /tool-executor-ptc/) - assert.doesNotMatch(text, /preset-minimal/) assert.match(text, /keep-me/) }) -test('writer: lift leaves a user row that differs from ours', async (t) => { +test('writer: P0 — OFF never deletes a user-handwritten same-value row', async (t) => { + const h = await withPatch(t, USER_HANDWRITTEN) + if (h.skip) return t.skip('no yaml module available') + const before = h.read() + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'unchanged', 'a patch this switch never wrote has nothing to lift') + assert.equal(h.read(), before, 'the user file must be byte-identical') +}) + +test('writer: P0 — OFF leaves a row the user edited after the switch wrote it', async (t) => { const h = await withPatch(t, '[]\n') if (h.skip) return t.skip('no yaml module available') await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) - // The user flips the native row back on; lift must now leave it alone. + // The user then flips the native row back on (a different value). const edited = h.read().replace(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true`, `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: false`) writeFileSync(h.file, edited) const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) - assert.equal(lifted.status, 'lifted') - const text = h.read() - assert.match(text, new RegExp(`${EXECUTOR_NATIVE_ROW}\\n disabled: false`)) + assert.equal(lifted.status, 'kept-user-choice') + assert.match(h.read(), new RegExp(`${EXECUTOR_NATIVE_ROW}\\n disabled: false`)) }) test('writer: lift on a patch without our rows changes nothing', async (t) => { @@ -209,3 +231,22 @@ test('writer: lift on a patch without our rows changes nothing', async (t) => { assert.equal(lifted.status, 'unchanged') assert.equal(h.read(), before) }) + +test('writer: adopt then lift round-trips to the original bytes', async (t) => { + const h = await withPatch(t, '- id: keep-me\n disabled: true\n') + if (h.skip) return t.skip('no yaml module available') + const before = h.read() + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(h.read(), before) + assert.deepEqual(h.receipt().rows, {}) +}) + +test('ownership: a receipt store reads back what it wrote', async (t) => { + const h = await withPatch(t, '[]\n') + if (h.skip) return t.skip('no yaml module available') + const store = globalPtcOwnership(h.io, h.file) + assert.deepEqual(await store.read(), { version: 1, rows: {} }) + await store.write({ version: 1, rows: { [EXECUTOR_NATIVE_ROW]: 'a'.repeat(64) } }) + assert.deepEqual((await store.read()).rows, { [EXECUTOR_NATIVE_ROW]: 'a'.repeat(64) }) +}) From 567cb1df0eb1574c9d26e7424975cb904b8a5ef3 Mon Sep 17 00:00:00 2001 From: MYCF711 Date: Mon, 9 Nov 2026 14:07:54 +0800 Subject: [PATCH 4/4] fix(global-ptc): preserve comments and the root executor invariant Address the second PR review round. - Receipt fingerprints now include YAML comment/commentBefore tokens as well as canonical row data, so a comment-only user edit blocks lifting. - Lift simulates the base composition (native ON, PTC OFF) plus retained rows before every splice. It never creates zero/two root executors; opaque rows fail closed. Safe partial lifts remain possible, missing siblings work in both directions, and stale receipt entries are pruned. - Disable/uninstall awaits in-flight adoption and lifts under the same profile lock, logging rather than failing host shutdown. - Empty-face retries use per-attempt records. A superseding reconcile chains the old created promise to its replacement (including the Bash mount); dispose settles directly. Timer firing cannot resolve early. - Settings copy is genuinely localized in all 21 locales and documents the minimal limitation. README/README_EN/AGENTS/CHANGELOG now describe ownership, disposal and composition safety; stale comments are fixed. Validation: npm test 410/410, node --check, git diff --check and npm pack --dry-run. Independent read-only re-review: APPROVE, no blockers. --- AGENTS.md | 18 ++++++ CHANGELOG.md | 12 ++++ README.md | 20 +++++++ README_EN.md | 24 ++++++++ src/client.js | 82 +++++++++++++-------------- src/global-ptc-ownership.js | 42 ++++++++++++-- src/global-ptc.js | 83 +++++++++++++++++++++------ src/index.js | 73 +++++++++++++++--------- src/inline-tools.js | 61 ++++++++++++++++---- tests/global-ptc-created.mjs | 107 +++++++++++++++++++++++++++++++++-- tests/global-ptc.mjs | 107 ++++++++++++++++++++++++++++++++++- 11 files changed, 522 insertions(+), 107 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d9b1854..d8ae0f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -649,6 +649,24 @@ `tests/runtime-preview.mjs` 的 eager-slot 用例需要已安装宿主(host-loader),不在 `npm test` 内。本机无 Windows 时不得声称真机通过,CHANGELOG 必须写明该边界。 +4n. **全局 PTC SDK 开关与所有权(`globalPtcSdk`,默认关)**:该开关只写 profile patch 的两个 root executor 行 + (`tool-executor-native: disabled true`、`tool-executor-ptc: disabled false`),不是 volatile 实时切换, + 重启 DSH 后生效。**绝不复述 `preset-minimal`**:它的 `persona.complete: true` 会抹掉 SDK,minimal 不在 + 本开关支持范围内;需要 minimal + PTC 的部署必须自己维护 preset 覆盖,README/设置卡必须明说。 + - 所有权由 patch 旁 `.gitbash-global-ptc-ownership.json` 记录:只登记本次实际新增的行 id 与指纹; + 用户原先手写的同值行不认领。指纹 = 规范化数据 + YAML AST 上全部 `comment/commentBefore` + (含嵌套 key/value),因为 `toJSON()` 会丢注释;只改注释同样视为用户编辑。 + - OFF / 禁用 / 卸载按 receipt 逐行 lift:只有 receipt 认领且当前指纹仍相同的行才可删;splice 前必须按 + base 默认(native 开、PTC 关)+ 将保留的行模拟最终组合,**无法证明恰好一个 enabled executor 就不删** + (含 opaque)。一行被改不阻断另一行「组合安全」的撤回,`lifted-partial` 必须列出需人工处理的行; + 会造成双 executor / 无 executor 时对应行与 receipt 保留并返回 `kept-user-choice`。无 receipt、 + 指纹不符、receipt 损坏均不得猜测删除。卸载 dispose 先等正在进行的 adopt,再用同一把 profile 文件锁 + lift,失败只 log。 + - 回归必须覆盖:用户手写同值、后续改值、只加注释、部分 lift、adopt→lift 字节回滚、receipt 生命周期、 + 禁用/卸载接线。改 `agent/created` 的 PTC readiness 时另跑 `tests/global-ptc-created.mjs` 的空 face、 + 取消与 dispose 用例;supersede 清 timer 后旧 Promise 必须链到替代 reconcile / Bash mount,dispose 才可 + 直接 settle;正常 firing 不得提前 settle 下一 attempt。 + ## 当前宿主测试与配置所有权 - 宿主预览使用真实 Native/Ptc executor,`tools.execute({calls,...})` 返回 `results`;不得用旧单调用签名或给 registry 打兼容补丁。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cee017..536241e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,18 @@ > 倒序排列,新版本条目在最上面。条目格式:`## vX.Y.Z — YYYY-MM-DD` + 类型(feat / fix / docs / chore)+ 要点 + 相关链接。 > 纪律见 AGENTS.md「变更记录纪律」:发版前先更新本文件并随版本提交;事故复盘、复现与真机验证记录也记在这里。 +## Unreleased — 2026-11-09 + +**类型**: feat / fix / docs(全局 PTC SDK 开关与配置所有权;版本号由维护者发版时统一 bump) + +- **新增 `globalPtcSdk`(默认关)**:设置卡控制 profile root executor,只写 `tool-executor-native: disabled true` 与 `tool-executor-ptc: disabled false`;未显式挂 scoped native executor 的 agent 经 `run_code` SDK 使用工具,SDK 含 Git Bash、无独立 pwsh。写入 profile patch,重启 DSH 后生效。 +- **minimal 明确不支持**:不复述 `preset-minimal`;其 `persona.complete: true` 会抹掉 SDK。需要 minimal + PTC 的部署自行维护 preset 覆盖。README / README_EN / AGENTS 与 21 门设置卡文案同步说明。 +- **ownership receipt 防数据丢失**:patch 旁 `.gitbash-global-ptc-ownership.json` 只登记实际写入的行与「规范化数据 + YAML 注释」指纹。用户手写同值行不认领;后续改值、加配置或只加注释都视为用户编辑并保留。receipt 损坏 fail-closed。 +- **组合安全的逐行恢复与卸载还原**:OFF / 禁用 / 卸载按 receipt 逐行 lift;splice 前按 base 默认与保留行模拟,必须恰好一个 enabled executor,否则保留对应行与 receipt 并返回 `kept-user-choice`。一行被改不阻断另一行「组合安全」的撤回;部分恢复返回 `lifted-partial` 并指出需人工处理的行。dispose 等正在进行的 adopt 后,以同一把 profile 锁执行 lift,失败只记录日志。 +- **PTC 首步 readiness**:`agent/created` 等待 bash 挂载;空 face 的有界重试也纳入等待。每次重试有独立 record;superseding reconcile 清 timer 后让旧 created Promise 等待本次 reconcile / Bash mount,dispose 才直接 settle;正常 firing 先按 identity 摘除当前 record,避免提前 resolve 下一 attempt。 +- **验证**:Windows / Node 24 完整 `npm test` **410 pass / 0 fail / 0 skip**;空 face 正常重试、foreign bash 取消、替代 reconcile 挂 Bash、agent dispose 取消四例,以及 comment-only / missing-sibling 的双向 executor 组合回归已进 CI。真实 Desktop GUI、真实模型及卸载时的整实例 patch 回滚仍未验证。 +- **链接**:[PR #44](https://github.com/KannaKuron/dsh-gitbash-shell/pull/44) + ## v0.51.0 — 2026-11-07 **类型**: feat / fix(运行时正确性、配置所有权与提示词投影;宿主基线仍为 0.2.2-rc.1) diff --git a/README.md b/README.md index 334629c..4404b7d 100644 --- a/README.md +++ b/README.md @@ -359,6 +359,26 @@ preset 会被插件自动清理;宿主官方 PowerShell 执行器原样保留( **依赖版本**:去重开关本体在**本插件 ≥ 0.25.0**;对方的协作能力在 **dsh-ptc-cordis-preset ≥ 0.14.0**。 +### 全局 PTC SDK:`globalPtcSdk`(默认关) + +设置卡的「Global PTC SDK」控制 profile 的 root executor。默认关闭时不新增任何覆盖;开启后写入 +`tool-executor-native: { disabled: true }` 与 `tool-executor-ptc: { disabled: false }`,让未显式挂载 +scoped native executor 的 agent 通过 `run_code` SDK 调用工具。SDK 内含本插件的 Git Bash,不发布独立 `pwsh`。 +**写入的是 profile patch,重启 DSH 后生效。** + +- **不覆盖 `preset-minimal`**:minimal 的 `persona.complete: true` 会在 prompt 组装时抹掉 PTC SDK, + 得到没有可用 SDK 的 `run_code`。本开关**不支持 minimal**,也不替部署复述该 preset(避免冻结官方行集); + 要在 minimal 使用 PTC,需自行维护对应 preset 覆盖,或改用 standard/ptc/cordis。 +- **只撤回自己写且未被改过的行**:patch 旁的 `.gitbash-global-ptc-ownership.json` 记录本开关写入的行 id + 与「数据 + YAML 注释」指纹。关闭开关、禁用或卸载插件时,只 lift receipt 认领且指纹仍一致的行; + 用户手写同值行、后续改值/加配置/加注释的行一律保留。 +- **组合安全的逐行恢复**:splice 前按 base 默认(native 开、PTC 关)与将保留的行模拟最终组合, + **必须仍能证明恰好一个 enabled executor**;一行被用户改过时,另一行只有在满足该不变量时才撤回, + 结果日志为 `lifted-partial`。若删除会造成「双 executor」或「无 executor」(含 `!!js` 等无法判定的行), + 对应行及其 receipt 都保留,日志返回 `kept-user-choice` 并明确要求手工处理。 +- **失败边界**:receipt 损坏时拒绝猜测所有权;写入与回读使用宿主原子写和同一把 profile 文件锁, + 校验失败回滚原 patch 字节。卸载恢复只记录失败日志,不阻断宿主关闭。 + ### run_code 后端开关:`pythonRuntime`(默认关,v0.26.0) dsh 有一个**实验性 CPython 后端**用于 PTC 的 `run_code` diff --git a/README_EN.md b/README_EN.md index 4ded977..cd413f4 100644 --- a/README_EN.md +++ b/README_EN.md @@ -300,6 +300,30 @@ there is no second copy and no sync logic. **Versions**: the switch itself ships in **this plugin ≥ 0.25.0**; the peer's cooperation capability ships in **dsh-ptc-cordis-preset ≥ 0.14.0**. +### Global PTC SDK: `globalPtcSdk` (off by default) + +The settings card's **Global PTC SDK** row controls the profile's root executor. OFF adopts no overrides. +ON writes `tool-executor-native: { disabled: true }` and `tool-executor-ptc: { disabled: false }`, so agents +without an explicitly scoped native executor reach their tools through the `run_code` SDK. The SDK carries +this plugin's Git Bash and no separate `pwsh`. **This writes the profile patch and takes effect after a DSH restart.** + +- **`preset-minimal` is not covered**: its `persona.complete: true` erases the PTC SDK during prompt assembly, + leaving `run_code` without a usable SDK. This switch does not support minimal and deliberately does not restate + that preset (which would freeze the official rows). Own a deployment-specific preset override for minimal, + or use standard/ptc/cordis instead. +- **Only unchanged rows written by this switch are lifted**: `.gitbash-global-ptc-ownership.json` beside the patch + records the written row ids and their data-plus-YAML-comment fingerprints. Turning the switch off, disabling, + or uninstalling the plugin lifts only receipted rows whose fingerprints still match. Handwritten same-value rows, + later value/config edits, and added comments are preserved. +- **Per-row recovery is composition-safe**: before splicing, the writer simulates the base defaults (native ON, PTC OFF) + plus every retained row and requires exactly one enabled executor. An untouched sibling is lifted only when that + invariant still holds; partial recovery logs `lifted-partial`. If a removal would leave two executors or none + (including an opaque `!!js` row), the row and its receipt stay in place and the log says `kept-user-choice` + with manual review required. +- **Failure boundaries**: a malformed receipt fails closed. Patch writes and rereads use the host atomic writer and + the same profile lock; a verification failure restores the previous patch bytes. Disposal logs lift failures without + blocking host shutdown. + ## POSIX path dialect (introduced in v0.7.0, gated by the `posixPaths` switch) While commands default to this plugin's own Git Bash tool on Windows, the diff --git a/src/client.js b/src/client.js index f989867..55bd4e7 100644 --- a/src/client.js +++ b/src/client.js @@ -148,8 +148,8 @@ window.__ModuleLoader__.load({ "variant.hint": "默认关闭:官方四个模式经行内工具补位直接获得 Git Bash,模式列表保持官方原样。开启后注册四个变体(standard/minimal/ptc/cordis · Git Bash)并停用官方模式的工具补位——两者互斥。钉在变体 id 上的旧会话在关闭升级后需重新选择模式;变更对新会话生效。", "experimental.label": "实验原生执行 / fail-closed", "experimental.hint": "默认开启:Windows 受限或未确定访问模式拒绝 Git Bash,并提供 gitbash_native / gitbash_to_native_path。修改立即作用于现有会话的后续调用。关闭会隐藏并禁用两个工具,恢复明确标注 UNCONFINED 的旧版 Bash:不执行 shell 文件写入限制。如保留拒绝机制,请由用户在会话访问模式控件中选择 danger-full-access。 ⚠ 工具面可见性:保存后需重启 DSH 才会在运行中会话更新;原生工具的执行门禁仍按当前开关立即生效。", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "全局 PTC SDK(重启后生效)", + "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),未显式挂 scoped native executor 的 agent 通过 run_code SDK 调用工具;SDK 含 Git Bash,无独立 pwsh。重启 DSH 后生效。不支持 preset-minimal:其 complete persona 会抹掉 SDK,需自行维护 preset 覆盖。关闭、禁用或卸载时只撤回本开关写入且未被改过的行;用户手写或后来修改(含注释)的行保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "默认关闭:开启后宿主官方的 pwsh 工具对会话可见——它是真正的 PowerShell(官方解析器自动优先 PowerShell 7),可直接用于 Windows 原生操作(注册表/服务/WMI)。关闭(默认)时该工具被隐藏,主机保持 bash 优先。无需安装任何额外组件;旧 PowerShell 7 旁路工具已随新架构退役。命令仍然首选 bash 工具。 ⚠ 工具面可见性:保存后需重启 DSH 才会在运行中会话更新;不会中途丢工具。", "fctx.label": "FastCtx 文件工具(gb_*)", @@ -239,7 +239,7 @@ window.__ModuleLoader__.load({ "experimental.label": "Experimental native execution / fail-closed", "experimental.hint": "Default ON: refuse Windows Git Bash in restricted or unresolved access modes and offer gitbash_native / gitbash_to_native_path. Changes apply to subsequent calls in existing sessions. OFF hides and disables both tools and restores legacy explicitly UNCONFINED Bash; shell file-write restrictions are NOT enforced. To keep refusal enabled, select danger-full-access in the session access-mode control yourself. ⚠ Tool-face visibility: a saved change reaches a running session only after a DSH restart; the native tools' execution gate still follows the current switch immediately.", "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.hint": "Off by default. Writes the profile patch: native off and ptc on, so agents without an explicitly scoped native executor use the run_code SDK, with Git Bash and no separate pwsh. Takes effect after a DSH restart. preset-minimal is NOT supported: its complete persona erases the SDK; maintain your own preset override for minimal. OFF, disable, or uninstall lifts only rows written by this switch and left unchanged; handwritten or later-edited rows, including comments, are preserved.", "pwsh.label": "pwsh tool (official PowerShell)", "pwsh.hint": "Off by default: when on, the host's official pwsh tool becomes visible to sessions — REAL PowerShell (the official resolver prefers PowerShell 7 automatically) for Windows-native work (registry/services/WMI). Off (the default) hides it and keeps the host bash-first. Nothing extra to install; the retired PowerShell 7 side-channel tool is gone. Commands still prefer the bash tool. ⚠ Tool-face visibility: a saved change reaches a running session only after a DSH restart; tools are never dropped mid-session.", "fctx.label": "FastCtx file tools (gb_*)", @@ -338,8 +338,8 @@ window.__ModuleLoader__.load({ "variant.hint": "معطَّل افتراضيًا: تحصل الأنماط الرسمية الأربعة على Git Bash عبر ترقيع الأدوات داخل العملية وتبقى القائمة رسمية. عند التفعيل تُسجَّل الأنماط الأربعة المتغيّرة وتتوقف ترقيع الأنماط الرسمية — الاثنان حصريان متباددان. الجلسة المثبَّتة على معرّف متغيّر تحتاج إعادة اختيار بعد الترقية مع بقاء المفتاح معطَّلًا.", "experimental.label": "التنفيذ الأصلي التجريبي / الرفض الآمن", "experimental.hint": "مفعّل افتراضيًا: يرفض Git Bash على Windows في أوضاع الوصول المقيّدة أو غير المحدّدة، ويتيح gitbash_native وgitbash_to_native_path. يسري التغيير على الاستدعاءات التالية في الجلسات الحالية. إيقافه يخفي الأداتين ويعطّلهما، ويعيد سلوك Bash القديم المعلن بأنه UNCONFINED: لا تُفرض قيود كتابة الملفات عبر shell. للإبقاء على الرفض الآمن، اختر بنفسك danger-full-access من عنصر التحكم في وضع وصول الجلسة.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "PTC SDK العام (يسري بعد إعادة التشغيل)", + "gptc.hint": "معطّل افتراضيًا. يكتب في profile patch: إيقاف native وتشغيل ptc، بحيث يستخدم العملاء دون native executor محدد النطاق run_code SDK مع Git Bash ودون pwsh مستقل. يسري بعد إعادة تشغيل DSH. لا يدعم preset-minimal: فـ complete persona يمحو SDK؛ صُن تجاوز preset الخاص بك لـ minimal. عند الإيقاف أو التعطيل أو الإزالة، تُسحب فقط الصفوف التي كتبها هذا المفتاح ولم تتغير؛ أما الصفوف المكتوبة يدويًا أو المعدلة لاحقًا، بما فيها التعليقات، فتبقى.", "pwsh.label": "أداة pwsh (PowerShell الرسمية)", "pwsh.hint": "مُعطَّلة افتراضيًا: عند التفعيل تصبح أداة pwsh الرسمية للمضيف مرئية للجلسات — وهي PowerShell حقيقية (يفضِّل المُحلِّل الرسمي PowerShell 7 تلقائيًا) لأعمال Windows الأصلية (السجل/الخدمات/WMI). وعند الإيقاف (الافتراضي) تُخفى الأداة ويبقى المضيف يفضِّل bash. لا حاجة لتثبيت أي شيء إضافي؛ أداة PowerShell 7 الجانبية القديمة أُوقفت مع المعمارية الجديدة. مرِّر الأوامر عبر أداة bash كالمعتاد.", "fctx.label": "أدوات ملفات FastCtx (gb_*)", @@ -428,8 +428,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Standardmäßig aus: Die vier OFFIZIELLEN Presets bekommen Git Bash durch den Inline-Tool-Patch, die Liste bleibt offiziell. Ein: Registriert die vier Varianten und stoppt das Patchen der offiziellen Presets — beides schließt sich aus. Eine am Varianten-Id festhängende Sitzung muss nach dem Upgrade neu wählen. Gilt für neue Sitzungen.", "experimental.label": "Experimentelle native Ausführung / sichere Ablehnung", "experimental.hint": "Standardmäßig EIN: Windows Git Bash wird bei eingeschränktem oder ungeklärtem Zugriffsmodus abgelehnt; gitbash_native und gitbash_to_native_path werden angeboten. Änderungen gelten für nachfolgende Aufrufe bestehender Sitzungen. AUS blendet beide Tools aus und deaktiviert sie; Bash kehrt zum ausdrücklich UNCONFINED gekennzeichneten Verhalten zurück, ohne Schreibbeschränkungen der Shell. Um die sichere Ablehnung beizubehalten, wählen Sie selbst danger-full-access in der Zugriffsmodus-Steuerung der Sitzung.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Globales PTC SDK (nach Neustart wirksam)", + "gptc.hint": "Standardmäßig aus. Schreibt in den Profile-Patch: native aus und ptc an; Agents ohne explizit begrenzten nativen Executor nutzen das run_code SDK mit Git Bash und ohne separates pwsh. Wirksam nach einem DSH-Neustart. preset-minimal wird NICHT unterstützt: dessen complete persona löscht das SDK; pflege für minimal einen eigenen Preset-Override. Aus, Deaktivieren oder Deinstallieren entfernt nur unveränderte Zeilen dieses Schalters; handgeschriebene oder später bearbeitete Zeilen, einschließlich Kommentaren, bleiben erhalten.", "pwsh.label": "pwsh-Werkzeug (offizielles PowerShell)", "pwsh.hint": "Standardmäßig aus: Beim Einschalten wird das offizielle pwsh-Werkzeug des Hosts für Sitzungen sichtbar — ECHTES PowerShell (der offizielle Resolver bevorzugt PowerShell 7 automatisch) für Windows-natives Arbeiten (Registry/Dienste/WMI). Im Aus-Zustand (der Standard) bleibt es verborgen und der Host bleibt bash-first. Nichts zusätzlich zu installieren; das alte PowerShell-7-Seitenkanal-Werkzeug ist mit der neuen Architektur entfallen. Befehle laufen weiterhin bevorzugt über das bash-Werkzeug.", "fctx.label": "FastCtx-Dateiwerkzeuge (gb_*)", @@ -518,8 +518,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Désactivé par défaut : les quatre presets OFFICIELS obtiennent Git Bash via le correctif d’outils en ligne et la liste reste officielle. Activé : enregistre les quatre variantes et cesse de corriger les presets officiels — les deux s’excluent. Une session attachée à un id de variante doit être rechoisie après mise à niveau. S’applique aux nouvelles sessions.", "experimental.label": "Exécution native expérimentale / refus sécurisé", "experimental.hint": "Activé par défaut : refuse Git Bash sur Windows en mode d’accès restreint ou indéterminé et propose gitbash_native / gitbash_to_native_path. Les changements concernent les appels suivants des sessions existantes. Désactiver masque et désactive les deux outils et rétablit Bash explicitement UNCONFINED, sans restrictions d’écriture de fichiers par le shell. Pour conserver le refus sécurisé, sélectionnez vous-même danger-full-access dans le contrôle du mode d’accès de la session.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "SDK PTC global (après redémarrage)", + "gptc.hint": "Désactivé par défaut. Écrit dans le patch de profil : native désactivé et ptc activé ; les agents sans exécuteur natif explicitement limité utilisent le SDK run_code, avec Git Bash et sans pwsh séparé. Effet après redémarrage de DSH. preset-minimal n’est PAS pris en charge : sa persona complete efface le SDK ; conservez votre propre dérogation de preset pour minimal. Désactivation ou désinstallation ne retire que les lignes écrites par ce commutateur et restées inchangées ; les lignes manuscrites ou modifiées ensuite, commentaires compris, sont conservées.", "pwsh.label": "Outil pwsh (PowerShell officiel)", "pwsh.hint": "Désactivé par défaut : activé, l'outil pwsh officiel de l'hôte devient visible pour les sessions — du VRAI PowerShell (le résolveur officiel préfère automatiquement PowerShell 7) pour le travail Windows natif (registre/services/WMI). Désactivé (défaut), il reste masqué et l'hôte garde bash en priorité. Rien à installer ; l'ancien outil PowerShell 7 en parallèle a été retiré avec la nouvelle architecture. Passez toujours par l'outil bash en premier.", "fctx.label": "Outils de fichiers FastCtx (gb_*)", @@ -608,8 +608,8 @@ window.__ModuleLoader__.load({ "variant.hint": "डिफ़ॉल्ट रूप से बंद: चार आधिकारिक प्रीसेट को इनलाइन टूल पैच से Git Bash मिलता है और सूची आधिकारिक रहती है। चालू: चार वेरिएंट पंजीकृत होते हैं और आधिकारिक प्रीसेट पैचिंग रुक जाती है — दोनों परस्पर अनन्य हैं। वेरिएंट id पर बंधे सत्र को अपग्रेड के बाद दोबारा चुनना पड़ेगा। नए सत्रों पर लागू।", "experimental.label": "प्रायोगिक नेटिव निष्पादन / सुरक्षित अस्वीकृति", "experimental.hint": "डिफ़ॉल्ट रूप से चालू: सीमित या अनिर्धारित पहुँच मोड में Windows Git Bash को अस्वीकार करता है और gitbash_native / gitbash_to_native_path उपलब्ध कराता है। बदलाव मौजूदा सत्रों की अगली कॉल पर लागू होते हैं। बंद करने पर दोनों टूल छिप जाते हैं और निष्क्रिय हो जाते हैं; Bash का स्पष्ट रूप से UNCONFINED पुराना व्यवहार लौट आता है, जिसमें shell की फ़ाइल लेखन पाबंदियाँ लागू नहीं होतीं। सुरक्षित अस्वीकृति बनाए रखने के लिए सत्र के पहुँच मोड नियंत्रण में स्वयं danger-full-access चुनें।", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "ग्लोबल PTC SDK (रीस्टार्ट के बाद लागू)", + "gptc.hint": "डिफ़ॉल्ट रूप से बंद। profile patch में native बंद और ptc चालू लिखता है, जिससे स्पष्ट scoped native executor न रखने वाले agents run_code SDK का उपयोग करें; SDK में Git Bash है, अलग pwsh नहीं। DSH रीस्टार्ट के बाद लागू होता है। preset-minimal समर्थित नहीं है: उसका complete persona SDK मिटा देता है; minimal के लिए अपना preset override बनाए रखें। बंद, अक्षम या अनइंस्टॉल करने पर केवल इस स्विच द्वारा लिखी गई अपरिवर्तित पंक्तियाँ हटती हैं; हस्तलिखित या बाद में बदली गई पंक्तियाँ, टिप्पणियों सहित, सुरक्षित रहती हैं।", "pwsh.label": "pwsh टूल (आधिकारिक PowerShell)", "pwsh.hint": "डिफ़ॉल्ट रूप से बंद: चालू करने पर होस्ट का आधिकारिक pwsh टूल सत्रों के लिए दिखाई देता है — असली PowerShell (आधिकारिक रिज़ॉल्वर स्वतः PowerShell 7 को प्राथमिकता देता है), Windows-नेटिव काम (रजिस्ट्री/सेवाएँ/WMI) के लिए सीधे उपयोगी। बंद (डिफ़ॉल्ट) रहने पर यह छिपा रहता है और होस्ट bash-प्राथमिकता बनाए रखता है। कुछ भी अतिरिक्त इंस्टॉल करने की ज़रूरत नहीं; पुराना PowerShell 7 साइड-चैनल टूल नए आर्किटेक्चर के साथ सेवामुक्त हो गया। कमांड अब भी पहले bash टूल से चलाएँ।", "fctx.label": "FastCtx फ़ाइल उपकरण (gb_*)", @@ -698,8 +698,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Nonaktif secara bawaan: empat preset RESMI mendapat Git Bash melalui patch alat inline dan daftar tetap resmi. Aktif: mendaftarkan empat varian dan berhenti mem-patch preset resmi — keduanya saling eksklusif. Sesi yang terikat pada id varian harus memilih ulang setelah peningkatan. Berlaku untuk sesi baru.", "experimental.label": "Eksekusi native eksperimental / penolakan aman", "experimental.hint": "Aktif secara default: menolak Git Bash Windows pada mode akses terbatas atau belum ditentukan, serta menyediakan gitbash_native / gitbash_to_native_path. Perubahan berlaku pada panggilan berikutnya dalam sesi yang sudah ada. Menonaktifkan menyembunyikan dan menonaktifkan kedua alat, lalu mengembalikan Bash lama yang secara jelas UNCONFINED, tanpa pembatasan penulisan file shell. Untuk mempertahankan penolakan aman, pilih sendiri danger-full-access pada kontrol mode akses sesi.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "PTC SDK global (berlaku setelah mulai ulang)", + "gptc.hint": "Nonaktif secara default. Menulis ke profile patch: native mati dan ptc aktif, sehingga agen tanpa native executor tercakup eksplisit memakai run_code SDK dengan Git Bash dan tanpa pwsh terpisah. Berlaku setelah DSH dimulai ulang. preset-minimal TIDAK didukung: complete persona-nya menghapus SDK; kelola override preset sendiri untuk minimal. Saat dimatikan, dinonaktifkan, atau dicopot, hanya baris yang ditulis sakelar ini dan belum diubah yang ditarik; baris tulisan tangan atau yang diubah kemudian, termasuk komentar, tetap dipertahankan.", "pwsh.label": "Alat pwsh (PowerShell resmi)", "pwsh.hint": "Nonaktif secara default: saat aktif, alat pwsh resmi milik host menjadi terlihat bagi sesi — PowerShell ASLI (resolver resmi otomatis memilih PowerShell 7) untuk kerja native Windows (registry/layanan/WMI). Nonaktif (default) menyembunyikannya dan host tetap bash-first. Tidak perlu menginstal apa pun; alat samping PowerShell 7 yang lama sudah dipensiunkan bersama arsitektur baru. Jalankan perintah tetap lewat alat bash terlebih dahulu.", "fctx.label": "Alat berkas FastCtx (gb_*)", @@ -788,8 +788,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Disattivo per impostazione predefinita: i quattro preset UFFICIALI ottengono Git Bash tramite la patch inline degli strumenti e l’elenco resta ufficiale. Attivo: registra le quattro varianti e smette di correggere i preset ufficiali — i due si escludono. Una sessione legata a un id di variante va riscelta dopo l’aggiornamento. Vale per le nuove sessioni.", "experimental.label": "Esecuzione nativa sperimentale / rifiuto sicuro", "experimental.hint": "Attivo per impostazione predefinita: rifiuta Git Bash su Windows con accesso limitato o non determinato e offre gitbash_native / gitbash_to_native_path. Le modifiche valgono per le chiamate successive delle sessioni esistenti. Disattivando si nascondono e disabilitano entrambi gli strumenti e si ripristina Bash esplicitamente UNCONFINED, senza restrizioni di scrittura dei file tramite shell. Per mantenere il rifiuto sicuro, selezionare personalmente danger-full-access nel controllo della modalità di accesso della sessione.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "SDK PTC globale (richiede riavvio)", + "gptc.hint": "Disattivato per impostazione predefinita. Scrive nel patch del profilo: native disattivato e ptc attivato, così gli agent senza executor nativo esplicitamente delimitato usano l’SDK run_code con Git Bash e senza pwsh separato. Ha effetto dopo il riavvio di DSH. preset-minimal NON è supportato: la sua persona complete cancella l’SDK; mantieni un override del preset dedicato per minimal. Disattivazione o disinstallazione ritira solo le righe scritte da questo interruttore e rimaste invariate; le righe scritte a mano o modificate dopo, inclusi i commenti, sono conservate.", "pwsh.label": "Strumento pwsh (PowerShell ufficiale)", "pwsh.hint": "Disattivo per impostazione predefinita: quando attivo, lo strumento pwsh ufficiale dell'host diventa visibile alle sessioni — VERO PowerShell (il resolver ufficiale preferisce automaticamente PowerShell 7) per lavoro Windows nativo (registro/servizi/WMI). Disattivo (predefinito), resta nascosto e l'host resta bash-first. Nulla da installare in più; il vecchio strumento laterale PowerShell 7 è andato in pensione con la nuova architettura. Instrada comunque i comandi prima tramite lo strumento bash.", "fctx.label": "Strumenti file FastCtx (gb_*)", @@ -878,8 +878,8 @@ window.__ModuleLoader__.load({ "variant.hint": "既定はオフ:公式 4 プリセットはインラインツールパッチで Git Bash を得られ、一覧は公式のまま。オンにすると 4 バリアントを登録し、公式プリセットへのパッチを停止(両者は排他)。バリアント id に固定されたセッションはアップグレード後に再選択が必要。新規セッションに適用。", "experimental.label": "実験的なネイティブ実行 / 安全な拒否", "experimental.hint": "既定でオン:Windows の制限付き、または未確定のアクセスモードでは Git Bash を拒否し、gitbash_native / gitbash_to_native_path を提供します。変更は既存セッションの次の呼び出しから適用されます。オフにすると両ツールを非表示・無効化し、UNCONFINED と明示された従来の Bash に戻ります。シェルによるファイル書き込み制限は適用されません。安全な拒否を維持する場合は、ユーザー自身がセッションのアクセスモード設定で danger-full-access を選択してください。", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "グローバル PTC SDK(再起動後に適用)", + "gptc.hint": "デフォルトはオフ。profile patch に native 無効・ptc 有効を書き込み、明示的にスコープされた native executor を持たない agent が run_code SDK 経由でツールを呼び出すようにします。SDK には Git Bash が含まれ、独立した pwsh はありません。DSH の再起動後に有効になります。preset-minimal はサポート外です。complete persona が SDK を消去するため、minimal 用の preset オーバーライドは自分で維持してください。オフ・無効化・アンインストール時には、このスイッチが書き込み、その後変更されていない行だけを撤回します。手書きまたは後で編集された行(コメントを含む)は保持されます。", "pwsh.label": "pwsh ツール(公式 PowerShell)", "pwsh.hint": "既定はオフ:オンにすると、ホスト公式の pwsh ツールがセッションから見えるようになります — 本物の PowerShell です(公式リゾルバが自動で PowerShell 7 を優先)。レジストリ/サービス/WMI など Windows ネイティブ作業にそのまま使えます。オフ(既定)では非表示のまま、ホストは bash 優先を保ちます。追加インストールは一切不要。旧 PowerShell 7 バイパスツールは新アーキテクチャで退役しました。コマンドは引き続き bash ツールを優先してください。", "fctx.label": "FastCtx ファイルツール(gb_*)", @@ -968,8 +968,8 @@ window.__ModuleLoader__.load({ "variant.hint": "기본 꺼짐: 공식 4개 프리셋이 인라인 도구 패치로 Git Bash를 얻으며 목록은 공식 그대로입니다. 켜면 4개 변형을 등록하고 공식 프리셋 패칭을 중단합니다(상호 배타). 변형 id 에 고정된 세션은 업그레이드 후 다시 선택해야 합니다. 새 세션에 적용.", "experimental.label": "실험적 네이티브 실행 / 안전한 거부", "experimental.hint": "기본값은 켜짐입니다. 제한되거나 확인되지 않은 접근 모드에서 Windows Git Bash를 거부하고 gitbash_native / gitbash_to_native_path를 제공합니다. 변경은 기존 세션의 다음 호출부터 적용됩니다. 끄면 두 도구를 숨기고 비활성화하며, UNCONFINED로 명시된 기존 Bash 동작을 복원합니다. 이때 셸의 파일 쓰기 제한은 적용되지 않습니다. 안전한 거부를 유지하려면 사용자가 세션 접근 모드 설정에서 직접 danger-full-access를 선택하세요.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "전역 PTC SDK(재시작 후 적용)", + "gptc.hint": "기본값은 꺼짐입니다. profile patch에 native 끄기 및 ptc 켜기를 기록하여 명시적으로 범위가 지정된 native executor가 없는 agent가 run_code SDK를 통해 도구를 호출하게 합니다. SDK에는 Git Bash가 포함되고 별도의 pwsh는 없습니다. DSH를 재시작하면 적용됩니다. preset-minimal은 지원하지 않습니다. complete persona가 SDK를 지우므로 minimal용 preset 재정의는 직접 유지해야 합니다. 끄기, 비활성화 또는 제거 시 이 스위치가 쓰고 이후 변경되지 않은 행만 철회합니다. 손으로 썼거나 나중에 수정한 행(주석 포함)은 유지됩니다.", "pwsh.label": "pwsh 도구(공식 PowerShell)", "pwsh.hint": "기본적으로 꺼짐: 켜면 호스트의 공식 pwsh 도구가 세션에 표시됩니다 — 진짜 PowerShell이며(공식 리졸버가 자동으로 PowerShell 7을 우선), 레지스트리/서비스/WMI 등 Windows 네이티브 작업에 바로 쓸 수 있습니다. 꺼짐(기본값)이면 숨겨진 채로 호스트는 bash 우선을 유지합니다. 추가 설치가 전혀 필요 없습니다. 이전 PowerShell 7 우회 도구는 새 아키텍처와 함께 은퇴했습니다. 명령은 여전히 bash 도구를 먼저 사용하세요.", "fctx.label": "FastCtx 파일 도구(gb_*)", @@ -1058,8 +1058,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Standaard uit: de vier OFFICIËLE presets krijgen Git Bash via de inline-toolpatch en de lijst blijft officieel. Aan: registreert de vier varianten en stopt het patchen van de officiële presets — sluit elkaar uit. Een sessie die aan een variant-id vastzit moet na een upgrade opnieuw kiezen. Geldt voor nieuwe sessies.", "experimental.label": "Experimentele native uitvoering / veilige weigering", "experimental.hint": "Standaard AAN: weigert Windows Git Bash bij beperkte of onbepaalde toegang en biedt gitbash_native / gitbash_to_native_path aan. Wijzigingen gelden voor volgende aanroepen in bestaande sessies. UIT verbergt en deactiveert beide tools en herstelt het expliciet UNCONFINED gemarkeerde Bash-gedrag, zonder beperkingen op schrijven via de shell. Om veilige weigering te behouden, kiest u zelf danger-full-access in de toegangsmodus van de sessie.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Globale PTC SDK (van kracht na herstart)", + "gptc.hint": "Standaard uit. Schrijft in de profile patch: native uit en ptc aan, zodat agents zonder expliciet begrensde native executor tools via de run_code SDK aanroepen, met Git Bash en zonder afzonderlijke pwsh. Wordt actief na een DSH-herstart. preset-minimal wordt NIET ondersteund: de complete persona wist de SDK; onderhoud zelf een preset-override voor minimal. Uitschakelen of verwijderen trekt alleen ongewijzigde rijen van deze schakelaar terug; handgeschreven of later bewerkte rijen, inclusief opmerkingen, blijven behouden.", "pwsh.label": "pwsh-hulpmiddel (officiële PowerShell)", "pwsh.hint": "Standaard uit: ingeschakeld wordt het officiële pwsh-hulpmiddel van de host zichtbaar voor sessies — ECHTE PowerShell (de officiële resolver geeft automatisch de voorkeur aan PowerShell 7) voor Windows-natief werk (register/services/WMI). Uit (de standaard) blijft het verborgen en blijft de host bash-first. Niets extra te installeren; het oude PowerShell-7-sidechannel-hulpmiddel is met de nieuwe architectuur met pensioen. Voer opdrachten nog steeds bij voorkeur uit via het bash-hulpmiddel.", "fctx.label": "FastCtx-bestandshulpmiddelen (gb_*)", @@ -1148,8 +1148,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Domyślnie wyłączone: cztery OFICJALNE presety dostają Git Bash przez inline-owy patch narzędzi, a lista pozostaje oficjalna. Włączenie rejestruje cztery warianty i zatrzymuje patchowanie oficjalnych presetów — opcje wykluczają się. Sesja przypięta do id wariantu musi zostać wybrana ponownie po aktualizacji. Dotyczy nowych sesji.", "experimental.label": "Eksperymentalne wykonanie natywne / bezpieczna odmowa", "experimental.hint": "Domyślnie WŁĄCZONE: odmawia uruchomienia Git Bash w Windows przy ograniczonym lub nieustalonym dostępie i udostępnia gitbash_native / gitbash_to_native_path. Zmiany dotyczą kolejnych wywołań w istniejących sesjach. Wyłączenie ukrywa i dezaktywuje oba narzędzia oraz przywraca Bash jawnie oznaczony jako UNCONFINED, bez ograniczeń zapisu plików przez powłokę. Aby zachować bezpieczną odmowę, wybierz samodzielnie danger-full-access w ustawieniu trybu dostępu sesji.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Globalny PTC SDK (wymaga restartu)", + "gptc.hint": "Domyślnie wyłączone. Zapisuje w profile patch: native wyłączone i ptc włączone, dzięki czemu agenci bez jawnie ograniczonego native executor wywołują narzędzia przez run_code SDK z Git Bash i bez osobnego pwsh. Działa po restarcie DSH. preset-minimal NIE jest obsługiwany: jego complete persona usuwa SDK; utrzymuj własne nadpisanie presetu dla minimal. Wyłączenie lub odinstalowanie usuwa tylko niezmienione wiersze tego przełącznika; ręcznie napisane lub później zmienione wiersze, w tym komentarze, są zachowywane.", "pwsh.label": "Narzędzie pwsh (oficjalny PowerShell)", "pwsh.hint": "Domyślnie wyłączone: po włączeniu oficjalne narzędzie pwsh hosta staje się widoczne dla sesji — PRAWDZIWY PowerShell (oficjalny resolver automatycznie preferuje PowerShell 7) do natywnej pracy w Windows (rejestr/usługi/WMI). Wyłączone (domyślnie) pozostaje ukryte, a host pozostaje bash-first. Niczego nie trzeba dodatkowo instalować; stare narzędzie poboczne PowerShell 7 przeszło na emeryturę wraz z nową architekturą. Polecenia nadal wykonuj najpierw przez narzędzie bash.", "fctx.label": "Narzędzia plików FastCtx (gb_*)", @@ -1238,8 +1238,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Desativado por padrão: os quatro presets OFICIAIS recebem Git Bash pelo patch de ferramentas em linha e a lista permanece oficial. Ativado: registra as quatro variantes e deixa de corrigir os presets oficiais — mutuamente exclusivos. Uma sessão presa a um id de variante precisa ser reescolhida após a atualização. Vale para novas sessões.", "experimental.label": "Execução nativa experimental / recusa segura", "experimental.hint": "Ativado por padrão: recusa Git Bash no Windows em modos de acesso restritos ou indeterminados e oferece gitbash_native / gitbash_to_native_path. As alterações valem para chamadas seguintes nas sessões existentes. Desativar oculta e desativa ambas as ferramentas e restaura o Bash explicitamente UNCONFINED, sem restrições de escrita de arquivos pelo shell. Para manter a recusa segura, selecione você mesmo danger-full-access no controle do modo de acesso da sessão.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "SDK PTC global (aplicar após reiniciar)", + "gptc.hint": "Desativado por padrão. Escreve no profile patch: native desativado e ptc ativado, para que agentes sem executor nativo explicitamente delimitado usem o run_code SDK com Git Bash e sem pwsh separado. Entra em vigor após reiniciar o DSH. preset-minimal NÃO é suportado: a persona complete apaga o SDK; mantenha sua própria substituição de preset para minimal. Desativar ou desinstalar remove apenas linhas escritas por este interruptor e não alteradas depois; linhas manuscritas ou editadas posteriormente, incluindo comentários, são preservadas.", "pwsh.label": "Ferramenta pwsh (PowerShell oficial)", "pwsh.hint": "Desativado por padrão: ao ativar, a ferramenta pwsh oficial do host fica visível para as sessões — PowerShell REAL (o resolvedor oficial prefere automaticamente o PowerShell 7) para trabalho nativo do Windows (registro/serviços/WMI). Desativado (o padrão), ela permanece oculta e o host continua bash-first. Nada extra para instalar; a antiga ferramenta paralela PowerShell 7 foi aposentada com a nova arquitetura. Encaminhe os comandos ainda pela ferramenta bash primeiro.", "fctx.label": "Ferramentas de arquivos FastCtx (gb_*)", @@ -1328,8 +1328,8 @@ window.__ModuleLoader__.load({ "variant.hint": "По умолчанию выключено: четыре ОФИЦИАЛЬНЫХ пресета получают Git Bash через встроенный патч инструментов, список остаётся официальным. Включено — регистрирует четыре варианта и прекращает патчить официальные пресеты (взаимоисключающе). Сессия, привязанная к id варианта, после обновления должна выбрать пресет заново. Действует для новых сессий.", "experimental.label": "Экспериментальное нативное выполнение / безопасный отказ", "experimental.hint": "По умолчанию включено: запрещает Git Bash в Windows при ограниченном или неопределённом режиме доступа и предоставляет gitbash_native / gitbash_to_native_path. Изменения действуют для следующих вызовов в текущих сеансах. Выключение скрывает и отключает оба инструмента и возвращает Bash с явной пометкой UNCONFINED: ограничения записи файлов через оболочку не применяются. Чтобы сохранить безопасный отказ, самостоятельно выберите danger-full-access в настройке режима доступа сеанса.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Глобальный PTC SDK (после перезапуска)", + "gptc.hint": "По умолчанию выключено. Записывает в profile patch: native выключен, ptc включён, поэтому агенты без явно ограниченного native executor вызывают инструменты через run_code SDK с Git Bash и без отдельного pwsh. Действует после перезапуска DSH. preset-minimal НЕ поддерживается: его complete persona стирает SDK; поддерживайте собственное переопределение preset для minimal. При выключении, отключении или удалении убираются только неизменённые строки этого переключателя; написанные вручную или изменённые строки, включая комментарии, сохраняются.", "pwsh.label": "Инструмент pwsh (официальный PowerShell)", "pwsh.hint": "По умолчанию выключено: при включении штатный pwsh-инструмент хоста становится видимым для сессий — НАСТОЯЩИЙ PowerShell (официальный резолвер автоматически предпочитает PowerShell 7) для нативной работы Windows (реестр/службы/WMI). В выключенном состоянии (по умолчанию) он скрыт, и хост остаётся bash-приоритетным. Ничего дополнительно устанавливать не нужно; старый обходной инструмент PowerShell 7 ушёл в отставку вместе с новой архитектурой. Команды по-прежнему выполняйте сначала через инструмент bash.", "fctx.label": "Файловые инструменты FastCtx (gb_*)", @@ -1418,8 +1418,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Av som standard: de fyra OFFICIELLA presetten får Git Bash via inline-verktygspatchen och listan förblir officiell. På: registrerar de fyra varianterna och slutar patcha de officiella presetten — ömsesidigt uteslutande. En session fastnåld på ett variant-id måste väljas om efter uppgradering. Gäller nya sessioner.", "experimental.label": "Experimentell native-körning / säker avvisning", "experimental.hint": "PÅ som standard: avvisar Windows Git Bash vid begränsad eller obestämd åtkomst och erbjuder gitbash_native / gitbash_to_native_path. Ändringar gäller nästa anrop i befintliga sessioner. AV döljer och inaktiverar båda verktygen och återställer Bash med den uttryckliga märkningen UNCONFINED, utan begränsningar för filskrivning via skalet. För att behålla säker avvisning väljer du själv danger-full-access i sessionens åtkomstläge.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Global PTC SDK (kräver omstart)", + "gptc.hint": "Av som standard. Skriver till profile patch: native av och ptc på, så att agenter utan uttryckligt avgränsad native executor anropar verktyg via run_code SDK med Git Bash och utan separat pwsh. Gäller efter omstart av DSH. preset-minimal stöds INTE: dess complete persona raderar SDK:t; underhåll en egen preset-override för minimal. Av, inaktivering eller avinstallation tar bara bort oförändrade rader som denna switch skrev; handskrivna eller senare redigerade rader, inklusive kommentarer, behålls.", "pwsh.label": "pwsh-verktyget (officiell PowerShell)", "pwsh.hint": "Av som standard: när den är på blir hostens officiella pwsh-verktyg synligt för sessioner — ÄKTA PowerShell (den officiella upplösaren föredrar automatiskt PowerShell 7) för Windows-inbyggt arbete (register/tjänster/WMI). Av (standarden) hålls den dold och hosten förblir bash-först. Inget extra att installera; det gamla PowerShell 7-sidokanalverktyget har pensionerats med den nya arkitekturen. Kör kommandon fortfarande via bash-verktyget först.", "fctx.label": "FastCtx-filverktyg (gb_*)", @@ -1508,8 +1508,8 @@ window.__ModuleLoader__.load({ "variant.hint": "ปิดตามค่าเริ่มต้น: พรีเซ็ตทางการทั้งสี่ได้ Git Bash ผ่านแพตช์เครื่องมือในตัว และรายการยังเป็นทางการ เปิด: ลงทะเบียนสี่ตัวย่อยและหยุดแพตช์พรีเซ็ตทางการ — ทั้งสองไม่ใช้ร่วมกันได้ เซสชันที่ตรึงกับ id ย่อยต้องเลือกใหม่หลังอัปเกรด ใช้กับเซสชันใหม่", "experimental.label": "การเรียกใช้แบบเนทีฟเชิงทดลอง / การปฏิเสธอย่างปลอดภัย", "experimental.hint": "เปิดตามค่าเริ่มต้น: ปฏิเสธ Git Bash บน Windows ในโหมดการเข้าถึงที่จำกัดหรือยังไม่ระบุ และให้ใช้ gitbash_native / gitbash_to_native_path การเปลี่ยนแปลงมีผลกับการเรียกครั้งถัดไปในเซสชันเดิม เมื่อปิดจะซ่อนและปิดใช้งานทั้งสองเครื่องมือ พร้อมคืนพฤติกรรม Bash เดิมที่ระบุชัดว่า UNCONFINED โดยไม่บังคับข้อจำกัดการเขียนไฟล์ผ่านเชลล์ หากต้องการคงการปฏิเสธอย่างปลอดภัย ให้ผู้ใช้เลือก danger-full-access เองในตัวควบคุมโหมดการเข้าถึงของเซสชัน", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "PTC SDK ส่วนกลาง (มีผลหลังรีสตาร์ต)", + "gptc.hint": "ปิดเป็นค่าเริ่มต้น เขียนลงใน profile patch: ปิด native และเปิด ptc เพื่อให้ agent ที่ไม่มี native executor แบบจำกัดขอบเขตอย่างชัดเจนเรียกเครื่องมือผ่าน run_code SDK ซึ่งมี Git Bash และไม่มี pwsh แยกต่างหาก มีผลหลังรีสตาร์ต DSH ไม่รองรับ preset-minimal: complete persona จะลบ SDK ออก โปรดดูแล preset override สำหรับ minimal ด้วยตนเอง เมื่อปิด ปิดใช้งาน หรือถอนการติดตั้ง จะยกเลิกเฉพาะบรรทัดที่สวิตช์นี้เขียนและยังไม่ได้แก้ไข บรรทัดที่เขียนเองหรือแก้ไขภายหลัง รวมถึงความคิดเห็น จะถูกเก็บไว้", "pwsh.label": "เครื่องมือ pwsh (PowerShell ทางการ)", "pwsh.hint": "ปิดอยู่โดยค่าเริ่มต้น: เมื่อเปิด เครื่องมือ pwsh ทางการของโฮสต์จะปรากฏแก่เซสชัน — เป็น PowerShell แท้ (ตัวแก้ไขทางการเลือก PowerShell 7 ให้โดยอัตโนมัติ) ใช้ได้ทันทีสำหรับงาน Windows แบบเนทีฟ (registry/services/WMI) เมื่อปิด (ค่าเริ่มต้น) เครื่องมือจะถูกซ่อนและโฮสต์ยังให้ bash มาก่อน ไม่ต้องติดตั้งอะไรเพิ่ม; เครื่องมือข้างทาง PowerShell 7 เดิมได้เลิกใช้ไปพร้อมสถาปัตยกรรมใหม่ ส่งคำสั่งผ่านเครื่องมือ bash เป็นอันดับแรกเช่นเดิม", "fctx.label": "เครื่องมือไฟล์ FastCtx (gb_*)", @@ -1598,8 +1598,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Varsayılan olarak kapalı: dört RESMİ preset, satır içi araç yamasıyla Git Bash alır; liste resmi kalır. Açık: dört varyantı kaydeder ve resmi presetleri yamalamayı bırakır — ikisi birbirini dışlar. Bir varyant kimliğine bağlı oturum yükseltmeden sonra yeniden seçilmelidir. Yeni oturumlar için geçerlidir.", "experimental.label": "Deneysel yerel yürütme / güvenli ret", "experimental.hint": "Varsayılan olarak AÇIK: kısıtlı veya belirsiz erişim modlarında Windows Git Bash yürütmesini reddeder ve gitbash_native / gitbash_to_native_path araçlarını sunar. Değişiklikler mevcut oturumlardaki sonraki çağrılarda geçerlidir. KAPALI, iki aracı gizler ve devre dışı bırakır; açıkça UNCONFINED olarak işaretlenen eski Bash davranışını geri getirir, kabuk üzerinden dosya yazma kısıtlamaları uygulanmaz. Güvenli reddi korumak için oturumun erişim modu denetiminde danger-full-access seçimini kendiniz yapın.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "Genel PTC SDK (yeniden başlatma gerekir)", + "gptc.hint": "Varsayılan olarak kapalı. profile patch içine yazar: native kapalı ve ptc açık; açıkça kapsamlandırılmış native executor bulunmayan agent’lar Git Bash içeren ve ayrı pwsh içermeyen run_code SDK üzerinden araçları çağırır. DSH yeniden başlatıldığında geçerli olur. preset-minimal desteklenMEZ: complete persona SDK’yı siler; minimal için kendi preset geçersiz kılmanızı koruyun. Kapatma, devre dışı bırakma veya kaldırma yalnızca bu anahtarın değiştirilmemiş satırlarını geri alır; el yazısıyla eklenen veya sonradan düzenlenen satırlar, yorumlar dahil, korunur.", "pwsh.label": "pwsh aracı (resmî PowerShell)", "pwsh.hint": "Varsayılan olarak kapalı: açıkken ana makinenin resmî pwsh aracı oturumlara görünür olur — GERÇEK PowerShell (resmî çözümleyici otomatik olarak PowerShell 7'yi tercih eder) Windows-yerel işler (kayıt defteri/hizmetler/WMI) için doğrudan kullanılabilir. Kapalı (varsayılan) kaldığında gizli kalır ve ana makine bash-öncelikli kalır. Ekstra bir şey kurmaya gerek yok; eski PowerShell 7 yan kanal aracı yeni mimariyle birlikte emekli edildi. Komutları yine de önce bash aracıyla çalıştırın.", "fctx.label": "FastCtx dosya araçları (gb_*)", @@ -1688,8 +1688,8 @@ window.__ModuleLoader__.load({ "variant.hint": "Mặc định tắt: bốn preset CHÍNH THỨC nhận Git Bash qua bản vá công cụ nội tuyến và danh sách vẫn chính thức. Bật: đăng ký bốn biến thể và ngừng vá các preset chính thức — hai bên loại trừ nhau. Phiên đang ghim vào id biến thể cần chọn lại sau nâng cấp. Áp dụng cho phiên mới.", "experimental.label": "Thực thi native thử nghiệm / từ chối an toàn", "experimental.hint": "Mặc định BẬT: từ chối Git Bash trên Windows khi chế độ truy cập bị hạn chế hoặc chưa xác định, đồng thời cung cấp gitbash_native / gitbash_to_native_path. Thay đổi áp dụng cho các lần gọi tiếp theo trong phiên hiện có. TẮT sẽ ẩn và vô hiệu hóa cả hai công cụ, khôi phục Bash cũ được ghi rõ là UNCONFINED, không thực thi giới hạn ghi tệp qua shell. Để giữ cơ chế từ chối an toàn, người dùng tự chọn danger-full-access trong điều khiển chế độ truy cập của phiên.", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "Off by default. Writes the profile patch: the root executor becomes PTC (native off, ptc on), so every agent that does not explicitly mount a scoped native executor reaches its tools through the run_code SDK, which carries Git Bash and no separate pwsh. Takes effect after a DSH restart. Turning it off removes only the rows this switch wrote; hand-written rows are never touched.", + "gptc.label": "PTC SDK toàn cục (áp dụng sau khi khởi động lại)", + "gptc.hint": "Tắt theo mặc định. Ghi vào profile patch: tắt native và bật ptc, để các agent không có native executor được giới hạn phạm vi rõ ràng gọi công cụ qua run_code SDK với Git Bash và không có pwsh riêng. Có hiệu lực sau khi khởi động lại DSH. KHÔNG hỗ trợ preset-minimal: complete persona của nó xóa SDK; hãy tự duy trì preset override cho minimal. Khi tắt, vô hiệu hóa hoặc gỡ cài đặt, chỉ thu hồi các dòng do công tắc này ghi và chưa bị sửa; các dòng viết tay hoặc sửa sau đó, kể cả chú thích, đều được giữ lại.", "pwsh.label": "Công cụ pwsh (PowerShell chính thức)", "pwsh.hint": "Mặc định tắt: khi bật, công cụ pwsh chính thức của host hiển thị cho các phiên — PowerShell THẬT (bộ phân giải chính thức tự ưu tiên PowerShell 7) dùng ngay cho công việc Windows gốc (registry/services/WMI). Tắt (mặc định) thì nó vẫn bị ẩn và host vẫn ưu tiên bash. Không cần cài thêm gì; công cụ rẽ nhánh PowerShell 7 cũ đã nghỉ hưu cùng kiến trúc mới. Vẫn ưu tiên chạy lệnh qua công cụ bash trước.", "fctx.label": "Công cụ tệp FastCtx (gb_*)", @@ -1778,8 +1778,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改即時作用於現有會話的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由用戶在會話存取模式控制項選擇 danger-full-access。", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", + "gptc.label": "全域 PTC SDK(重新啟動後生效)", + "gptc.hint": "預設關閉。寫入 profile patch:root executor 切換為 PTC(native 關、ptc 開),未明確掛載 scoped native executor 的 agent 透過 run_code SDK 呼叫工具;SDK 內含 Git Bash,沒有獨立 pwsh。重新啟動 DSH 後生效。不支援 preset-minimal:其 complete persona 會抹掉 SDK,需要自行維護 preset 覆寫。關閉、停用或解除安裝時,只撤回本開關寫入且未被修改的列;使用者手寫或之後修改(包括註解)的列一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對會話可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", @@ -1868,8 +1868,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改即時作用於現有會話的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由用戶在會話存取模式控制項選擇 danger-full-access。", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", + "gptc.label": "全域 PTC SDK(重新啟動後生效)", + "gptc.hint": "預設關閉。寫入 profile patch:root executor 切換為 PTC(native 關、ptc 開),未明確掛載 scoped native executor 的 agent 透過 run_code SDK 呼叫工具;SDK 內含 Git Bash,沒有獨立 pwsh。重新啟動 DSH 後生效。不支援 preset-minimal:其 complete persona 會抹掉 SDK,需要自行維護 preset 覆寫。關閉、停用或解除安裝時,只撤回本開關寫入且未被修改的列;使用者手寫或之後修改(包括註解)的列一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對會話可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", @@ -1958,8 +1958,8 @@ window.__ModuleLoader__.load({ "variant.hint": "預設關閉:官方四個模式經行內工具補位直接獲得 Git Bash,模式列表保持官方原樣。開啟後註冊四個變體並停用官方模式的工具補位——兩者互斥。釘在變體 id 的舊會話在關閉升級後需重新選擇模式;變更對新會話生效。", "experimental.label": "實驗原生執行 / fail-closed", "experimental.hint": "預設開啟:Windows 受限或未確定存取模式下拒絕 Git Bash,並提供 gitbash_native / gitbash_to_native_path。修改立即作用於現有工作階段的後續呼叫。關閉會隱藏並停用兩個工具,恢復明確標示 UNCONFINED 的舊版 Bash,不執行 shell 檔案寫入限制。如保留安全拒絕,請由使用者在工作階段存取模式控制項選擇 danger-full-access。", - "gptc.label": "Global PTC SDK (restart to apply)", - "gptc.hint": "默认关闭。写入 profile patch:root executor 切换为 PTC(native 关、ptc 开),所有未显式挂 scoped native executor 的 agent 都通过 run_code SDK 调用工具,SDK 内含 Git Bash、无独立 pwsh。重启 DSH 后生效。关闭时只移除本开关写过的行,用户手写的行一律保留。", + "gptc.label": "全域 PTC SDK(重新啟動後生效)", + "gptc.hint": "預設關閉。寫入 profile patch:root executor 切換為 PTC(native 關、ptc 開),未明確掛載 scoped native executor 的 agent 透過 run_code SDK 呼叫工具;SDK 內含 Git Bash,沒有獨立 pwsh。重新啟動 DSH 後生效。不支援 preset-minimal:其 complete persona 會抹掉 SDK,需要自行維護 preset 覆寫。關閉、停用或解除安裝時,只撤回本開關寫入且未被修改的列;使用者手寫或之後修改(包括註解)的列一律保留。", "pwsh.label": "pwsh 工具(官方 PowerShell)", "pwsh.hint": "預設關閉:開啟後宿主官方的 pwsh 工具對工作階段可見——它是真正的 PowerShell(官方解析器自動優先 PowerShell 7),可直接用於 Windows 原生操作(登錄檔/服務/WMI)。關閉(預設)時該工具被隱藏,主機保持 bash 優先。無需安裝任何額外元件;舊版 PowerShell 7 旁路工具已隨新架構退役。命令仍然首選 bash 工具。", "fctx.label": "FastCtx 檔案工具(gb_*)", diff --git a/src/global-ptc-ownership.js b/src/global-ptc-ownership.js index 28df442..99d9f10 100644 --- a/src/global-ptc-ownership.js +++ b/src/global-ptc-ownership.js @@ -39,14 +39,48 @@ export const OWNED_ROWS = ['tool-executor-native', 'tool-executor-ptc'] * Canonical fingerprint of one written row. * * Key order is normalised (sorted, recursively) so a re-serialisation of the - * SAME row never looks like a user edit, while any added/removed/changed key — - * including a `config` block or a comment-bearing sibling — does. + * SAME row never looks like a user edit, while any added/removed/changed key + * does. YAML comments are included separately: `toJSON()` drops them, but a + * comment is user content and must make the row ineligible for lifting too. * * @param {unknown} row - plain data (not a yaml node). + * @param {string[]} [comments] - ordered comment tokens from the yaml node. * @returns {string} sha256 hex */ -export function rowFingerprint(row) { - return createHash('sha256').update(stableStringify(row)).digest('hex') +export function rowFingerprint(row, comments = []) { + return createHash('sha256').update(stableStringify({ row, comments })).digest('hex') +} + +/** + * Fingerprint a yaml AST row, including every comment/commentBefore attached + * to the row, its pairs, keys and values. Formatting-only re-serialisation is + * ignored; adding, moving or editing a comment is not. + * @param {unknown} node - a yaml AST node (plain data is accepted too). + * @returns {string} sha256 hex + */ +export function yamlRowFingerprint(node) { + let plain = node + if (node && typeof node === 'object' && typeof node.toJSON === 'function') { + try { plain = node.toJSON() } catch { plain = undefined } + } + return rowFingerprint(plain, collectYamlComments(node)) +} + +/** Collect comment tokens without walking yaml's cyclic internal metadata. */ +function collectYamlComments(node) { + const comments = [] + const seen = new WeakSet() + const visit = (value) => { + if (!value || typeof value !== 'object' || seen.has(value)) return + seen.add(value) + if (typeof value.commentBefore === 'string') comments.push(`before:${value.commentBefore}`) + if (typeof value.comment === 'string') comments.push(`after:${value.comment}`) + if (Array.isArray(value.items)) for (const item of value.items) visit(item) + visit(value.key) + visit(value.value) + } + visit(node) + return comments } /** Deterministic JSON with sorted object keys. */ diff --git a/src/global-ptc.js b/src/global-ptc.js index 73d6159..f906831 100644 --- a/src/global-ptc.js +++ b/src/global-ptc.js @@ -46,7 +46,7 @@ */ import { readPatchRow } from './terminal-bundle.js' -import { OWNED_ROWS, globalPtcOwnership, rowFingerprint } from './global-ptc-ownership.js' +import { OWNED_ROWS, globalPtcOwnership, yamlRowFingerprint } from './global-ptc-ownership.js' /** Root executor row that runs each tool natively on the wire. */ export const EXECUTOR_NATIVE_ROW = 'tool-executor-native' @@ -125,14 +125,15 @@ export function planGlobalPtcAdopt(input) { /** * Extract the current override rows for the two ids this module owns. * @param {object} document - a yaml parseDocument result. - * @returns {{native?: object, ptc?: object, raw?: {native?: unknown, ptc?: unknown}, indices?: {native: number, ptc: number}}} + * @returns {{native?: object, ptc?: object, raw?: {native?: unknown, ptc?: unknown}, fingerprints?: {native?: string, ptc?: string}, indices?: {native: number, ptc: number}}} */ export function currentGlobalPtcRows(document) { const out = {} const raw = {} + const fingerprints = {} const indices = { native: -1, ptc: -1 } const items = document?.contents?.items - if (!Array.isArray(items)) return { ...out, raw, indices } + if (!Array.isArray(items)) return { ...out, raw, fingerprints, indices } items.forEach((item, index) => { if (!item || typeof item !== 'object') return @@ -140,14 +141,16 @@ export function currentGlobalPtcRows(document) { if (id === EXECUTOR_NATIVE_ROW) { indices.native = index raw.native = toPlain(item) + fingerprints.native = yamlRowFingerprint(item) out.native = readPatchRow(raw.native) } else if (id === EXECUTOR_PTC_ROW) { indices.ptc = index raw.ptc = toPlain(item) + fingerprints.ptc = yamlRowFingerprint(item) out.ptc = readPatchRow(raw.ptc) } }) - return { ...out, raw, indices } + return { ...out, raw, fingerprints, indices } } /** Convert a yaml node to plain JS data (no anchors, no tags). */ @@ -210,20 +213,61 @@ export async function adoptGlobalPtcPatch(io, input) { if (lift === true) { return ownership.run(async () => { const receipt = await ownership.read() - const { raw, indices } = currentGlobalPtcRows(document) - const remove = [] + const snapshot = currentGlobalPtcRows(document) + const { fingerprints, indices } = snapshot + const candidates = [] + const edited = [] + const blocked = [] + const missing = [] for (const id of OWNED_ROWS) { const recorded = receipt.rows[id] if (typeof recorded !== 'string') continue - const row = id === EXECUTOR_NATIVE_ROW ? raw.native : raw.ptc + const fingerprint = id === EXECUTOR_NATIVE_ROW ? fingerprints.native : fingerprints.ptc const index = id === EXECUTOR_NATIVE_ROW ? indices.native : indices.ptc - if (index < 0 || row === undefined) continue - if (rowFingerprint(row) !== recorded) { - return done('lift', 'kept-user-choice', `${id} was edited after this switch wrote it — leaving the row alone`) + if (index < 0) { + missing.push(id) + continue + } + if (fingerprint === undefined) continue + if (fingerprint !== recorded) { + edited.push(id) + continue } - remove.push([id, index]) + candidates.push([id, index]) + } + + // Data ownership alone is not sufficient: deleting one override changes + // the OTHER executor back to its base default (native ON, ptc OFF). + // Simulate that composition before every splice. If the retained row is + // enabled ptc, removing native would enable BOTH executors; if retained + // native is disabled, removing ptc would leave NO executor. Opaque rows + // are unknown and therefore block lifting too. + const proposed = new Set(candidates.map(([id]) => id)) + const safeToLift = (id) => { + const other = id === EXECUTOR_NATIVE_ROW ? EXECUTOR_PTC_ROW : EXECUTOR_NATIVE_ROW + if (proposed.has(other)) return true // both return to the official base: native only + const otherIndex = other === EXECUTOR_NATIVE_ROW ? indices.native : indices.ptc + // The sibling is already absent. Lifting our remaining override + // restores the official base in EITHER direction: native ON, ptc OFF. + if (otherIndex < 0) return true + const fact = other === EXECUTOR_NATIVE_ROW ? snapshot.native : snapshot.ptc + if (fact?.opaque === true || typeof fact?.disabled !== 'boolean') return false + return id === EXECUTOR_NATIVE_ROW ? fact.disabled === true : fact.disabled === false } + const remove = [] + for (const candidate of candidates) { + if (safeToLift(candidate[0])) remove.push(candidate) + else blocked.push(candidate[0]) + } + const kept = [...new Set([...edited, ...blocked])] + const manualReasons = [ + edited.length > 0 ? `${edited.join(', ')} was edited after this switch wrote it` : '', + blocked.length > 0 ? `lifting ${blocked.join(', ')} would leave zero or two root executors` : '', + ].filter(Boolean).join('; ') if (remove.length === 0) { + if (kept.length > 0) { + return done('lift', 'kept-user-choice', `${manualReasons}; no rows were lifted — manual review is required`, { kept }) + } return done('unchanged', 'unchanged', 'no global PTC rows are owned by this switch; nothing changed') } document.contents.flow = false @@ -241,17 +285,24 @@ export async function adoptGlobalPtcPatch(io, input) { } catch (error) { return done('lift', 'write-failed', undefined, { detail: `the atomic write failed (${error?.message ?? error}); the previous patch bytes stand` }) } - // Drop the lifted ids from the receipt so a second OFF is a no-op. + // Drop only the lifted ids from the receipt. Edited or composition- + // blocking rows stay owned on disk and in the receipt for the next OFF. const nextRows = { ...receipt.rows } for (const [id] of remove) delete nextRows[id] + for (const id of missing) delete nextRows[id] + const status = kept.length > 0 ? 'lifted-partial' : 'lifted' + const reason = kept.length > 0 + ? `removed only rows that preserve exactly one root executor; manual review is required for ${kept.join(', ')} (${manualReasons})` + : 'removed the global PTC rows this switch wrote' + const extra = { wrote: remove.map(([id]) => id), ...(kept.length > 0 ? { kept } : {}) } try { await ownership.write({ version: 1, rows: nextRows }) } catch (error) { // The patch is already correct; a stale receipt only means a later OFF // re-checks fingerprints (and finds the rows gone). Report, do not revert. - return done('lift', 'lifted', 'removed the global PTC rows this switch wrote (the receipt could not be updated)', { wrote: remove.map(([id]) => id), detail: `receipt write failed: ${error?.message ?? error}` }) + return done('lift', status, reason, { ...extra, detail: `receipt write failed: ${error?.message ?? error}` }) } - return done('lift', 'lifted', 'removed the global PTC rows this switch wrote', { wrote: remove.map(([id]) => id) }) + return done('lift', status, reason, extra) }) } @@ -318,8 +369,8 @@ export async function adoptGlobalPtcPatch(io, input) { const receipt = await ownership.read() const nextRows = { ...receipt.rows } for (const id of wrote) { - const row = id === EXECUTOR_NATIVE_ROW ? after.raw.native : after.raw.ptc - if (row !== undefined) nextRows[id] = rowFingerprint(row) + const fingerprint = id === EXECUTOR_NATIVE_ROW ? after.fingerprints.native : after.fingerprints.ptc + if (fingerprint !== undefined) nextRows[id] = fingerprint } await ownership.write({ version: 1, rows: nextRows }) } catch (error) { diff --git a/src/index.js b/src/index.js index d745a24..e80448b 100644 --- a/src/index.js +++ b/src/index.js @@ -502,20 +502,19 @@ export const Config = Schema === null ? undefined : Schema.object({ */ fastctxTools: Schema.boolean().default(false).volatile(), /** - * Run every agent through the GLOBAL PTC run_code SDK instead of a native - * per-tool face (default OFF, and deliberately NOT volatile). + * Run supported agents through the GLOBAL PTC run_code SDK instead of a + * native per-tool face (default OFF, and deliberately NOT volatile). * * The root executor is a profile-patch decision read at boot, so this is a * patch write and not a live toggle: an edit remounts the plugin, which is - * the right weight for a change that lands on the next start. OFF writes - * nothing and never removes rows the user added. + * the right weight for a change that lands on the next start. OFF never + * adopts new rows; OFF/disable/uninstall lifts only receipted rows whose + * data AND comments are still exactly what this switch wrote. * - * What it writes (see src/global-ptc.js): `tool-executor-native` off, - * `tool-executor-ptc` on, and a `preset-minimal` restatement whose - * `persona.complete: false` keeps the SDK from being erased at assembly. - * Every write goes through the same guarded atomic writer the persistent - * terminal adoption uses, and stands down on any row the user shaped - * differently. + * What it writes (see src/global-ptc.js): `tool-executor-native` off and + * `tool-executor-ptc` on. preset-minimal is deliberately NOT restated: its + * complete persona erases the SDK, so minimal is outside this switch's + * supported presets and needs a deployment-owned preset override instead. */ globalPtcSdk: Schema.boolean().default(false), }) @@ -1873,36 +1872,54 @@ export async function apply(ctx, config = {}) { // same atomic write, verify-by-reread and rollback. See src/global-ptc.js // for the full rationale and the stand-down matrix. // - // OFF is not a no-op: it LIFTS the rows this switch wrote (matched by exact - // value), so turning the switch back off restores the official native shape - // without ever deleting a row the user shaped differently. + // OFF is not a no-op: it LIFTS only rows named by the ownership receipt AND + // still carrying the recorded data+comment fingerprint. Disable/uninstall + // runs the same lift after the in-flight adoption settles, so an enabled + // switch cannot strand a PTC root after its settings UI has disappeared. try { ctx.inject(['profileContext'], (ptcPatchCtx) => { - const run = async () => { - const patchPath = ptcPatchCtx.get('profileContext')?.patchPath - if (typeof patchPath !== 'string' || patchPath.trim() === '') { - console.log(`${TAG} global PTC SDK: no profile patch path — nothing to write`) - return - } - const atomic = await resolveHostModule(ctx, '@deepseek-ai/dsh-atomic-write') - if (typeof atomic?.withFileLock !== 'function' || typeof atomic?.writeFileAtomic !== 'function') { - throw new Error('current host atomic profile-edit capability unavailable') - } - const enabled = valueOf(config.globalPtcSdk) === true + const enabled = valueOf(config.globalPtcSdk) === true + let patchPath + let atomic + const write = (lift) => { const update = () => adoptGlobalPtcPatch( { readFile: (file) => readFileSync(file, 'utf8'), writeFileAtomic: (file, data) => atomic.writeFileAtomic(file, data, { mode: 0o600 }), yaml: () => resolveHostModule(ctx, 'yaml'), }, - { patchPath, enabled, lift: !enabled }, + { patchPath, enabled: !lift, lift }, ) // Same lock target as the terminal adoption: one serialisation point - // for every profile-patch writer in this plugin. - const result = await atomic.withFileLock(join(dirname(patchPath), 'package.json'), update) + // for every profile-patch writer in this plugin, including disposal. + return atomic.withFileLock(join(dirname(patchPath), 'package.json'), update) + } + const run = async () => { + patchPath = ptcPatchCtx.get('profileContext')?.patchPath + if (typeof patchPath !== 'string' || patchPath.trim() === '') { + console.log(`${TAG} global PTC SDK: no profile patch path — nothing to write`) + return + } + atomic = await resolveHostModule(ctx, '@deepseek-ai/dsh-atomic-write') + if (typeof atomic?.withFileLock !== 'function' || typeof atomic?.writeFileAtomic !== 'function') { + throw new Error('current host atomic profile-edit capability unavailable') + } + const result = await write(!enabled) console.log(`${TAG} ${globalPtcReport(result)}`) } - run().catch((error) => console.log(`${TAG} global PTC SDK wiring failed: ${error?.message ?? error}`)) + const pending = run().catch((error) => console.log(`${TAG} global PTC SDK wiring failed: ${error?.message ?? error}`)) + ptcPatchCtx.effect(() => async () => { + await pending + if (!enabled || !patchPath || !atomic) return + try { + const result = await write(true) + console.log(`${TAG} disable/uninstall: ${globalPtcReport(result)}`) + } catch (error) { + // Disposal must not fail the host shutdown. The log names the manual + // follow-up because the patch is persistent by design. + console.log(`${TAG} global PTC SDK disable/uninstall lift failed: ${error?.message ?? error}; review the two executor rows in ${patchPath}`) + } + }, 'dsh-gitbash-shell: global PTC SDK restore') }) } catch (error) { console.log(`${TAG} global PTC SDK wiring failed: ${error?.message ?? error}`) diff --git a/src/inline-tools.js b/src/inline-tools.js index 620aa72..ccce8d6 100644 --- a/src/inline-tools.js +++ b/src/inline-tools.js @@ -196,7 +196,33 @@ export function mountInlineTools(ctx, deps) { const controller = new AbortController() let closed = false const isLive = (agent, state) => !closed && tracked.get(agent) === state && !state.controller.signal.aborted - const newState = () => ({ timer: undefined, scope: undefined, denyPwsh: undefined, denyOpsShell: undefined, pending: undefined, native: undefined, nativeFailed: false, controller: new AbortController(), toolFace: undefined }) + const newState = () => ({ retry: undefined, scope: undefined, denyPwsh: undefined, denyOpsShell: undefined, pending: undefined, native: undefined, nativeFailed: false, controller: new AbortController(), toolFace: undefined }) + // Every retry attempt owns one record. Detaching stops the timer without + // resolving; settling is separate so a REPLACEMENT reconcile can make the + // old created promise await its own Bash mount instead of resolving early. + const detachRetry = (state, retry) => { + if (!retry || retry.detached) return retry + retry.detached = true + if (retry.timer) clearTimeout(retry.timer) + retry.timer = undefined + if (state.retry === retry) state.retry = undefined + return retry + } + const settleRetry = (state, retry) => { + if (!retry || retry.settled) return + retry.settled = true + detachRetry(state, retry) + retry.resolve() + } + const cancelRetry = (state) => { + if (state?.retry) settleRetry(state, state.retry) + } + const followRetry = (state, retry, result) => { + if (!retry) return result + return Promise.resolve(result) + .catch(() => { /* registration failures never fail agent creation */ }) + .finally(() => settleRetry(state, retry)) + } // toolFace freezes the switch values this agent was created under, so a live // settings edit cannot reshape a running face. const experimentalEnabled = () => deps.experimentalEnabled?.() !== false @@ -539,7 +565,12 @@ export function mountInlineTools(ctx, deps) { // Undo ONLY our mask before observing the face. schemas() filters a // restricted-away pwsh, so it cannot tell us what an ON flip must restore. const previous = tracked.get(agent) - if (previous?.timer) { clearTimeout(previous.timer); previous.timer = undefined } + // A new reconcile supersedes a pending timer, but the OLD created promise + // must follow THIS reconcile's result (including an async bash mount). + // Only dispose may settle a waiting retry without a ready replacement. + const interrupted = previous?.retry && !previous.retry.settled + ? detachRetry(previous, previous.retry) + : undefined if (previous?.denyPwsh) { previous.denyPwsh(); previous.denyPwsh = undefined } if (previous?.denyOpsShell) { previous.denyOpsShell(); previous.denyOpsShell = undefined } const names = faceNames(agent) @@ -551,21 +582,27 @@ export function mountInlineTools(ctx, deps) { // awaits whatever the listener returns, so a bare `return` admitted the // agent against a face that was not wired yet (review P2). Resolve only // after the retried reconcile settles, so the chain is awaited end to end. - return new Promise((resolve) => { - const timer = setTimeout(() => { + const state = tracked.get(agent) ?? newState() + if (!tracked.has(agent)) tracked.set(agent, state) + const waiting = new Promise((resolve) => { + const retry = { timer: undefined, resolve, settled: false, detached: false } + state.retry = retry + retry.timer = setTimeout(() => { + if (retry.settled) return + // This record is now FIRING, not pending. Detach it before recursing + // so the next reconcile cannot cancel/resolve its own continuation + // before the new face (or a later attempt) has been observed. + detachRetry(state, retry) Promise.resolve() .then(() => reconcile(agent, { attempt: attempt + 1 })) .catch(() => { /* never crash on a timer */ }) - .finally(() => resolve()) + .finally(() => settleRetry(state, retry)) }, 250) - timer.unref?.() - const state = tracked.get(agent) - if (state) state.timer = timer - else tracked.set(agent, { ...newState(), timer }) + retry.timer.unref?.() }) + return followRetry(state, interrupted, waiting) } let state = tracked.get(agent) - if (state?.timer) { clearTimeout(state.timer); state.timer = undefined } if (!state) { state = newState() tracked.set(agent, state) @@ -653,16 +690,16 @@ export function mountInlineTools(ctx, deps) { // returned nothing let that first admission see a face without bash (step // 1 missing, step 2 present). When a scope is already owned (or no bash is // wanted) there is nothing to wait for. - return state.pending + return followRetry(state, interrupted, state.pending) } const teardown = async (agent) => { const state = tracked.get(agent) if (!state) return tracked.delete(agent) + cancelRetry(state) state.controller.abort(new Error('inline bash agent disposed')) disposeNativeSlot(state) - if (state.timer) clearTimeout(state.timer) if (state.denyPwsh) { state.denyPwsh(); state.denyPwsh = undefined } if (state.denyOpsShell) { state.denyOpsShell(); state.denyOpsShell = undefined } await Promise.all([state.scope?.dispose(), state.pending]) diff --git a/tests/global-ptc-created.mjs b/tests/global-ptc-created.mjs index 64892a2..c83d6ba 100644 --- a/tests/global-ptc-created.mjs +++ b/tests/global-ptc-created.mjs @@ -45,10 +45,12 @@ const resolvedThenable = () => ({ /** Base host face before this plugin acts: the official win32 composition. */ const BASE_FACE = ['pwsh', 'read', 'edit'] -function createRegistry() { +function createRegistry(initialFace = BASE_FACE) { const masks = new WeakMap() const registrations = new Map() const calls = new Map() + const reads = new Map() + let baseFace = [...initialFace] return { restrict(agent, deny) { const mask = masks.get(agent) ?? new Set() @@ -74,10 +76,13 @@ function createRegistry() { } }, schemas(agent) { + reads.set(agent, (reads.get(agent) ?? 0) + 1) const mask = masks.get(agent) ?? new Set() - const names = [...BASE_FACE, ...(registrations.get(agent) ?? []).map((entry) => entry.name)] + const names = [...baseFace, ...(registrations.get(agent) ?? []).map((entry) => entry.name)] return [...new Set(names)].filter((name) => !mask.has(name)).map((name) => ({ name })) }, + setBaseFace(names) { baseFace = [...names] }, + readCount(agent) { return reads.get(agent) ?? 0 }, registerCalls(agent, name) { return (calls.get(agent) ?? []).filter((entry) => entry === name).length }, @@ -93,11 +98,11 @@ function createRegistry() { * A faithful "serial" emission: DSH's `ctx.serial` awaits each listener in * order, so a listener that returns its promise delays the caller. */ -function createFixture({ mountDelayMs = 50 } = {}) { +function createFixture({ mountDelayMs = 50, initialFace = BASE_FACE } = {}) { const listeners = new Map() const effects = [] const logs = [] - const registry = createRegistry() + const registry = createRegistry(initialFace) const agentByCtx = new WeakMap() const scopesByAgent = new WeakMap() const executorScopes = [] @@ -239,6 +244,21 @@ function createFixture({ mountDelayMs = 50 } = {}) { } } +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** Reject a hung created/retry chain instead of letting node --test hang. */ +async function settlesWithin(promise, ms) { + let watchdog + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { watchdog = setTimeout(() => reject(new Error(`promise did not settle within ${ms}ms`)), ms) }), + ]) + } finally { + clearTimeout(watchdog) + } +} + test('global PTC first step: agent/created waits for the own Bash registration', async () => { const fixture = createFixture() await fixture.ready @@ -291,3 +311,82 @@ test('global PTC: no duplicate registration on later reconciles, and dispose lea for (const effect of fixture.effects.reverse()) await effect() assert.equal(fixture.executorScopes[0]?.disposed, 1, 'the private executor scope is released on plugin dispose') }) + +test('empty face: created waits for the retry and returns with bash ready', async () => { + const fixture = createFixture({ initialFace: ['read', 'edit'] }) + await fixture.ready + const agent = fixture.createAgent('agent-empty-face') + let settled = false + const created = fixture.emitCreated(agent).then((value) => { settled = true; return value }) + + await delay(20) + assert.equal(fixture.registry.readCount(agent), 1, 'the empty face was observed once') + assert.equal(settled, false, 'created must not resolve against an unwired face') + + fixture.registry.setBaseFace(BASE_FACE) + await settlesWithin(created, 2000) + assert.ok(fixture.registry.readCount(agent) >= 2, 'the composed face was re-read') + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 1) + assert.ok(fixture.registry.schemas(agent).some((schema) => schema.name === 'bash')) +}) + +test('empty face: a later reconcile cancels the timer but still settles created', async () => { + const fixture = createFixture({ initialFace: ['read', 'edit'] }) + await fixture.ready + const agent = fixture.createAgent('agent-reconcile-cancels-retry') + const created = fixture.emitCreated(agent) + await delay(20) + assert.equal(fixture.registry.readCount(agent), 1) + + // A foreign bash arrives before the first tool call. The lazy reconcile + // clears the old retry; created must settle without mounting a second bash. + fixture.registry.setBaseFace(['bash', 'read', 'edit']) + fixture.preExecute(agent) + await settlesWithin(created, 500) + const reads = fixture.registry.readCount(agent) + await delay(350) + assert.equal(fixture.registry.readCount(agent), reads, 'the cancelled timer never fires late') + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 0, 'the foreign bash is left alone') +}) + +test('empty face: superseding reconcile makes created wait for its own bash mount', async () => { + const fixture = createFixture({ initialFace: ['read', 'edit'] }) + await fixture.ready + const agent = fixture.createAgent('agent-replacement-mounts-bash') + let settled = false + const created = fixture.emitCreated(agent).then((value) => { settled = true; return value }) + await delay(20) + assert.equal(fixture.registry.readCount(agent), 1) + + // The replacement reconcile DOES need the own bash. Cancelling the old timer + // must not resolve created before this new asynchronous mount has finished. + fixture.registry.setBaseFace(BASE_FACE) + fixture.preExecute(agent) + await delay(20) + assert.equal(settled, false, 'created is still waiting for the replacement mount') + assert.equal(fixture.registry.schemas(agent).some((schema) => schema.name === 'bash'), false) + + await settlesWithin(created, 2000) + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 1) + assert.ok(fixture.registry.schemas(agent).some((schema) => schema.name === 'bash')) + const reads = fixture.registry.readCount(agent) + await delay(350) + assert.equal(fixture.registry.readCount(agent), reads, 'the superseded timer never fires late') +}) + +test('empty face: agent disposal cancels the retry and still settles created', async () => { + const fixture = createFixture({ initialFace: ['read', 'edit'] }) + await fixture.ready + const agent = fixture.createAgent('agent-dispose-cancels-retry') + const created = fixture.emitCreated(agent) + await delay(20) + assert.equal(fixture.registry.readCount(agent), 1) + + await fixture.emitDisposed(agent) + await settlesWithin(created, 500) + const reads = fixture.registry.readCount(agent) + await delay(350) + assert.equal(fixture.registry.readCount(agent), reads, 'disposal leaves no late retry') + assert.equal(fixture.registry.activeCount(), 0) + assert.equal(fixture.registry.registerCalls(agent, 'bash'), 0) +}) diff --git a/tests/global-ptc.mjs b/tests/global-ptc.mjs index e87d363..d95614a 100644 --- a/tests/global-ptc.mjs +++ b/tests/global-ptc.mjs @@ -211,7 +211,7 @@ test('writer: P0 — OFF never deletes a user-handwritten same-value row', async assert.equal(h.read(), before, 'the user file must be byte-identical') }) -test('writer: P0 — OFF leaves a row the user edited after the switch wrote it', async (t) => { +test('writer: OFF lifts an untouched row even when its sibling was edited', async (t) => { const h = await withPatch(t, '[]\n') if (h.skip) return t.skip('no yaml module available') await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) @@ -219,10 +219,78 @@ test('writer: P0 — OFF leaves a row the user edited after the switch wrote it' const edited = h.read().replace(`- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true`, `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: false`) writeFileSync(h.file, edited) const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'lifted-partial') + assert.deepEqual(lifted.kept, [EXECUTOR_NATIVE_ROW]) + const text = h.read() + assert.match(text, new RegExp(`${EXECUTOR_NATIVE_ROW}\\n disabled: false`)) + assert.doesNotMatch(text, new RegExp(`- id: ${EXECUTOR_PTC_ROW}`)) + assert.ok(h.receipt().rows[EXECUTOR_NATIVE_ROW]) + assert.equal(h.receipt().rows[EXECUTOR_PTC_ROW], undefined) +}) + +test('writer: a comment added after adopt keeps the row and its comment', async (t) => { + // The ptc row is user-owned; only native is adopted (and receipted) here. + const h = await withPatch(t, `- id: ${EXECUTOR_PTC_ROW}\n disabled: false\n`) + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + const edited = h.read().replace( + `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true`, + `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true # keep this note`, + ) + writeFileSync(h.file, edited) + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) assert.equal(lifted.status, 'kept-user-choice') - assert.match(h.read(), new RegExp(`${EXECUTOR_NATIVE_ROW}\\n disabled: false`)) + const text = h.read() + assert.match(text, /# keep this note/) + assert.match(text, new RegExp(`- id: ${EXECUTOR_NATIVE_ROW}`)) + assert.match(text, new RegExp(`- id: ${EXECUTOR_PTC_ROW}`)) }) +for (const id of [EXECUTOR_NATIVE_ROW, EXECUTOR_PTC_ROW]) { + test(`writer: a comment-only edit on ${id} never breaks the root executor`, async (t) => { + const h = await withPatch(t, '[]\n') + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + const value = id === EXECUTOR_NATIVE_ROW ? 'true' : 'false' + const edited = h.read().replace(`- id: ${id}\n disabled: ${value}`, `- id: ${id}\n disabled: ${value} # user note`) + writeFileSync(h.file, edited) + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'kept-user-choice') + assert.match(lifted.reason, /zero or two root executors/) + assert.equal(h.read(), edited, 'neither executor row is removed when the final composition is unsafe') + assert.match(h.read(), /# user note/) + assert.ok(h.receipt().rows[EXECUTOR_NATIVE_ROW]) + assert.ok(h.receipt().rows[EXECUTOR_PTC_ROW]) + }) +} + +test('writer: an unowned disabled native row blocks lifting our ptc row', async (t) => { + const h = await withPatch(t, `- id: ${EXECUTOR_NATIVE_ROW}\n disabled: true\n`) + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + const before = h.read() + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'kept-user-choice') + assert.equal(h.read(), before, 'lifting ptc would leave no root executor') + assert.ok(h.receipt().rows[EXECUTOR_PTC_ROW]) + assert.equal(h.receipt().rows[EXECUTOR_NATIVE_ROW], undefined) +}) + +for (const missingId of [EXECUTOR_NATIVE_ROW, EXECUTOR_PTC_ROW]) { + test(`writer: OFF lifts the remaining row when ${missingId} is already missing`, async (t) => { + const h = await withPatch(t, '[]\n') + if (h.skip) return t.skip('no yaml module available') + await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: true }) + const value = missingId === EXECUTOR_NATIVE_ROW ? 'true' : 'false' + const edited = h.read().replace(`- id: ${missingId}\n disabled: ${value}\n`, '') + writeFileSync(h.file, edited) + const lifted = await adoptGlobalPtcPatch(h.io, { patchPath: h.file, enabled: false, lift: true }) + assert.equal(lifted.status, 'lifted') + assert.doesNotMatch(h.read(), /tool-executor-native|tool-executor-ptc/) + assert.deepEqual(h.receipt().rows, {}, 'missing and lifted rows both leave the receipt') + }) +} + test('writer: lift on a patch without our rows changes nothing', async (t) => { const h = await withPatch(t, '- id: untouched\n') if (h.skip) return t.skip('no yaml module available') @@ -250,3 +318,38 @@ test('ownership: a receipt store reads back what it wrote', async (t) => { await store.write({ version: 1, rows: { [EXECUTOR_NATIVE_ROW]: 'a'.repeat(64) } }) assert.deepEqual((await store.read()).rows, { [EXECUTOR_NATIVE_ROW]: 'a'.repeat(64) }) }) + +test('wiring: disable/uninstall awaits adoption and lifts under the same lock', () => { + const source = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8') + assert.match(source, /ptcPatchCtx\.effect\(\(\) => async \(\) => \{/) + assert.match(source, /await pending/) + assert.match(source, /const result = await write\(true\)/) + assert.match(source, /disable\/uninstall: \$\{globalPtcReport\(result\)\}/) + assert.match(source, /atomic\.withFileLock\(join\(dirname\(patchPath\), 'package\.json'\), update\)/) +}) + +test('settings: 21 real locale entries and the minimal limitation are present', () => { + const source = readFileSync(new URL('../src/client.js', import.meta.url), 'utf8') + const labels = [...source.matchAll(/^\t{3}"gptc\.label": "([^"]+)"/gm)].map((match) => match[1]) + const hints = [...source.matchAll(/^\t{3}"gptc\.hint": "([^"]+)"/gm)].map((match) => match[1]) + assert.equal(labels.length, 21) + assert.equal(hints.length, 21) + // zh-HK / zh-MO / zh-TW intentionally share Traditional Chinese; every + // other locale has its own text (no 18 copies of the English fallback). + assert.equal(new Set(labels).size, 19) + assert.equal(new Set(hints).size, 19) + for (const hint of hints) assert.ok(hint.includes('preset-minimal'), 'every hint names the unsupported preset') + assert.match(source, /writeField\("globalPtcSdk", true\)/) + assert.match(source, /t\("gptc\.hint"\)/) +}) + +test('docs: minimal and disposal limits are explicit', () => { + const readme = readFileSync(new URL('../README.md', import.meta.url), 'utf8') + const english = readFileSync(new URL('../README_EN.md', import.meta.url), 'utf8') + const agents = readFileSync(new URL('../AGENTS.md', import.meta.url), 'utf8') + assert.match(readme, /不覆盖 `preset-minimal`/) + assert.match(english, /`preset-minimal` is not covered/) + assert.match(agents, /绝不复述 `preset-minimal`/) + assert.match(readme, /lifted-partial/) + assert.match(agents, /comment\/commentBefore/) +})