gsd-for-omp 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,18 @@ All notable changes to `gsd-for-omp` are recorded here in [Keep a Changelog](htt
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.1.3] - 2026-10-26
8
+
9
+ ### Added
10
+
11
+ - `/gsd-execute-phase` checks that OMP will offer isolated tasks before the run starts. Without `--interactive`, it stops with a message when `task.isolation.enabled` is off or plan mode hides the task `isolated` option, instead of failing at the first executor dispatch after state reads and config writes. When nothing configures `task.isolation.enabled` (no user, project, env or protocol-host value), it is turned on for the current session only and a notification says so; `config.yml` is not touched. OMP 17 does not expose tool schemas to extensions, so it starts the run unchecked as before. The generated `extensions/gsd-for-omp.ts` wrapper now passes OMP's settings registry to the extension, so run `gsd-for-omp install` after updating.
12
+
13
+ ### Fixed
14
+
15
+ - The native phase execution guard no longer blocks writes that cannot touch the parent checkout: OMP settings and session URLs (`cfg://`, `local://`, `agent://`, `proc://`, `artifact://`, `skill://`, `omp://`, `history://`), `~/` paths, and files outside the Git checkout, such as `~/.omp/agent/config.yml` or another repository. Hashline, `apply_patch` and `sloppy` edits are now checked against the files named in their payload, including move destinations, so `.planning/` edits pass and any source target blocks the call; previously every edit without a `path` field was blocked. `write xd://<tool>` is checked as a call to `<tool>`, so `xd://gsd_invoke` passes and `xd://ast_edit` on source files still blocks. Unknown targets, unknown URL schemes, and outside paths that resolve into the checkout through a symlink stay blocked.
16
+ - The phase execution guard is released when the agent run ends with no native GSD task running and either no task was ever dispatched or the last `[checkpoint]` line reported `failed`. Before, a stale `status: executing` in `STATE.md` kept the guard on for the rest of the session after a run stopped early.
17
+ - Projected `gsd-executor` agents create a per-agent `agent-phase{PHASE}-plan{PLAN}` branch before their first commit when HEAD is detached. OMP isolated workspaces start with a detached HEAD, which made the executor's commit safety check refuse every task commit. OMP captures the commits from HEAD in both patch and branch merge modes, and the branch never leaves the isolated workspace.
18
+
7
19
  ## [1.1.2] - 2026-10-21
8
20
 
9
21
  ### Added
@@ -96,7 +108,8 @@ Related: [PR #53](https://github.com/tchivs/gsd-omp/pull/53), [release PR #54](h
96
108
 
97
109
  Related: [PR #51](https://github.com/tchivs/gsd-omp/pull/51), [release PR #52](https://github.com/tchivs/gsd-omp/pull/52).
98
110
 
99
- [Unreleased]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.2...HEAD
111
+ [Unreleased]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.3...HEAD
112
+ [1.1.3]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.2...v1.1.3
100
113
  [1.1.2]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.1...v1.1.2
101
114
  [1.1.1]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.0...v1.1.1
102
115
  [1.1.0]: https://github.com/GManzato/gsd-for-omp/compare/v1.0.27...v1.1.0
package/README.md CHANGED
@@ -53,6 +53,7 @@ The `gsd_invoke` tool gives agents structured access to the same `gsd-tools` CLI
53
53
  - **Update notice** — in GSD projects, a notification and a `⬆` footer marker appear when a newer `gsd-for-omp` is published; the npm check runs in the background at most once a day. Opt out with `GSD_FOR_OMP_NO_UPDATE_CHECK=1`.
54
54
  - **Native controls** — `/gsd-status` accepts `--compact`, `--stop`, `--branch`, `--tree`, `--switch`, and `--reload` for OMP's native session controls.
55
55
  - **Goal Mode** — when the host emits `goal_updated`, the objective, status, and token budget are mirrored in `/gsd-status`; pause or drop the goal (`/goal pause`, `/goal drop`) before `/gsd-next`. Hosts without it, such as OMP 17, keep everything else.
56
+ - **Phase execution** — `/gsd-execute-phase` dispatches executors as isolated OMP tasks, so it needs `task.isolation.enabled: true` with plan mode off (`--interactive` runs inline without it). When the setting is not configured anywhere, it is turned on for the session; an explicit `false` is respected. See [Configuration](docs/CONFIGURATION.md#phase-execution-and-task-isolation).
56
57
  - **Models** — OMP owns the model. Switch with OMP's `/model`; the GSD `model_profile` setting has no effect under OMP. See [Configuration](docs/CONFIGURATION.md#model-routing).
57
58
 
58
59
  ## Update and uninstall
package/README.zh-CN.md CHANGED
@@ -53,6 +53,7 @@ gsd-for-omp doctor
53
53
  - **更新提示** —— 在 GSD 项目中,当 npm 上发布了更新的 `gsd-for-omp` 时,会弹出通知并在页脚显示 `⬆` 标记;npm 检查在后台运行,每天最多一次。设置 `GSD_FOR_OMP_NO_UPDATE_CHECK=1` 可关闭。
54
54
  - **原生控制** —— `/gsd-status` 接受 `--compact`、`--stop`、`--branch`、`--tree`、`--switch`、`--reload`,对应 OMP 的原生会话控制。
55
55
  - **Goal Mode** —— 当主机提供 `goal_updated` 事件时,目标、状态与 token 预算会同步到 `/gsd-status`;运行 `/gsd-next` 前请先暂停或放弃目标(`/goal pause`、`/goal drop`)。没有该事件的主机(如 OMP 17)仍可使用其余全部功能。
56
+ - **阶段执行** —— `/gsd-execute-phase` 以 OMP 隔离任务派发执行器,因此需要 `task.isolation.enabled: true` 且关闭计划模式(`--interactive` 在当前会话内顺序执行,不需要隔离)。若该设置在任何位置都未配置,会为当前会话启用;显式的 `false` 会被保留。详见[配置参考](docs/CONFIGURATION.md#phase-execution-and-task-isolation)。
56
57
  - **模型** —— 模型由 OMP 掌管。请使用 OMP 的 `/model` 切换;GSD 的 `model_profile` 设置在 OMP 下不起作用。详见[配置参考](docs/CONFIGURATION.md#model-routing)。
57
58
 
58
59
  ## 更新与卸载
@@ -320,9 +320,27 @@ function assertSupportedCore(coreRoot) {
320
320
  return corePackage.version;
321
321
  }
322
322
 
323
+ // The settings registry subpath only resolves inside the OMP extension graph,
324
+ // so the wrapper imports it and hands it to the CommonJS extension. Hosts
325
+ // without the registry (OMP before 18.3) load the extension without it.
323
326
  function extensionWrapper(root) {
324
327
  const extensionPath = path.join(__dirname, '..', 'src', 'extension.cjs');
325
- return `import { createRequire } from "node:module";\n\nconst require = createRequire(import.meta.url);\nconst extension = require(${JSON.stringify(extensionPath)});\n\nexport default (pi: unknown) => extension(pi, { runtime: "omp", runtimeRoot: ${JSON.stringify(root)} });\n`;
328
+ return [
329
+ 'import { createRequire } from "node:module";',
330
+ '',
331
+ 'const require = createRequire(import.meta.url);',
332
+ `const extension = require(${JSON.stringify(extensionPath)});`,
333
+ '',
334
+ 'let settingsRegistry: unknown;',
335
+ 'try {',
336
+ ' settingsRegistry = await import("@oh-my-pi/pi-coding-agent/config/registry");',
337
+ '} catch {',
338
+ ' settingsRegistry = undefined;',
339
+ '}',
340
+ '',
341
+ `export default (pi: unknown) => extension(pi, { runtime: "omp", runtimeRoot: ${JSON.stringify(root)}, settingsRegistry });`,
342
+ '',
343
+ ].join('\n');
326
344
  }
327
345
 
328
346
  function desiredArtifacts(root, coreRoot) {
@@ -60,7 +60,7 @@ An install performs these steps:
60
60
 
61
61
  1. Resolve `@opengsd/gsd-core` and run `Eos.initialize()`.
62
62
  2. Reject a bundled GSD Core version below the minimum declared in `package.json` `engines.gsd` (currently `>=1.12.0`).
63
- 3. Build `extensions/gsd-for-omp.ts`, a thin OMP module wrapper that imports `src/extension.cjs` and passes `{ runtime: "omp", runtimeRoot }`.
63
+ 3. Build `extensions/gsd-for-omp.ts`, a thin OMP module wrapper that imports `src/extension.cjs` and passes `{ runtime: "omp", runtimeRoot, settingsRegistry }`. `settingsRegistry` is OMP's `@oh-my-pi/pi-coding-agent/config/registry` module, which resolves only inside the extension graph; the wrapper imports it in a `try` block so hosts without it still load.
64
64
  4. Project every `gsd-*.md` agent and every `gsd-*` skill with a `SKILL.md` from the resolved core tree.
65
65
  5. Stage all files in a temporary transaction directory, replace prior targets only after ownership checks, and write `.gsd-for-omp-manifest.json`.
66
66
  6. Remove unchanged stale managed projections and recognized legacy CJS extensions. Modified stale files remain protected.
@@ -139,6 +139,7 @@ Lifecycle event handling is project-scoped (the extension first checks whether t
139
139
  - `auto_compaction_start/end`, `auto_retry_start/end`, and `session_stop` expose transient native runtime signals in status.
140
140
  - `message_end` extracts pending next-action/checkpoint records from assistant text and persists them in the planning workspace.
141
141
  - `tool_execution_start/update/end`, `tool_result`, and `tool_call` track native GSD task IDs, progress, failures, settlement, hook decisions, and guarded repository writes.
142
+ - `turn_end` and `agent_end` release the native phase execution guard: `turn_end` when `STATE.md` no longer reports an executing phase, `agent_end` when the run stopped with no native GSD task running and nothing was dispatched or the last plan failed.
142
143
  - `session_shutdown` clears context and project runtime tracking.
143
144
 
144
145
  ## Status surface and optional Goal Mode adapter
@@ -97,6 +97,45 @@ A minimal project-language example is:
97
97
 
98
98
  To select Simplified Chinese explicitly, use `"response_language": "Simplified Chinese"`. The first interactive `session_start` for a GSD project with no `response_language` offers `Simplified Chinese` or `English`; it can also ask for interaction style if `workflow.text_mode` is not already explicit. Projects without an interactive UI do not receive that picker.
99
99
 
100
+ ## Phase execution and task isolation
101
+
102
+ `/gsd-execute-phase` dispatches every executor as an OMP native `task` with `isolated: true`. OMP offers that option only while `task.isolation.enabled` is `true` and plan mode is off, so the command checks the task tool's live schema before it starts a run:
103
+
104
+ | Situation | Result |
105
+ |---|---|
106
+ | Task tool already offers `isolated` | The run starts. |
107
+ | `task.isolation.enabled` is unset in every layer (provenance `default`) | The extension sets a session-only runtime override to `true`, shows a notification, and starts the run. `config.yml` is not written. |
108
+ | `task.isolation.enabled` is `false` in `config.yml`, a project `.omp/config.yml`, an env var, or a protocol-host default (RPC/ACP modes pin it to `false`) | The run does not start; the message asks for `omp config set task.isolation.enabled true`, which OMP reloads live. |
109
+ | `task.isolation.enabled` is `true` but plan mode hides `isolated` | The run does not start; leave plan mode and run the command again. |
110
+ | `--interactive` | No check: the run executes inline without isolated tasks. |
111
+
112
+ To enable isolation permanently:
113
+
114
+ ```yaml
115
+ # ~/.omp/agent/config.yml
116
+ task:
117
+ isolation:
118
+ enabled: true
119
+ ```
120
+
121
+ The check and the session override use OMP 18's tool schemas and settings registry, which the generated `extensions/gsd-for-omp.ts` wrapper imports from `@oh-my-pi/pi-coding-agent/config/registry` and passes to the extension. OMP 17 exposes neither, so the run starts unchecked; on OMP 17, isolation is the `task.isolation.mode` setting, which defaults to `none`.
122
+
123
+ ### Executor commits in isolated workspaces
124
+
125
+ An OMP isolated workspace is a private copy of the repository with HEAD detached at the parent's commit. The projected `gsd-executor` creates an `agent-phase{PHASE}-plan{PLAN}` branch there before its first commit, which satisfies the executor's protected-branch and detached-HEAD checks. OMP captures the commits from HEAD in both `task.isolation.merge` modes (as a patch, or replayed onto `omp/task/<id>`), and the branch is discarded with the workspace. A protected parent branch such as `main` with `branching_strategy: none` therefore does not block executor commits.
126
+
127
+ ### Parent-checkout guard
128
+
129
+ While a non-interactive phase execution is active, the extension blocks `write`, `edit`, `ast_edit` and applying `lsp` calls that would change a file in the parent Git checkout outside the planning directory; repository changes must come from isolated executors. It allows:
130
+
131
+ - files under the planning directory (normally `.planning/`), unless a path component is a symlink;
132
+ - OMP internal URLs that do not address checkout files: `cfg://`, `local://`, `agent://`, `proc://`, `artifact://`, `skill://`, `omp://`, `history://`;
133
+ - paths outside the checkout, including `~/` paths such as `~/.omp/agent/config.yml`, unless they resolve into the checkout through a symlink.
134
+
135
+ Edit payloads are checked against every file they name (hashline `[PATH#TAG]` headers and `MV` destinations, `apply_patch` and `sloppy` file headers, patch-mode renames); one checkout source blocks the whole call. `write xd://<tool>` is checked as a direct call to `<tool>`. Calls with no recognizable target, and other URL schemes, are blocked.
136
+
137
+ The guard ends when `STATE.md` no longer reports an executing phase at the end of a turn, or when the agent run ends with no native GSD task running and either no task was dispatched during the execution or the last `[checkpoint]` line reported `failed`.
138
+
100
139
  ## Installer CLI configuration
101
140
 
102
141
  The executable accepts one command followed by common options:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gsd-for-omp",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "Oh My Pi host plugin for the GSD Embeddable Orchestration System — extension bindings, slash-command surface, Host-Integration SDK adapter, and optional Goal Mode status integration for AI coding agents",
5
5
  "license": "MIT",
6
6
  "author": "Gilles Manzato",
@@ -38,9 +38,11 @@ function registerLifecycleHandlers({
38
38
  preToolHookOutcome,
39
39
  queueHookAdvisories,
40
40
  reconcileTaskSettlement,
41
+ recordNativePhaseCheckpoint,
41
42
  releaseFailedGsdTaskRequest,
42
43
  releaseInactiveNativePhase,
43
44
  releaseSettledGsdTasks,
45
+ releaseStoppedNativePhase,
44
46
  rememberGoalModeState,
45
47
  scheduleOnboardingPrompt,
46
48
  setNativeRuntimeSignal,
@@ -158,12 +160,21 @@ function registerLifecycleHandlers({
158
160
  updateStatus(ctx);
159
161
  });
160
162
 
163
+ // turn_end fires after every model turn, including the ones before the first dispatch;
164
+ // agent_end marks the run handing control back to the user.
165
+ pi.on('agent_end', async (_event, ctx) => {
166
+ if (!isGsdProject(ctx.cwd)) return;
167
+ releaseStoppedNativePhase(ctx.cwd);
168
+ updateStatus(ctx);
169
+ });
170
+
161
171
  pi.on('message_end', async (event, ctx) => {
162
172
  if (!isGsdProject(ctx.cwd)) return;
163
173
  const output = assistantMessageText(event?.message);
164
174
  const checkpoint = extractCheckpoint(output);
165
175
  const nextAction = extractNextAction(output);
166
176
  if (checkpoint) persistCheckpoint(ctx.cwd, checkpoint);
177
+ recordNativePhaseCheckpoint(ctx.cwd, output);
167
178
  if (nextAction) persistNextAction(ctx.cwd, nextAction);
168
179
  if (checkpoint || nextAction) updateStatus(ctx);
169
180
  if (nextAction && ctx.hasUI) await choosePendingContinuation(ctx, nextAction);
@@ -54,6 +54,7 @@ const {
54
54
  const { prioritizeRecentPhase, rememberRecentPhase } = require('./planning-store.cjs');
55
55
  const { isGsdProject } = require('./planning.cjs');
56
56
  const { parseCommandLine } = require('./util.cjs');
57
+ const { ensureTaskIsolation, taskIsolationMessage } = require('./task-isolation.cjs');
57
58
 
58
59
  /**
59
60
  * Native workflow launchers bound to the host API and runtime paths.
@@ -127,10 +128,12 @@ function createNativeLaunchers({ pi, options, agentsDir, cliPath, state }) {
127
128
  });
128
129
  }
129
130
  const phase = parseCommandLine(input)[0];
131
+ const interactive = parseCommandLine(input).includes('--interactive');
132
+ if (!interactive && !(await requireTaskIsolation(ctx))) return;
130
133
  rememberRecentPhase(ctx.cwd, 'execute', phase);
131
134
  await nameNativePhaseSession(ctx, phase, 'execute');
132
135
  const projectPath = path.resolve(ctx.cwd);
133
- nativePhaseExecutions.set(projectPath, { interactive: parseCommandLine(input).includes('--interactive') });
136
+ nativePhaseExecutions.set(projectPath, { interactive, dispatched: false });
134
137
  try {
135
138
  await pi.sendMessage({ customType: 'gsd-native-execute-phase', content: prompt, display: true }, { triggerTurn: true });
136
139
  } catch (error) {
@@ -139,6 +142,25 @@ function createNativeLaunchers({ pi, options, agentsDir, cliPath, state }) {
139
142
  }
140
143
  }
141
144
 
145
+ // Non-interactive execution dispatches every executor as an isolated native task; refuse
146
+ // before the run starts writing state rather than after the first dispatch fails.
147
+ async function requireTaskIsolation(ctx) {
148
+ const chinese = usesChinese(ctx.cwd);
149
+ const isolation = ensureTaskIsolation(pi, options.settingsRegistry);
150
+ if (isolation.enabled && typeof ctx.ui?.notify === 'function') {
151
+ ctx.ui.notify(chinese
152
+ ? '已为本会话启用 OMP 任务隔离(task.isolation.enabled 未配置)。'
153
+ : 'Enabled OMP task isolation for this session (task.isolation.enabled was not configured).', 'info');
154
+ }
155
+ if (isolation.available) return true;
156
+ await pi.sendMessage({
157
+ customType: 'gsd-execute-isolation-required',
158
+ content: taskIsolationMessage(isolation.reason, chinese),
159
+ display: true,
160
+ }, { triggerTurn: false });
161
+ return false;
162
+ }
163
+
142
164
  async function chooseExecutionPhase(ctx) {
143
165
  const chinese = usesChinese(ctx.cwd);
144
166
  const phases = prioritizeRecentPhase(ctx.cwd, 'execute', executablePhaseOptions(ctx.cwd));
@@ -40,7 +40,7 @@ function nativeTaskActivityLines(count, chinese) {
40
40
  * Per-instance native task tracker over the shared runtime state: ref-counted task ids, task calls and live execution progress.
41
41
  */
42
42
  function createNativeTaskTracker({ state }) {
43
- const { activeGsdTaskIds, activeGsdTaskIdsByCall, activeGsdTaskRefCounts, nativeTaskExecutionByCall } = state;
43
+ const { activeGsdTaskIds, activeGsdTaskIdsByCall, activeGsdTaskRefCounts, nativePhaseExecutions, nativeTaskExecutionByCall } = state;
44
44
 
45
45
  function taskIdsFor(cwd) {
46
46
  const projectPath = path.resolve(cwd);
@@ -163,6 +163,8 @@ function createNativeTaskTracker({ state }) {
163
163
  if (event?.toolName !== 'task' || typeof event.toolCallId !== 'string' || !event.toolCallId) return;
164
164
  const execution = nativeTaskExecutionState(cwd, event, null);
165
165
  if (!execution) return;
166
+ const phaseExecution = nativePhaseExecutions.get(path.resolve(cwd));
167
+ if (phaseExecution) phaseExecution.dispatched = true;
166
168
  trackGsdTaskRequest(event, cwd);
167
169
  }
168
170
 
@@ -45,7 +45,7 @@ const nativeMessageTypes = new Set([
45
45
  'gsd-continuation', 'gsd-continuation-deferred', 'gsd-continuation-dismissed',
46
46
  'gsd-continuation-error', 'gsd-continuation-preview', 'gsd-native-continuation',
47
47
  'gsd-native-skill-command', 'gsd-native-tasks-active', 'gsd-native-abort', 'gsd-native-compact', 'gsd-native-session', 'gsd-goal-mode-active', 'gsd-projected-skill-input-error', 'gsd-ship-ready', 'gsd-resume-ready',
48
- 'gsd-workflow-advisory', 'gsd-hook-advisory',
48
+ 'gsd-workflow-advisory', 'gsd-hook-advisory', 'gsd-execute-isolation-required',
49
49
  ]);
50
50
 
51
51
  for (const name of nativeMessageWorkflowNames) {
@@ -5,23 +5,125 @@
5
5
  */
6
6
 
7
7
  const fs = require('node:fs');
8
+ const os = require('node:os');
8
9
  const path = require('node:path');
9
10
  const { resolvedPlanningPaths, stateSnapshot } = require('./planning.cjs');
10
11
 
11
- function nativeMutationPaths(event) {
12
- const input = event?.input || {};
13
- if (['edit', 'write'].includes(event?.toolName)) return [input.path || input.filePath || input.file_path || input.file || ''];
14
- if (['ast_edit', 'ast-edit'].includes(event?.toolName)) return Array.isArray(input.paths) && input.paths.length ? input.paths : [input.path || ''];
15
- if (event?.toolName === 'lsp' && (['rename', 'rename_file'].includes(input.action) || (input.action === 'code_actions' && input.apply === true))) {
16
- const paths = [input.file || input.path || '', input.new_name || input.newName || ''];
17
- if (input.action === 'code_actions' && Array.isArray(input.edits)) {
18
- for (const edit of input.edits) paths.push(edit?.file || edit?.path || '');
12
+ // OMP internal URLs that address settings, session artifacts, agents or jobs, never a checkout file.
13
+ const NON_CHECKOUT_URL = /^(?:cfg|local|agent|proc|artifact|skill|omp|history):\/\//i;
14
+ const URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
15
+ // `write xd://<tool>` runs <tool> with the JSON `content` as its arguments, without a tool_call of its own.
16
+ const XD_DEVICE = /^xd:\/\/([^/?#\s]+)\/?$/i;
17
+ const CHECKPOINT_STATUS = /^\s*\[checkpoint\]\s+phase\s+\S+\s+wave\s+\d+\/\d+\s+plan\s+\S+\s+([a-z]+)/gmi;
18
+
19
+ // Edit payload grammars that carry their targets inside `input`.
20
+ const SLOPPY_TARGET = /^\s*\*\*\*\s+Edit\s+File:\s*(.+?)(?:\s+all)?\s*$/;
21
+ const APPLY_PATCH_TARGET = /^\s*\*\*\*\s+(?:(?:Add|Update|Delete)\s+File|Move\s+to):\s*(.+?)\s*$/;
22
+ // Hashline `[PATH#TAG]` (tag optional), legacy `¶PATH#TAG`, and `MV DEST` file operations.
23
+ const HASHLINE_TARGET = /^\s*(?:\[(.+?)(?:#[^#\]]*)?\]|¶+(.+?)(?:#[^#\s]*)?|MV\s+(.+?))\s*$/;
24
+
25
+ function unquote(value) {
26
+ return value.replace(/^(["'])(.*)\1$/, '$2');
27
+ }
28
+
29
+ function editPayloadPaths(text) {
30
+ const lines = text.split(/\r?\n/);
31
+ const pattern = lines.some((line) => /^\s*\*\*\*\s+Edit\s+File:/.test(line))
32
+ ? SLOPPY_TARGET
33
+ : lines.some((line) => /^\s*\*\*\*\s+(?:Add|Update|Delete)\s+File:/.test(line))
34
+ ? APPLY_PATCH_TARGET
35
+ : HASHLINE_TARGET;
36
+ const paths = [];
37
+ for (const line of lines) {
38
+ const match = pattern.exec(line);
39
+ const target = match && (match[1] ?? match[2] ?? match[3]);
40
+ if (target) paths.push(unquote(target.trim()));
41
+ }
42
+ return paths.length ? paths : [''];
43
+ }
44
+
45
+ function jsonObject(text) {
46
+ try {
47
+ const value = JSON.parse(text);
48
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+
54
+ function targetPath(input) {
55
+ return input.path || input.filePath || input.file_path || input.file || '';
56
+ }
57
+
58
+ /**
59
+ * Paths a tool call would mutate; null when the tool does not write files.
60
+ */
61
+ function mutationPaths(toolName, input) {
62
+ const args = input && typeof input === 'object' ? input : {};
63
+ if (toolName === 'write') {
64
+ const target = targetPath(args);
65
+ const device = typeof target === 'string' ? XD_DEVICE.exec(target) : null;
66
+ return device ? mutationPaths(device[1], jsonObject(args.content)) : [target];
67
+ }
68
+ if (toolName === 'edit' || toolName === 'apply_patch') {
69
+ // OMP also derives `path`/`paths` from hashline headers; the payload stays authoritative.
70
+ const payload = typeof args.input === 'string' ? args.input : args._input;
71
+ const paths = typeof payload === 'string' ? editPayloadPaths(payload) : [targetPath(args)];
72
+ if (Array.isArray(args.paths)) paths.push(...args.paths.filter((target) => typeof target === 'string'));
73
+ if (Array.isArray(args.edits)) {
74
+ for (const edit of args.edits) if (typeof edit?.rename === 'string' && edit.rename) paths.push(edit.rename);
75
+ }
76
+ return paths;
77
+ }
78
+ if (['ast_edit', 'ast-edit'].includes(toolName)) return Array.isArray(args.paths) && args.paths.length ? args.paths : [args.path || ''];
79
+ if (toolName === 'lsp' && (['rename', 'rename_file'].includes(args.action) || (args.action === 'code_actions' && args.apply === true))) {
80
+ const paths = [args.file || args.path || '', args.new_name || args.newName || ''];
81
+ if (args.action === 'code_actions' && Array.isArray(args.edits)) {
82
+ for (const edit of args.edits) paths.push(edit?.file || edit?.path || '');
19
83
  }
20
84
  return paths.filter(Boolean).length ? paths.filter(Boolean) : [''];
21
85
  }
22
86
  return null;
23
87
  }
24
88
 
89
+ function nativeMutationPaths(event) {
90
+ return mutationPaths(event?.toolName, event?.input);
91
+ }
92
+
93
+ function expandHome(filePath) {
94
+ return filePath === '~' || filePath.startsWith('~/') ? path.join(os.homedir(), filePath.slice(1)) : filePath;
95
+ }
96
+
97
+ function isWithin(root, target) {
98
+ const relative = path.relative(root, target);
99
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
100
+ }
101
+
102
+ // Realpath of the deepest existing ancestor, with the missing tail re-attached.
103
+ function realTarget(target) {
104
+ const missing = [];
105
+ let current = target;
106
+ for (;;) {
107
+ try {
108
+ return path.join(fs.realpathSync(current), ...missing);
109
+ } catch {
110
+ const parent = path.dirname(current);
111
+ if (parent === current) return target;
112
+ missing.unshift(path.basename(current));
113
+ current = parent;
114
+ }
115
+ }
116
+ }
117
+
118
+ // The enclosing Git checkout; the project directory when it is not in one.
119
+ function checkoutRoot(cwd) {
120
+ const projectRoot = path.resolve(cwd);
121
+ for (let current = projectRoot; ; current = path.dirname(current)) {
122
+ if (fs.existsSync(path.join(current, '.git'))) return current;
123
+ if (path.dirname(current) === current) return projectRoot;
124
+ }
125
+ }
126
+
25
127
  function hasSymlinkComponent(cwd, target) {
26
128
  const projectRoot = path.resolve(cwd);
27
129
  const relative = path.relative(projectRoot, target);
@@ -48,6 +150,21 @@ function isPlanningPath(filePath, cwd) {
48
150
  return inside && !hasSymlinkComponent(cwd, resolved);
49
151
  }
50
152
 
153
+ /**
154
+ * True for a file in the parent checkout outside the planning directory. Unknown targets and
155
+ * unrecognized URL schemes count as checkout files, so the guard fails closed.
156
+ */
157
+ function isParentCheckoutSource(filePath, cwd) {
158
+ if (typeof filePath !== 'string' || !filePath.trim()) return true;
159
+ if (NON_CHECKOUT_URL.test(filePath)) return false;
160
+ if (URL_SCHEME.test(filePath)) return true;
161
+ const resolved = path.resolve(cwd, expandHome(filePath));
162
+ const root = checkoutRoot(cwd);
163
+ // A path outside the checkout can still reach into it through a symlink.
164
+ const inCheckout = isWithin(root, resolved) || isWithin(realTarget(root), realTarget(resolved));
165
+ return inCheckout && !isPlanningPath(resolved, cwd);
166
+ }
167
+
51
168
  /**
52
169
  * Native phase execution guard bound to the shared runtime state.
53
170
  */
@@ -57,8 +174,8 @@ function createPhaseGuard({ state, nativeTaskActivityCount }) {
57
174
  function nativePhaseWriteBlock(event, cwd) {
58
175
  const execution = nativePhaseExecutions.get(path.resolve(cwd));
59
176
  if (!execution || execution.interactive) return null;
60
- const mutationPaths = nativeMutationPaths(event);
61
- if (!mutationPaths || mutationPaths.every((filePath) => isPlanningPath(filePath, cwd))) return null;
177
+ const paths = nativeMutationPaths(event);
178
+ if (!paths || !paths.some((filePath) => isParentCheckoutSource(filePath, cwd))) return null;
62
179
  return 'GSD OMP guard: native phase execution must dispatch an isolated gsd-executor task for repository file changes; do not edit source files in the parent checkout.';
63
180
  }
64
181
 
@@ -70,9 +187,27 @@ function createPhaseGuard({ state, nativeTaskActivityCount }) {
70
187
  nativePhaseExecutions.delete(projectPath);
71
188
  }
72
189
 
190
+ function recordNativePhaseCheckpoint(cwd, output) {
191
+ const execution = nativePhaseExecutions.get(path.resolve(cwd));
192
+ if (!execution) return;
193
+ const statuses = [...String(output || '').matchAll(CHECKPOINT_STATUS)];
194
+ if (statuses.length) execution.lastCheckpointStatus = statuses.at(-1)[1].toLowerCase();
195
+ }
196
+
197
+ // STATE.md can say `executing` long after a run stopped, so an agent run that ends with no
198
+ // native task running releases the guard when it never dispatched or its last plan failed.
199
+ function releaseStoppedNativePhase(cwd) {
200
+ const projectPath = path.resolve(cwd);
201
+ const execution = nativePhaseExecutions.get(projectPath);
202
+ if (!execution || nativeTaskActivityCount(cwd) > 0) return;
203
+ if (!execution.dispatched || execution.lastCheckpointStatus === 'failed') nativePhaseExecutions.delete(projectPath);
204
+ }
205
+
73
206
  return {
74
207
  nativePhaseWriteBlock,
208
+ recordNativePhaseCheckpoint,
75
209
  releaseInactiveNativePhase,
210
+ releaseStoppedNativePhase,
76
211
  };
77
212
  }
78
213
 
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Whether OMP's native task tool offers `isolated` dispatch in the current session.
5
+ *
6
+ * The task tool advertises `isolated` only while `task.isolation.enabled` is true and plan
7
+ * mode is off, and it rebuilds its schema from live settings, so the schema is the answer.
8
+ */
9
+
10
+ const ISOLATION_SETTING = 'task.isolation.enabled';
11
+
12
+ function schemaDeclaresIsolated(schema, seen = new Set()) {
13
+ if (!schema || typeof schema !== 'object' || seen.has(schema)) return false;
14
+ seen.add(schema);
15
+ const properties = schema.properties;
16
+ if (properties && typeof properties === 'object' && Object.hasOwn(properties, 'isolated')) return true;
17
+ return Object.values(schema).some((value) => schemaDeclaresIsolated(value, seen));
18
+ }
19
+
20
+ /**
21
+ * @returns {boolean|null} whether the task tool accepts `isolated`; null when the host cannot tell
22
+ */
23
+ function taskIsolationOffered(pi) {
24
+ if (typeof pi.getAllTools !== 'function') return null;
25
+ try {
26
+ const tools = pi.getAllTools();
27
+ const task = Array.isArray(tools) ? tools.find((tool) => tool?.name === 'task') : undefined;
28
+ if (!task) return null;
29
+ // OMP 18 tool schemas are arktype types; older hosts expose JSON Schema objects.
30
+ const parameters = task.parameters;
31
+ const schema = typeof parameters?.toJsonSchema === 'function' ? parameters.toJsonSchema() : parameters;
32
+ return schema && typeof schema === 'object' ? schemaDeclaresIsolated(schema) : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function isolationSetting(pi, registry) {
39
+ const scope = pi.pi?.settings;
40
+ const setting = scope && typeof registry?.lookup === 'function' ? registry.lookup(ISOLATION_SETTING) : undefined;
41
+ return setting ? { setting, scope } : null;
42
+ }
43
+
44
+ /**
45
+ * Makes isolated task dispatch available when nothing configures it, through a session-only
46
+ * override; an explicit user, project, env or protocol-host value is respected.
47
+ *
48
+ * @returns {{ available: boolean, enabled?: boolean, reason?: 'disabled' | 'plan-mode' }}
49
+ */
50
+ function ensureTaskIsolation(pi, registry) {
51
+ const offered = taskIsolationOffered(pi);
52
+ if (offered !== false) return { available: true };
53
+ const handle = isolationSetting(pi, registry);
54
+ if (!handle) return { available: false, reason: 'disabled' };
55
+ const { setting, scope } = handle;
56
+ try {
57
+ if (setting.get(scope) === true) return { available: false, reason: 'plan-mode' };
58
+ if (setting.provenance(scope) !== 'default') return { available: false, reason: 'disabled' };
59
+ setting.override(scope, true);
60
+ if (taskIsolationOffered(pi) !== false) return { available: true, enabled: true };
61
+ setting.clearOverride(scope);
62
+ return { available: false, reason: 'plan-mode' };
63
+ } catch {
64
+ return { available: false, reason: 'disabled' };
65
+ }
66
+ }
67
+
68
+ function taskIsolationMessage(reason, chinese) {
69
+ if (reason === 'plan-mode') {
70
+ return chinese
71
+ ? '阶段执行需要 OMP 隔离任务,但计划模式会隐藏 `isolated` 选项。请退出计划模式后重新运行 /gsd-execute-phase,或使用 --interactive。'
72
+ : 'Phase execution needs isolated OMP tasks, and plan mode hides the task `isolated` option. Leave plan mode and run /gsd-execute-phase again, or use --interactive.';
73
+ }
74
+ return chinese
75
+ ? [
76
+ '阶段执行需要 OMP 任务隔离,但当前 `task.isolation.enabled` 已关闭。启用方式:',
77
+ '',
78
+ 'omp config set task.isolation.enabled true',
79
+ '',
80
+ '设置会实时生效;然后重新运行 /gsd-execute-phase,或使用 --interactive。',
81
+ ].join('\n')
82
+ : [
83
+ 'Phase execution needs OMP task isolation, and `task.isolation.enabled` is off. Enable it with:',
84
+ '',
85
+ 'omp config set task.isolation.enabled true',
86
+ '',
87
+ 'OMP reloads the setting live; then run /gsd-execute-phase again, or use --interactive.',
88
+ ].join('\n');
89
+ }
90
+
91
+ module.exports = {
92
+ ensureTaskIsolation,
93
+ taskIsolationMessage,
94
+ taskIsolationOffered,
95
+ };
@@ -24,6 +24,16 @@ End the final report with exactly one lifecycle line, then follow OMP's terminal
24
24
  \`\`\`
25
25
 
26
26
  Use \`failed\` or \`cancelled\` instead of \`completed\` when the plan did not complete.
27
+
28
+ ## OMP isolated workspace branch
29
+
30
+ An OMP isolated task workspace is a private copy of the repository whose HEAD starts detached at the parent's commit, so the task commit protocol's HEAD safety assertion refuses to commit there. Before your first task commit, if \`git symbolic-ref --quiet HEAD\` fails, create a per-agent branch at that commit and keep committing on it:
31
+
32
+ \`\`\`bash
33
+ git switch -c "agent-phase{PHASE}-plan{PLAN}"
34
+ \`\`\`
35
+
36
+ The branch exists only inside the isolated workspace, and OMP captures your commits from HEAD whatever the branch is called (as a patch, or replayed onto \`omp/task/<id>\` in branch mode). If HEAD is already on a branch, leave it there.
27
37
  `;
28
38
 
29
39
  const EXECUTE_PHASE_SKILL = 'gsd-execute-phase';