@goodandready/dsh-cron 0.3.30 → 0.3.32

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/README.md CHANGED
@@ -206,7 +206,9 @@ Every task picks its own runtime; non-LLM runtimes need no model and consume no
206
206
  * **SSH** (`ssh`) — execute a command on a remote host through a `dsh-remote-workspace` profile (`sshProfileId`) or standalone host/key fields.
207
207
  * **Docker** (`docker`) — run the command in a container image (`dockerImage`).
208
208
  * **Environment variables** — a per-task `env` map (KEY VALUE per line in the UI) applied to external runtimes; secrets do not belong here.
209
- * **Workspaces and worktrees** — bind a task to a harness workspace (`workspaceId`, resolved through host `workspaceRegistry`) or path, and run code-modifying agent tasks in an isolated git worktree (`worktree`, `keepWorktree`).
209
+ * **Workspaces and worktrees** — bind a task to a harness workspace (`workspaceId`, resolved through host `workspaceRegistry`) or path; the agent session created for the run is registered with that workspace's ledger (`attachSession`), so it appears under the project instead of ungrouped. Code-modifying agent tasks can run in an isolated git worktree (`worktree`, `keepWorktree`).
210
+ * **Scope Locks & Conflict Prevention** — declare `writeScopes` (e.g. `src/`, `docs/`) to prevent concurrent agent runs in the same workspace from editing overlapping paths; conflicting tasks queue safely until the lock is released.
211
+ * **Input Change Detection & Hash Gate** — specify `inputHashPaths` (and `skipIfUnchanged`) to compute a deterministic SHA-256 of watched files/directories; if inputs have not changed since the last successful run, execution is skipped (`skipped (inputs unchanged)`), saving 100% of LLM tokens and execution cost.
210
212
 
211
213
  ### 7. Cost Control: Fallback Model & Burn Guard
212
214
  * **Fallback Model** — A task can run on the cheap model by default and still finish on the strong one: set `fallbackModel` (and optionally `fallbackProvider`) and a failed run — `error` or `timeout` — is retried **once** on that model before the ordinary retry backoff applies. History records which model produced the result and whether the fallback was used, usage and cost of both attempts are summed, and the `{model}` template variable renders the model that finished the run. Only agent-mediated tasks (`llm`, `skill`, `workflow`) can use a fallback.
@@ -217,7 +219,7 @@ Every task picks its own runtime; non-LLM runtimes need no model and consume no
217
219
  ### 8. Session Integration & Permissions
218
220
  * **Real Assistant Output & Terminal Status Extraction** — Isolates current turn session events, extracts the actual assistant message text (excluding previous turn history in persistent sessions), and validates terminal turn status (`turn/end` errors or interruptions) to guarantee accurate reporting, chaining, and structured action execution.
219
221
  * **Per-task permission presets & unattended approval** — `default`, `read-only`, `workspace-write`, or `danger-full-access` (aliased as `full`) are mapped directly to host `SandboxMode` and applied to the task's agent session before the prompt runs. For unattended background runs, approval policy is pinned to `never` via host `approval` service to eliminate interactive approval stalls.
220
- * **Session auto-archive** — isolated cron sessions are archived after each run (best-effort) so they do not clutter the chat list.
222
+ * **Session auto-archive** — isolated cron sessions are archived after each run (best-effort, via host `workspaceRegistry.archiveSession`) so they do not clutter the chat list.
221
223
  * **History → session navigation** — every LLM run records its session; open it straight from the run history entry.
222
224
 
223
225
  ### 9. Quiet by Rule
@@ -433,7 +435,7 @@ Developer-facing, no behaviour change. `parseScheduleExpression` was split into
433
435
  - `daily`: Automatically rotates the session daily (`<id>-YYYY-MM-DD`).
434
436
  - `weekly`: Automatically rotates the session weekly (`<id>-YYYY-Www`).
435
437
  - Custom templating: Any `targetSessionId` containing `{{date}}` automatically interpolates today's date (`YYYY-MM-DD`).
436
- - **Main Chat Visibility**: Persistent sessions are omitted from `sessions.archive()` and unflagged from `ephemeral`/`internal`, making them visible and interactable directly in the DeepSeek Harness chat interface.
438
+ - **Main Chat Visibility**: Persistent sessions are omitted from `workspaceRegistry.archiveSession()` and unflagged from `ephemeral`/`internal`, making them visible and interactable directly in the DeepSeek Harness chat interface.
437
439
  - **Preset & Tooling Compatibility**: Resumed sessions automatically preserve and remount configured `agentPresets`, ensuring full access to workspace, terminal, and file tools on every turn.
438
440
  - *Inspiration credit*: Community idea originally explored by [@RaulLazaro](https://github.com/RaulLazaro).
439
441
 
package/README.ru.md CHANGED
@@ -205,7 +205,9 @@ cron({
205
205
  * **SSH** (`ssh`) — выполнение команды на удалённом хосте через профиль `dsh-remote-workspace` (`sshProfileId`) или отдельные поля host/key.
206
206
  * **Docker** (`docker`) — выполнение команды в контейнере образа (`dockerImage`).
207
207
  * **Переменные окружения** — карта `env` на задачу (в UI — строки KEY VALUE) для внешних рантаймов; секретам здесь не место.
208
- * **Workspace и worktree** — привязка задачи к workspace харнесса (`workspaceId`, разрешаемому через службу `workspaceRegistry`) или пути, и запуск в изолированном git worktree (`worktree`, `keepWorktree`).
208
+ * **Workspace и worktree** — привязка задачи к workspace харнесса (`workspaceId`, разрешаемому через службу `workspaceRegistry`) или пути; созданная для прогона сессия агента регистрируется в ведомости этого workspace (`attachSession`), поэтому появляется в группе проекта вместо «неразмещённых». Запуск в изолированном git worktree (`worktree`, `keepWorktree`).
209
+ * **Блокировка областей записи (Scope Locks)** — указание `writeScopes` (например `src/`, `docs/`) для защиты от конфликтов при одновременной работе агентов над одним проектом; пересекающиеся задачи безопасно ждут в очереди освобождения путей.
210
+ * **Контроль изменений входных данных (Input Hash)** — настройка `inputHashPaths` (`skipIfUnchanged`) вычисляет SHA-256 файлов/папок перед запуском; если входные файлы не менялись, запуск пропускается (`skipped (inputs unchanged)`), экономя 100% токенов и бюджета.
209
211
 
210
212
  ### 7. Экономия: fallback-модель и защита бюджета (Burn Guard)
211
213
  * **Fallback-модель** — задача может идти на дешёвой модели по умолчанию и всё же завершиться на сильной: задайте `fallbackModel` (и при необходимости `fallbackProvider`), и сбойный запуск (`error` или `timeout`) один раз повторится на этой модели, прежде чем включится обычный retry с задержкой. В истории видно, какая модель произвела результат и был ли использован fallback; расход и стоимость обеих попыток суммируются; переменная шаблона `{model}` подставляет модель, завершившую запуск. Fallback доступен только агентским типам (`llm`, `skill`, `workflow`).
@@ -299,7 +301,7 @@ cron({
299
301
  - `daily`: ежедневная автоматическая ротация (`<id>-YYYY-MM-DD`).
300
302
  - `weekly`: еженедельная автоматическая ротация (`<id>-YYYY-Www`).
301
303
  - Шаблоны дат: в `targetSessionId` поддерживается плейсхолдер `{{date}}`, который автоматически заменяется на текущую дату `YYYY-MM-DD`.
302
- - **Видимость в списке чатов DSH**: Долговременные сессии не помечаются как `ephemeral`/`internal` и исключены из автоматической архивации (`sessions.archive()`), поэтому они остаются доступны для чтения и прямого диалога в веб-интерфейсе DSH.
304
+ - **Видимость в списке чатов DSH**: Долговременные сессии не помечаются как `ephemeral`/`internal` и исключены из автоматической архивации (`workspaceRegistry.archiveSession()`), поэтому они остаются доступны для чтения и прямого диалога в веб-интерфейсе DSH.
303
305
  - **Совместимость с пресетами и инструментами**: При возобновлении сессии автоматически подключаются инструменты пресета `agentPreset`, гарантируя доступ к терминалу, файлам и командам.
304
306
  - *Благодарность*: концепция вдохновлена разработкой [@RaulLazaro](https://github.com/RaulLazaro).
305
307
 
package/README.zh.md CHANGED
@@ -205,7 +205,9 @@ cron({
205
205
  * **SSH**(`ssh`)—— 通过 `dsh-remote-workspace` 配置(`sshProfileId`)或独立 host/key 字段在远程主机执行命令。
206
206
  * **Docker**(`docker`)—— 在镜像容器(`dockerImage`)中执行命令。
207
207
  * **环境变量** —— 按任务的 `env` 映射(界面中每行 KEY VALUE)应用于外部运行时;请勿在此存放密钥。
208
- * **工作区与 worktree** —— 将任务绑定到 Harness 工作区(`workspaceId`,通过宿主 `workspaceRegistry` 服务解析)或直接路径;对会修改代码的智能体任务,可在隔离的 git worktree 中运行(`worktree`、`keepWorktree`)。
208
+ * **工作区与 worktree** —— 将任务绑定到 Harness 工作区(`workspaceId`,通过宿主 `workspaceRegistry` 服务解析)或直接路径;运行创建的智能体会话会登记进该工作区的账本(`attachSession`),因此出现在项目分组下而非「未分组」。对会修改代码的智能体任务,可在隔离的 git worktree 中运行(`worktree`、`keepWorktree`)。
209
+ * **写入范围锁与冲突避免 (Scope Locks)** —— 声明 `writeScopes`(例如 `src/`、`docs/`)防止同一工作区内并发任务互相覆盖代码;重叠任务安全排队等待释放锁。
210
+ * **输入哈希监控与跳过 (Input Hash)** —— 配置 `inputHashPaths`(与 `skipIfUnchanged`)在运行前计算确定性 SHA-256;若输入未变则直接跳过 (`skipped (inputs unchanged)`),节省 100% 的 Token 与调用成本。
209
211
 
210
212
  ### 7. 成本控制:回退模型与支出保护(Burn Guard)
211
213
  * **回退模型** —— 任务可以默认使用便宜模型,失败时改用更强模型完成:设置 `fallbackModel`(可选 `fallbackProvider`),失败(`error` 或 `timeout`)的运行会在该模型上重试一次,之后才进入常规重试退避。历史记录会标明最终产出结果的模型以及是否使用了回退,两次尝试的用量与成本都会累计,模板变量 `{model}` 渲染完成运行的模型。回退仅适用于智能体类型(`llm`、`skill`、`workflow`)。
@@ -216,7 +218,7 @@ cron({
216
218
  ### 8. 会话集成与权限
217
219
  * **真实智能体输出与终端状态捕获** —— 隔离当前轮次的会话事件,提取最终真实的智能体回复文本(持久会话中自动排除以往历史轮次),并严格校验轮次终止状态(带有错误或中断的 `turn/end`),确保任务失败能准确反映到执行历史、链路调用及结构化指令中。
218
220
  * **按任务的权限预设** —— `default`、`read-only`、`workspace-write` 或 `full` 在提示词执行前应用于任务会话。
219
- * **会话自动归档** —— 隔离的 cron 会话在运行后自动归档(尽力而为),不干扰聊天列表。
221
+ * **会话自动归档** —— 隔离的 cron 会话在运行后自动归档(尽力而为,通过宿主 `workspaceRegistry.archiveSession`),不干扰聊天列表。
220
222
  * **历史 → 会话** —— 每次 LLM 运行都会记录会话,可直接从历史记录打开对话。
221
223
 
222
224
  ### 9. 按规则保持安静
@@ -424,7 +426,7 @@ bash deploy.sh verify [exact-version]
424
426
  - `daily`:每日自动开启全新子会话(后缀 `<id>-YYYY-MM-DD`)。
425
427
  - `weekly`:每周自动开启全新子会话(后缀 `<id>-YYYY-Www`)。
426
428
  - 日期变量插值:`targetSessionId` 中支持 `{{date}}` 占位符,自动注入当前日期 `YYYY-MM-DD`。
427
- - **主界面原生可见交互**:持久会话不会被标记为 `ephemeral`/`internal`,且在执行后跳过自动归档(`sessions.archive()`),用户可在 DSH 聊天列表中直接查看并继续手动对话。
429
+ - **主界面原生可见交互**:持久会话不会被标记为 `ephemeral`/`internal`,且在执行后跳过自动归档(`workspaceRegistry.archiveSession()`),用户可在 DSH 聊天列表中直接查看并继续手动对话。
428
430
  - **预设工具链无缝适配**:恢复会话时同样完整挂载 `agentPresets`,保障文件读写、代码编辑与终端工具持续可用。
429
431
  - *致谢*:功能灵感源自社区开发者 [@RaulLazaro](https://github.com/RaulLazaro)。
430
432
 
@@ -215,6 +215,11 @@
215
215
  'form.gracePeriodLabel': 'Heartbeat grace period (seconds)',
216
216
  'form.priorityLabel': 'Queue priority (1-10, higher runs first)',
217
217
  'form.concurrencyGroupLabel': 'Concurrency group',
218
+ 'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
219
+ 'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
220
+ 'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
221
+ 'form.inputHashPathsPlaceholder': 'e.g. src/, package.json (skip run if unchanged)',
222
+ 'form.skipIfUnchangedLabel': 'Skip execution if inputs are unchanged (save tokens & budget)',
218
223
  'form.selfHealingLabel': 'Self-healing runbook command (shell)',
219
224
  'form.selfHealingPlaceholder': 'systemctl restart app || true',
220
225
  'form.autoDiagnoseLabel': 'Auto-diagnose failures with AI agent',
@@ -421,6 +426,9 @@
421
426
  'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
422
427
  'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
423
428
  'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
429
+ 'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
430
+ 'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
431
+ 'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
424
432
  'form.selfHealingLabel': '故障自愈脚本 (Shell)', 'form.selfHealingPlaceholder': 'systemctl restart app || true',
425
433
  'form.autoDiagnoseLabel': '任务失败时启用 AI 智能分析诊断', 'form.agentPresetLabel': '智能体预设 (Agent Preset)',
426
434
  'form.agentPresetPlaceholder': 'standard (留空使用全局默认预设)', 'form.agentPresetHint': '来自 dsh-agent-presets 的智能体预设(如 standard, minimal, cordis, ptc),挂载工作区工具与文件读写能力。',
@@ -100,6 +100,9 @@
100
100
  const [formPreflightTarget, setFormPreflightTarget] = React.useState('');
101
101
  const [formPriority, setFormPriority] = React.useState(5);
102
102
  const [formConcurrencyGroup, setFormConcurrencyGroup] = React.useState('default');
103
+ const [formWriteScopes, setFormWriteScopes] = React.useState('');
104
+ const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
105
+ const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
103
106
  const [formSelfHealingCommand, setFormSelfHealingCommand] = React.useState('');
104
107
  const [formAutoDiagnose, setFormAutoDiagnose] = React.useState(false);
105
108
  const [schedulePreviewRuns, setSchedulePreviewRuns] = React.useState(null);
@@ -333,6 +333,9 @@
333
333
  setFormPreflightTarget(task.preflightTarget || '');
334
334
  setFormPriority(task.priority !== undefined ? task.priority : 5);
335
335
  setFormConcurrencyGroup(task.concurrencyGroup || 'default');
336
+ setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
337
+ setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
338
+ setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
336
339
  setFormSelfHealingCommand(task.selfHealingCommand || '');
337
340
  setFormAutoDiagnose(Boolean(task.autoDiagnose));
338
341
  setSchedulePreviewRuns(null);
@@ -418,6 +421,9 @@
418
421
  preflightTarget: formPreflightTarget.trim() || undefined,
419
422
  priority: Number(formPriority) || 5,
420
423
  concurrencyGroup: formConcurrencyGroup.trim() || 'default',
424
+ writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
425
+ inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
426
+ skipIfUnchanged: Boolean(formSkipIfUnchanged),
421
427
  selfHealingCommand: formSelfHealingCommand.trim() || undefined,
422
428
  autoDiagnose: Boolean(formAutoDiagnose),
423
429
  requireApproval: Boolean(formRequireApproval),
@@ -294,6 +294,35 @@
294
294
  })
295
295
  )
296
296
  ),
297
+ React.createElement('div', { className: 'dsh-cron-form-group' },
298
+ React.createElement('label', null, T_KEY(t, 'form.writeScopesLabel')),
299
+ React.createElement('input', {
300
+ type: 'text',
301
+ value: formWriteScopes,
302
+ placeholder: T_KEY(t, 'form.writeScopesPlaceholder'),
303
+ onChange: (e) => setFormWriteScopes(e.target.value)
304
+ })
305
+ ),
306
+ React.createElement('div', { className: 'dsh-cron-form-group' },
307
+ React.createElement('label', null, T_KEY(t, 'form.inputHashPathsLabel')),
308
+ React.createElement('input', {
309
+ type: 'text',
310
+ value: formInputHashPaths,
311
+ placeholder: T_KEY(t, 'form.inputHashPathsPlaceholder'),
312
+ onChange: (e) => setFormInputHashPaths(e.target.value)
313
+ })
314
+ ),
315
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '6px' } },
316
+ React.createElement('input', {
317
+ type: 'checkbox',
318
+ id: 'formSkipIfUnchangedCheckbox',
319
+ checked: formSkipIfUnchanged,
320
+ onChange: (e) => setFormSkipIfUnchanged(e.target.checked)
321
+ }),
322
+ React.createElement('label', { htmlFor: 'formSkipIfUnchangedCheckbox', style: { margin: 0, cursor: 'pointer', fontSize: '13px' } },
323
+ T_KEY(t, 'form.skipIfUnchangedLabel')
324
+ )
325
+ ),
297
326
  React.createElement('div', { className: 'dsh-cron-form-group' },
298
327
  React.createElement('label', null, T_KEY(t, 'form.selfHealingLabel')),
299
328
  React.createElement('input', {
package/lib/client.js CHANGED
@@ -261,6 +261,11 @@ en: {
261
261
  'form.gracePeriodLabel': 'Heartbeat grace period (seconds)',
262
262
  'form.priorityLabel': 'Queue priority (1-10, higher runs first)',
263
263
  'form.concurrencyGroupLabel': 'Concurrency group',
264
+ 'form.writeScopesLabel': 'Write scopes (Scope Locks, relative paths per line or comma)',
265
+ 'form.writeScopesPlaceholder': 'e.g. src/, docs/ (prevents concurrent writes on overlapping scopes)',
266
+ 'form.inputHashPathsLabel': 'Input hash paths (inputHashPaths)',
267
+ 'form.inputHashPathsPlaceholder': 'e.g. src/, package.json (skip run if unchanged)',
268
+ 'form.skipIfUnchangedLabel': 'Skip execution if inputs are unchanged (save tokens & budget)',
264
269
  'form.selfHealingLabel': 'Self-healing runbook command (shell)',
265
270
  'form.selfHealingPlaceholder': 'systemctl restart app || true',
266
271
  'form.autoDiagnoseLabel': 'Auto-diagnose failures with AI agent',
@@ -466,6 +471,9 @@ zh: {
466
471
  'form.preflightTargetLabel': '预检目标参数', 'form.preflightTargetPlaceholder': 'https://example.com/healthz 或 ls /data 或 /:10%',
467
472
  'form.heartbeatIntervalLabel': '心跳打卡时限 (秒, 0 = 禁用)', 'form.gracePeriodLabel': '心跳宽限期 (秒)',
468
473
  'form.priorityLabel': '队列优先级 (1-10,数值越大越先执行)', 'form.concurrencyGroupLabel': '并发分组名称',
474
+ 'form.writeScopesLabel': '文件写入范围锁 (writeScopes, 相对路径)', 'form.writeScopesPlaceholder': '例如: src/, docs/ (阻止与同工作区重叠任务并发执行)',
475
+ 'form.inputHashPathsLabel': '输入文件哈希变动监控 (inputHashPaths)', 'form.inputHashPathsPlaceholder': '例如: src/, package.json (无变动时跳过执行)',
476
+ 'form.skipIfUnchangedLabel': '输入文件无变动时跳过执行 (节省 Token 与预算)',
469
477
  'form.selfHealingLabel': '故障自愈脚本 (Shell)', 'form.selfHealingPlaceholder': 'systemctl restart app || true',
470
478
  'form.autoDiagnoseLabel': '任务失败时启用 AI 智能分析诊断', 'form.agentPresetLabel': '智能体预设 (Agent Preset)',
471
479
  'form.agentPresetPlaceholder': 'standard (留空使用全局默认预设)', 'form.agentPresetHint': '来自 dsh-agent-presets 的智能体预设(如 standard, minimal, cordis, ptc),挂载工作区工具与文件读写能力。',
@@ -1630,6 +1638,9 @@ const [formPreflightType, setFormPreflightType] = React.useState('none');
1630
1638
  const [formPreflightTarget, setFormPreflightTarget] = React.useState('');
1631
1639
  const [formPriority, setFormPriority] = React.useState(5);
1632
1640
  const [formConcurrencyGroup, setFormConcurrencyGroup] = React.useState('default');
1641
+ const [formWriteScopes, setFormWriteScopes] = React.useState('');
1642
+ const [formInputHashPaths, setFormInputHashPaths] = React.useState('');
1643
+ const [formSkipIfUnchanged, setFormSkipIfUnchanged] = React.useState(false);
1633
1644
  const [formSelfHealingCommand, setFormSelfHealingCommand] = React.useState('');
1634
1645
  const [formAutoDiagnose, setFormAutoDiagnose] = React.useState(false);
1635
1646
  const [schedulePreviewRuns, setSchedulePreviewRuns] = React.useState(null);
@@ -2552,6 +2563,9 @@ setFormPreflightType(task.preflightType || 'none');
2552
2563
  setFormPreflightTarget(task.preflightTarget || '');
2553
2564
  setFormPriority(task.priority !== undefined ? task.priority : 5);
2554
2565
  setFormConcurrencyGroup(task.concurrencyGroup || 'default');
2566
+ setFormWriteScopes(Array.isArray(task.writeScopes) ? task.writeScopes.join('\n') : (task.writeScopes || ''));
2567
+ setFormInputHashPaths(Array.isArray(task.inputHashPaths) ? task.inputHashPaths.join('\n') : (task.inputHashPaths || ''));
2568
+ setFormSkipIfUnchanged(Boolean(task.skipIfUnchanged));
2555
2569
  setFormSelfHealingCommand(task.selfHealingCommand || '');
2556
2570
  setFormAutoDiagnose(Boolean(task.autoDiagnose));
2557
2571
  setSchedulePreviewRuns(null);
@@ -2635,6 +2649,9 @@ preflightType: formPreflightType || 'none',
2635
2649
  preflightTarget: formPreflightTarget.trim() || undefined,
2636
2650
  priority: Number(formPriority) || 5,
2637
2651
  concurrencyGroup: formConcurrencyGroup.trim() || 'default',
2652
+ writeScopes: formWriteScopes ? formWriteScopes.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
2653
+ inputHashPaths: formInputHashPaths ? formInputHashPaths.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean) : [],
2654
+ skipIfUnchanged: Boolean(formSkipIfUnchanged),
2638
2655
  selfHealingCommand: formSelfHealingCommand.trim() || undefined,
2639
2656
  autoDiagnose: Boolean(formAutoDiagnose),
2640
2657
  requireApproval: Boolean(formRequireApproval),
@@ -4138,6 +4155,35 @@ onChange: (e) => setFormConcurrencyGroup(e.target.value)
4138
4155
  )
4139
4156
  ),
4140
4157
  _h('div', { className: 'dsh-cron-form-group' },
4158
+ _h('label', null, T_KEY(t, 'form.writeScopesLabel')),
4159
+ _h('input', {
4160
+ type: 'text',
4161
+ value: formWriteScopes,
4162
+ placeholder: T_KEY(t, 'form.writeScopesPlaceholder'),
4163
+ onChange: (e) => setFormWriteScopes(e.target.value)
4164
+ })
4165
+ ),
4166
+ _h('div', { className: 'dsh-cron-form-group' },
4167
+ _h('label', null, T_KEY(t, 'form.inputHashPathsLabel')),
4168
+ _h('input', {
4169
+ type: 'text',
4170
+ value: formInputHashPaths,
4171
+ placeholder: T_KEY(t, 'form.inputHashPathsPlaceholder'),
4172
+ onChange: (e) => setFormInputHashPaths(e.target.value)
4173
+ })
4174
+ ),
4175
+ _h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginTop: '6px' } },
4176
+ _h('input', {
4177
+ type: 'checkbox',
4178
+ id: 'formSkipIfUnchangedCheckbox',
4179
+ checked: formSkipIfUnchanged,
4180
+ onChange: (e) => setFormSkipIfUnchanged(e.target.checked)
4181
+ }),
4182
+ _h('label', { htmlFor: 'formSkipIfUnchangedCheckbox', style: { margin: 0, cursor: 'pointer', fontSize: '13px' } },
4183
+ T_KEY(t, 'form.skipIfUnchangedLabel')
4184
+ )
4185
+ ),
4186
+ _h('div', { className: 'dsh-cron-form-group' },
4141
4187
  _h('label', null, T_KEY(t, 'form.selfHealingLabel')),
4142
4188
  _h('input', {
4143
4189
  type: 'text',
package/lib/cron-tool.js CHANGED
@@ -326,6 +326,18 @@ export const cronToolParameters = {
326
326
  type: 'string',
327
327
  description: 'Named concurrency group to serialize related tasks',
328
328
  },
329
+ writeScopes: {
330
+ type: 'array',
331
+ description: 'Relative directory/file scopes to lock to prevent conflicting concurrent writes',
332
+ },
333
+ inputHashPaths: {
334
+ type: 'array',
335
+ description: 'Relative directory/file paths to check for changes before running',
336
+ },
337
+ skipIfUnchanged: {
338
+ type: 'boolean',
339
+ description: 'Skip running task if inputHashPaths content has not changed since last successful run',
340
+ },
329
341
  priority: {
330
342
  type: 'number',
331
343
  description: 'Task priority (1 = highest, 10 = lowest, default 5)',
@@ -0,0 +1,106 @@
1
+ // @ts-check
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+
6
+ /**
7
+ * Normalize an array or string of input paths to watch/hash.
8
+ *
9
+ * @param {string[]|string|null|undefined} paths
10
+ * @returns {string[]}
11
+ */
12
+ export function normalizeInputHashPaths(paths) {
13
+ if (!paths) return [];
14
+ const list = Array.isArray(paths)
15
+ ? paths
16
+ : String(paths).split(/[\n,]+/).map((p) => p.trim());
17
+ return list.filter((p) => typeof p === 'string' && p.length > 0);
18
+ }
19
+
20
+ /**
21
+ * Compute a SHA-256 hash or signature of a file or directory tree.
22
+ * Deterministic and skips noisy or non-tracked artifacts (.git, node_modules).
23
+ *
24
+ * @param {string} targetPath
25
+ * @returns {string}
26
+ */
27
+ export function hashPath(targetPath) {
28
+ if (!fs.existsSync(targetPath)) {
29
+ return 'nonexistent';
30
+ }
31
+
32
+ let stat;
33
+ try {
34
+ stat = fs.statSync(targetPath);
35
+ } catch (_err) {
36
+ return 'error';
37
+ }
38
+
39
+ if (stat.isFile()) {
40
+ try {
41
+ const content = fs.readFileSync(targetPath);
42
+ return crypto.createHash('sha256').update(content).digest('hex').slice(0, 32);
43
+ } catch (_err) {
44
+ return `stat:${stat.size}:${stat.mtimeMs}`;
45
+ }
46
+ }
47
+
48
+ if (stat.isDirectory()) {
49
+ const hash = crypto.createHash('sha256');
50
+ function walk(dir, depth = 0) {
51
+ if (depth > 8) return; // Prevent infinite recursion on deep/circular trees
52
+ let entries = [];
53
+ try {
54
+ entries = fs.readdirSync(dir, { withFileTypes: true });
55
+ } catch (_err) {
56
+ return;
57
+ }
58
+ entries.sort((a, b) => a.name.localeCompare(b.name));
59
+ for (const ent of entries) {
60
+ if (ent.name === '.git' || ent.name === 'node_modules') continue;
61
+ const fullPath = path.join(dir, ent.name);
62
+ if (ent.isFile()) {
63
+ try {
64
+ const st = fs.statSync(fullPath);
65
+ hash.update(`${ent.name}:${st.size}:${st.mtimeMs}:`);
66
+ if (st.size < 2 * 1024 * 1024) {
67
+ const fileBuf = fs.readFileSync(fullPath);
68
+ hash.update(fileBuf);
69
+ }
70
+ } catch (_err) { void _err; }
71
+ } else if (ent.isDirectory()) {
72
+ hash.update(`dir:${ent.name}:`);
73
+ walk(fullPath, depth + 1);
74
+ }
75
+ }
76
+ }
77
+ walk(targetPath);
78
+ return hash.digest('hex').slice(0, 32);
79
+ }
80
+
81
+ return 'other';
82
+ }
83
+
84
+ /**
85
+ * Compute the combined input hash for a task based on its configured inputHashPaths.
86
+ * Returns null if no inputHashPaths are configured or valid.
87
+ *
88
+ * @param {string|null|undefined} cwd
89
+ * @param {string[]|string|null|undefined} inputHashPaths
90
+ * @returns {Promise<string|null>}
91
+ */
92
+ export async function computeTaskInputHash(cwd, inputHashPaths) {
93
+ const normPaths = normalizeInputHashPaths(inputHashPaths);
94
+ if (normPaths.length === 0) return null;
95
+
96
+ const combined = crypto.createHash('sha256');
97
+ const baseDir = cwd || process.cwd();
98
+
99
+ for (const relOrAbs of normPaths) {
100
+ const resolved = path.isAbsolute(relOrAbs) ? relOrAbs : path.resolve(baseDir, relOrAbs);
101
+ const h = hashPath(resolved);
102
+ combined.update(`${relOrAbs}=${h};`);
103
+ }
104
+
105
+ return 'sha256:' + combined.digest('hex').slice(0, 16);
106
+ }
package/lib/locales.json CHANGED
@@ -405,6 +405,11 @@
405
405
  "settings.feishuSecretLabel": "签名密钥(可选)",
406
406
  "settings.feishuSecretPlaceholder": "SEC…",
407
407
  "settings.feishuGlobalNotify": "所有任务的运行结果都推送到飞书",
408
- "settings.feishuHint": "飞书群通知:在目标群里添加「自定义机器人」,把它的 Webhook 地址粘贴到下面;如果机器人开启了「签名校验」,再把签名密钥一并填入。"
408
+ "settings.feishuHint": "飞书群通知:在目标群里添加「自定义机器人」,把它的 Webhook 地址粘贴到下面;如果机器人开启了「签名校验」,再把签名密钥一并填入。",
409
+ "form.writeScopesLabel": "文件写入范围锁 (writeScopes, 每行或逗号分隔一个路径)",
410
+ "form.writeScopesPlaceholder": "例如: src/, docs/ (阻止与同工作区重叠任务并发执行)",
411
+ "form.inputHashPathsLabel": "输入文件哈希变动监控 (inputHashPaths)",
412
+ "form.inputHashPathsPlaceholder": "例如: src/, package.json (无变动时跳过执行)",
413
+ "form.skipIfUnchangedLabel": "输入文件无变动时跳过执行 (节省 Token 与预算)"
409
414
  }
410
415
  }
@@ -113,6 +113,49 @@ export class SessionRunner {
113
113
  }
114
114
  }
115
115
 
116
+ _getWorkspaceRegistry() {
117
+ if (!this.ctx) return null;
118
+ try {
119
+ if (typeof this.ctx.get === 'function') {
120
+ const svc = this.ctx.get('workspaceRegistry');
121
+ if (svc) return svc;
122
+ }
123
+ } catch (_err) {
124
+ // service unavailable via ctx.get
125
+ }
126
+ try {
127
+ return this.ctx.workspaceRegistry || null;
128
+ } catch (_err) {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Resolve the registered Workspace object for a task's workspaceId (workspace attach & archive).
135
+ * Mirrors the id/title/path lookup used by resolveCwd; returns null when the
136
+ * id is absent, the registry is unavailable, or no workspace matches.
137
+ */
138
+ _resolveWorkspace(task) {
139
+ const rawId = task?.workspaceId ? String(task.workspaceId).trim() : '';
140
+ if (!rawId) return null;
141
+ return bestEffort('resolve-workspace', () => {
142
+ const registry = this._getWorkspaceRegistry();
143
+ if (!registry) return null;
144
+ if (typeof registry.get === 'function') {
145
+ const ws = registry.get(rawId);
146
+ if (ws && typeof ws.attachSession === 'function') return ws;
147
+ }
148
+ if (typeof registry.list === 'function') {
149
+ const list = registry.list();
150
+ if (Array.isArray(list)) {
151
+ const matched = list.find((w) => w && (w.id === rawId || w.path === rawId || w.title === rawId));
152
+ if (matched && typeof matched.attachSession === 'function') return matched;
153
+ }
154
+ }
155
+ return null;
156
+ }) || null;
157
+ }
158
+
116
159
  async execute(task, options = {}) {
117
160
  const timeoutSeconds = Number(task.timeoutSeconds) > 0 ? Number(task.timeoutSeconds) : 1800;
118
161
  const timeoutMs = timeoutSeconds * 1000;
@@ -369,7 +412,16 @@ export class SessionRunner {
369
412
  // Context window overflow auto-recovery in persistent sessions (#145)
370
413
  if (prep.targetSessionId && isContextOverflowError(err) && !signal?.aborted) {
371
414
  logger.warn(`[dsh-cron] Persistent session "${prep.targetSessionId}" exceeded context window (${err.message}). Auto-recovering with fresh session...`);
372
- bestEffort('archive-rotated-session', () => {
415
+ // workspace attach & archive: the host SessionStore has no archive() method — the durable
416
+ // archive set lives on the workspaceRegistry. Archive the exhausted
417
+ // session there (the dispose in _executeAgentTurn's finally has already
418
+ // run, so the session is inactive).
419
+ await bestEffort('archive-rotated-session', async () => {
420
+ const registry = this._getWorkspaceRegistry();
421
+ if (registry && typeof registry.archiveSession === 'function') {
422
+ await registry.archiveSession(prep.targetSessionId);
423
+ return;
424
+ }
373
425
  const sessions = this.ctx?.get?.('sessions');
374
426
  if (sessions && typeof sessions.archive === 'function') {
375
427
  sessions.archive(prep.targetSessionId);
@@ -566,6 +618,17 @@ export class SessionRunner {
566
618
  }
567
619
  }
568
620
 
621
+ // workspace attach & archive: register the new session with its workspace ledger so it shows
622
+ // up under the project instead of "ungrouped". attachSession validates
623
+ // that the session cwd resolves to the workspace path, so skip when the
624
+ // run uses an isolated worktree (different cwd) or the workspaceId does
625
+ // not resolve to a registered workspace.
626
+ if (!isResumed && !prep.taskWorktree && task.workspaceId && handle?.agent?.session?.id) {
627
+ await bestEffort('attach-session-to-workspace', () =>
628
+ this._resolveWorkspace(task)?.attachSession(handle.agent.session.id)
629
+ );
630
+ }
631
+
569
632
  this._applyPermissionPreset(task, handle);
570
633
  this._nameSession(task, handle, isResumed);
571
634
  await prep.raceAbort(handle.agent.whenIdle());
@@ -864,9 +927,17 @@ export class SessionRunner {
864
927
  }
865
928
  // Best-effort: keep ephemeral cron sessions out of the main chat list (#30).
866
929
  // Persistent sessions (targetSessionId configured) stay unarchived so users can interact with them (#143).
867
- if (archivedSessionId && this.ctx && this.ctx.get && !prep.targetSessionId) {
868
- bestEffort('archive-session-cleanup', () => {
869
- const sessions = this.ctx.get('sessions');
930
+ if (archivedSessionId && this.ctx && !prep.targetSessionId) {
931
+ // workspace attach & archive: the host SessionStore has no archive() method (it was a silent
932
+ // no-op on every run). The durable archive set is written by
933
+ // workspaceRegistry.archiveSession, which needs no workspace membership.
934
+ await bestEffort('archive-session-cleanup', async () => {
935
+ const registry = this._getWorkspaceRegistry();
936
+ if (registry && typeof registry.archiveSession === 'function') {
937
+ await registry.archiveSession(archivedSessionId);
938
+ return;
939
+ }
940
+ const sessions = typeof this.ctx.get === 'function' ? this.ctx.get('sessions') : null;
870
941
  if (sessions && typeof sessions.archive === 'function') {
871
942
  sessions.archive(archivedSessionId);
872
943
  }
@@ -232,6 +232,14 @@ export async function handleCompleteRun(scheduler, task, taskId, currentRun, out
232
232
  const finishedRun = scheduler.running.get(taskId);
233
233
  const isCurrentRun = (finishedRun === currentRun);
234
234
  if (isCurrentRun) scheduler.running.delete(taskId);
235
+ if (scheduler.scopeLocks) {
236
+ scheduler.scopeLocks.release(task, taskId);
237
+ }
238
+ if (outcome && (outcome.status === 'ok' || outcome.status === 'success') && options && options.currentInputHash) {
239
+ try {
240
+ scheduler.store.patch(taskId, { lastInputHash: options.currentInputHash });
241
+ } catch (_hashErr) { void _hashErr; }
242
+ }
235
243
  const queuedRuns = isCurrentRun ? (finishedRun?.queuedRuns || []) : [];
236
244
  const queuedCount = isCurrentRun ? (finishedRun?.queueCount || 0) : 0;
237
245
 
@@ -249,40 +257,8 @@ export async function handleCompleteRun(scheduler, task, taskId, currentRun, out
249
257
  const guard = await checkAndApplyBurnGuard(scheduler, taskId, outcome);
250
258
  if (guard && guard.exceeded) return;
251
259
 
252
- if (!scheduler.isStopped && scheduler.queue.length > 0 && (scheduler.maxConcurrent === 0 || scheduler.running.size < scheduler.maxConcurrent)) {
253
- let admittedIndex = -1;
254
- for (let i = 0; i < scheduler.queue.length; i++) {
255
- const candidate = scheduler.queue[i];
256
- const queuedTask = scheduler.store.get(candidate.taskId);
257
- if (!queuedTask || queuedTask.status !== 'active') {
258
- scheduler.queue.splice(i, 1);
259
- i--;
260
- continue;
261
- }
262
- const qGroup = queuedTask.concurrencyGroup && queuedTask.concurrencyGroup !== 'default'
263
- ? String(queuedTask.concurrencyGroup).trim()
264
- : null;
265
- const qLimit = scheduler.getGroupLimit ? scheduler.getGroupLimit(qGroup) : (qGroup ? 1 : 0);
266
- if (qGroup && qLimit > 0) {
267
- const inGroup = scheduler.getRunningGroupCount ? scheduler.getRunningGroupCount(qGroup) : 0;
268
- if (inGroup >= qLimit) {
269
- continue;
270
- }
271
- }
272
- admittedIndex = i;
273
- break;
274
- }
275
-
276
- if (admittedIndex !== -1) {
277
- const nextItem = scheduler.queue.splice(admittedIndex, 1)[0];
278
- setImmediate(() => {
279
- if (!scheduler.isStopped) {
280
- scheduler.runTask(nextItem.taskId, nextItem.options || {}).catch((runErr) => {
281
- bestEffort('drain-queued-task', () => {}, scheduler.logger);
282
- });
283
- }
284
- });
285
- }
260
+ if (typeof scheduler.drainQueue === 'function') {
261
+ scheduler.drainQueue();
286
262
  }
287
263
 
288
264
  // 1. Structured LLM Actions (#137)
@@ -4,6 +4,7 @@ import { globalBudgetManager } from '../global-budgets.js';
4
4
  import { logger } from '../logger.js';
5
5
  import { checkAndApplyBurnGuard, checkTaskBudgetLimits } from '../burn-guard.js';
6
6
  import { resolveTaskForExecution } from '../prompt-interpolation.js';
7
+ import { computeTaskInputHash } from '../input-hash.js';
7
8
  import { approvalManager } from '../approval.js';
8
9
  import {
9
10
  AGENT_TASK_TYPES,
@@ -79,6 +80,28 @@ export function beginRun(scheduler, task, taskId, options = {}) {
79
80
  }
80
81
  }
81
82
 
83
+ if (scheduler.scopeLocks && !scheduler.running.has(taskId)) {
84
+ const scopeCheck = scheduler.scopeLocks.canAcquire(task, taskId);
85
+ if (!scopeCheck.ok) {
86
+ const conflictMsg = `Scope conflict with task "${scopeCheck.conflictTaskId}" on "${scopeCheck.conflictingScope}"`;
87
+ if (task.overlapPolicy === 'queue') {
88
+ logger.info(`[dsh-cron] Task "${task.title}" (${taskId}) queued by ${conflictMsg}`);
89
+ scheduler.queue.push({
90
+ taskId,
91
+ options: { ...options },
92
+ priority: task.priority !== undefined ? task.priority : 5,
93
+ queuedAt: Date.now(),
94
+ waitReason: 'scope-conflict',
95
+ });
96
+ scheduler.queue.sort((a, b) => (a.priority - b.priority) || (a.queuedAt - b.queuedAt));
97
+ return null;
98
+ }
99
+ logger.info(`[dsh-cron] Task "${task.title}" (${taskId}) skipped: ${conflictMsg}`);
100
+ scheduler.recordSkipped(taskId, `Skipped: ${conflictMsg}`);
101
+ return null;
102
+ }
103
+ }
104
+
82
105
  const overlapPolicy = task.overlapPolicy || 'skip';
83
106
  const active = scheduler.running.get(taskId);
84
107
  if (active) {
@@ -112,6 +135,9 @@ export function beginRun(scheduler, task, taskId, options = {}) {
112
135
  concurrencyGroup: group || 'default',
113
136
  };
114
137
  scheduler.running.set(taskId, currentRun);
138
+ if (scheduler.scopeLocks) {
139
+ scheduler.scopeLocks.acquire(task, taskId);
140
+ }
115
141
  return currentRun;
116
142
  }
117
143
 
@@ -225,13 +251,37 @@ export async function executeTask(scheduler, taskId, options = {}) {
225
251
  const currentRun = scheduler.beginRun(task, taskId, options);
226
252
  if (currentRun === null) return null;
227
253
 
254
+ // Input Hash check (#408): skip execution if input files are unchanged
255
+ const rawInputPaths = task.inputHashPaths;
256
+ const hasInputCheck = (Array.isArray(rawInputPaths) ? rawInputPaths.length > 0 : Boolean(rawInputPaths)) || task.skipIfUnchanged;
257
+ if (hasInputCheck && !options.dryRun && !options.forceRun) {
258
+ const cwd = scheduler.runner?.resolveCwd ? scheduler.runner.resolveCwd(task, scheduler.ctx) : (task.cwd || process.cwd());
259
+ const currentHash = await computeTaskInputHash(cwd, rawInputPaths && rawInputPaths.length > 0 ? rawInputPaths : ['.']);
260
+ if (currentHash && task.lastInputHash && task.lastInputHash === currentHash) {
261
+ logger.info(`[dsh-cron] Task "${task.title}" (${taskId}) skipped: inputs unchanged (${currentHash})`);
262
+ if (scheduler.scopeLocks) scheduler.scopeLocks.release(task, taskId);
263
+ scheduler.running.delete(taskId);
264
+ scheduler.recordSkipped(taskId, `Skipped: inputs unchanged (${currentHash})`);
265
+ if (typeof scheduler.drainQueue === 'function') scheduler.drainQueue();
266
+ return {
267
+ ok: true,
268
+ status: 'skipped',
269
+ skippedReason: 'inputs unchanged',
270
+ inputHash: currentHash,
271
+ };
272
+ }
273
+ options.currentInputHash = currentHash;
274
+ }
275
+
228
276
  const preflightStart = Date.now();
229
277
  const preflight = await executePreflight(task);
230
278
  const preflightDurationMs = Date.now() - preflightStart;
231
279
  if (!preflight.ok) {
232
280
  logger.info(`[dsh-cron] task "${task.title}" (${taskId}) skipped: ${preflight.reason}`);
281
+ if (scheduler.scopeLocks) scheduler.scopeLocks.release(task, taskId);
233
282
  scheduler.running.delete(taskId);
234
283
  scheduler.recordSkipped(taskId, `Preflight check skipped: ${preflight.reason}`);
284
+ if (typeof scheduler.drainQueue === 'function') scheduler.drainQueue();
235
285
  return null;
236
286
  }
237
287
 
@@ -3,6 +3,7 @@ import { bestEffort } from '../best-effort.js';
3
3
  import { Cron } from 'croner';
4
4
  import { FileSystemWatcherManager } from '../watcher.js';
5
5
  import { parseNaturalSchedule } from '../nl-schedule.js';
6
+ import { ScopeLockManager } from '../scope-locks.js';
6
7
 
7
8
  const MAX_TIMEOUT_MS = 2147483647; // 2^31 - 1 ms (~24.85 days)
8
9
  import {
@@ -337,6 +338,7 @@ export class TaskScheduler {
337
338
  this.groupLimits = opts.groupLimits instanceof Map ? opts.groupLimits : new Map(Object.entries(opts.groupLimits || {}));
338
339
  this.heartbeatTimer = null;
339
340
  this.watcherManager = new FileSystemWatcherManager(this);
341
+ this.scopeLocks = new ScopeLockManager();
340
342
  this.logger = opts.logger || null;
341
343
  this.isStopped = false;
342
344
  this.generation = 0;
@@ -669,6 +671,50 @@ export class TaskScheduler {
669
671
  return shouldUseFallback(task, outcome);
670
672
  }
671
673
 
674
+ drainQueue() {
675
+ if (this.isStopped || this.queue.length === 0) return;
676
+ if (this.maxConcurrent > 0 && this.running.size >= this.maxConcurrent) return;
677
+
678
+ let admittedIndex = -1;
679
+ for (let i = 0; i < this.queue.length; i++) {
680
+ const candidate = this.queue[i];
681
+ const queuedTask = this.store.get(candidate.taskId);
682
+ if (!queuedTask || queuedTask.status !== 'active') {
683
+ this.queue.splice(i, 1);
684
+ i--;
685
+ continue;
686
+ }
687
+ const qGroup = queuedTask.concurrencyGroup && queuedTask.concurrencyGroup !== 'default'
688
+ ? String(queuedTask.concurrencyGroup).trim()
689
+ : null;
690
+ const qLimit = this.getGroupLimit ? this.getGroupLimit(qGroup) : (qGroup ? 1 : 0);
691
+ if (qGroup && qLimit > 0) {
692
+ const inGroup = this.getRunningGroupCount ? this.getRunningGroupCount(qGroup) : 0;
693
+ if (inGroup >= qLimit) {
694
+ continue;
695
+ }
696
+ }
697
+
698
+ if (this.scopeLocks && !this.scopeLocks.canAcquire(queuedTask, candidate.taskId).ok) {
699
+ continue;
700
+ }
701
+
702
+ admittedIndex = i;
703
+ break;
704
+ }
705
+
706
+ if (admittedIndex !== -1) {
707
+ const nextItem = this.queue.splice(admittedIndex, 1)[0];
708
+ setImmediate(() => {
709
+ if (!this.isStopped) {
710
+ this.runTask(nextItem.taskId, nextItem.options || {}).catch((_runErr) => {
711
+ bestEffort('drain-queued-task', () => {}, this.logger);
712
+ });
713
+ }
714
+ });
715
+ }
716
+ }
717
+
672
718
  async runTask(taskId, options = {}) {
673
719
  if (this.isStopped) return null;
674
720
  return executeTask(this, taskId, options);
@@ -0,0 +1,189 @@
1
+ // @ts-check
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Normalize an array or string of relative scopes.
6
+ * Leading slashes or './' are stripped, backslashes replaced with '/',
7
+ * trailing slashes removed (except root), empty strings filtered.
8
+ *
9
+ * @param {string[]|string|null|undefined} scopes
10
+ * @returns {string[]}
11
+ */
12
+ export function normalizeScopes(scopes) {
13
+ if (!scopes) return [];
14
+ const list = Array.isArray(scopes)
15
+ ? scopes
16
+ : String(scopes).split(/[\n,]+/).map((s) => s.trim());
17
+
18
+ const result = new Set();
19
+ for (let s of list) {
20
+ if (!s || typeof s !== 'string') continue;
21
+ let norm = s.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
22
+ norm = norm.replace(/\/+$/, '');
23
+ if (norm.length > 0) {
24
+ result.add(norm);
25
+ }
26
+ }
27
+ return Array.from(result);
28
+ }
29
+
30
+ /**
31
+ * Check if two path scopes overlap.
32
+ * Overlap means:
33
+ * - A is equal to B ('src' === 'src')
34
+ * - A is parent of B ('src' is parent of 'src/components')
35
+ * - B is parent of A ('src/components' has parent 'src')
36
+ * - Either is root '.' or '*'
37
+ *
38
+ * @param {string} scopeA
39
+ * @param {string} scopeB
40
+ * @returns {boolean}
41
+ */
42
+ export function scopesOverlap(scopeA, scopeB) {
43
+ if (!scopeA || !scopeB) return false;
44
+ const a = scopeA.replace(/\/+$/, '');
45
+ const b = scopeB.replace(/\/+$/, '');
46
+ if (a === '.' || a === '*' || b === '.' || b === '*') return true;
47
+ if (a === b) return true;
48
+ if (b.startsWith(a + '/')) return true;
49
+ if (a.startsWith(b + '/')) return true;
50
+ return false;
51
+ }
52
+
53
+ /**
54
+ * Check if any scope in scopes1 overlaps with any scope in scopes2.
55
+ *
56
+ * @param {string[]|string} scopes1
57
+ * @param {string[]|string} scopes2
58
+ * @returns {{ conflict: true, scopeA: string, scopeB: string } | null}
59
+ */
60
+ export function hasScopeConflict(scopes1, scopes2) {
61
+ const norm1 = normalizeScopes(scopes1);
62
+ const norm2 = normalizeScopes(scopes2);
63
+ if (norm1.length === 0 || norm2.length === 0) return null;
64
+ for (const s1 of norm1) {
65
+ for (const s2 of norm2) {
66
+ if (scopesOverlap(s1, s2)) {
67
+ return { conflict: true, scopeA: s1, scopeB: s2 };
68
+ }
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * ScopeLockManager
76
+ * Tracks active write scopes per workspace to prevent concurrent conflicts.
77
+ */
78
+ export class ScopeLockManager {
79
+ constructor() {
80
+ /** @type {Map<string, Map<string, Set<string>>>} */
81
+ this.locks = new Map();
82
+ }
83
+
84
+ /**
85
+ * Determine key for scoping (workspaceId or cwd).
86
+ *
87
+ * @param {any} task
88
+ * @returns {string}
89
+ */
90
+ getWorkspaceKey(task) {
91
+ if (task?.workspaceId && String(task.workspaceId).trim()) {
92
+ return 'ws:' + String(task.workspaceId).trim();
93
+ }
94
+ if (task?.cwd && String(task.cwd).trim()) {
95
+ return 'cwd:' + path.normalize(String(task.cwd).trim());
96
+ }
97
+ return 'default';
98
+ }
99
+
100
+ /**
101
+ * Check if task writeScopes can be acquired without conflict.
102
+ *
103
+ * @param {any} task
104
+ * @param {string} taskId
105
+ * @returns {{ ok: true } | { ok: false, conflictTaskId: string, conflictingScope: string, heldScope: string, workspaceKey: string }}
106
+ */
107
+ canAcquire(task, taskId) {
108
+ const scopes = normalizeScopes(task?.writeScopes);
109
+ if (scopes.length === 0) return { ok: true };
110
+
111
+ // Isolated worktrees don't conflict with main workspace files
112
+ if (task?.worktree) return { ok: true };
113
+
114
+ const wsKey = this.getWorkspaceKey(task);
115
+ const activeTasks = this.locks.get(wsKey);
116
+ if (!activeTasks || activeTasks.size === 0) return { ok: true };
117
+
118
+ for (const [activeTaskId, activeScopes] of activeTasks.entries()) {
119
+ if (activeTaskId === taskId) continue;
120
+ const conflict = hasScopeConflict(scopes, Array.from(activeScopes));
121
+ if (conflict) {
122
+ return {
123
+ ok: false,
124
+ conflictTaskId: activeTaskId,
125
+ conflictingScope: conflict.scopeA,
126
+ heldScope: conflict.scopeB,
127
+ workspaceKey: wsKey,
128
+ };
129
+ }
130
+ }
131
+ return { ok: true };
132
+ }
133
+
134
+ /**
135
+ * Register active write scopes for a running task.
136
+ *
137
+ * @param {any} task
138
+ * @param {string} taskId
139
+ * @returns {boolean}
140
+ */
141
+ acquire(task, taskId) {
142
+ const scopes = normalizeScopes(task?.writeScopes);
143
+ if (scopes.length === 0 || task?.worktree) return true;
144
+
145
+ const wsKey = this.getWorkspaceKey(task);
146
+ if (!this.locks.has(wsKey)) {
147
+ this.locks.set(wsKey, new Map());
148
+ }
149
+ this.locks.get(wsKey).set(taskId, new Set(scopes));
150
+ return true;
151
+ }
152
+
153
+ /**
154
+ * Release active write scopes when a task finishes.
155
+ *
156
+ * @param {any} task
157
+ * @param {string} taskId
158
+ */
159
+ release(task, taskId) {
160
+ const wsKey = this.getWorkspaceKey(task);
161
+ const activeTasks = this.locks.get(wsKey);
162
+ if (activeTasks) {
163
+ activeTasks.delete(taskId);
164
+ if (activeTasks.size === 0) {
165
+ this.locks.delete(wsKey);
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Get active locks for inspection.
172
+ *
173
+ * @param {string} workspaceKey
174
+ * @returns {Array<{ taskId: string, scopes: string[] }>}
175
+ */
176
+ getActiveScopes(workspaceKey) {
177
+ const activeTasks = this.locks.get(workspaceKey);
178
+ if (!activeTasks) return [];
179
+ const all = [];
180
+ for (const [taskId, scopes] of activeTasks.entries()) {
181
+ all.push({ taskId, scopes: Array.from(scopes) });
182
+ }
183
+ return all;
184
+ }
185
+
186
+ clear() {
187
+ this.locks.clear();
188
+ }
189
+ }
@@ -95,6 +95,10 @@ export const TaskSchema = z.object({
95
95
  previousScript: z.string(),
96
96
  swarm: z.any(),
97
97
  gitDiff: z.any(),
98
+ writeScopes: z.any(),
99
+ inputHashPaths: z.any(),
100
+ skipIfUnchanged: z.boolean().default(false),
101
+ lastInputHash: z.string().default(''),
98
102
  maxMemoryMb: z.number().min(0).default(0),
99
103
  executionTimeoutMs: z.number().min(0).default(900000),
100
104
  maxLogBytesPerRun: z.number().min(0).default(5 * 1024 * 1024),
@@ -104,6 +104,10 @@ export const PATCHABLE_TASK_FIELDS = [
104
104
  'cpus',
105
105
  'maxArchiveMonths',
106
106
  'gitDiff',
107
+ 'writeScopes',
108
+ 'inputHashPaths',
109
+ 'skipIfUnchanged',
110
+ 'lastInputHash',
107
111
  ];
108
112
 
109
113
  /** Fields a duplicate inherits; anything else is runtime state, not config. */
@@ -9,6 +9,8 @@ import { validateTaskType } from './task-transfer.js';
9
9
  import { parseScheduleExpression } from './scheduler.js';
10
10
  import { CHANNEL_IDS } from './channels.js';
11
11
  import { redactTaskSecrets } from './http-utils.js';
12
+ import { normalizeScopes } from './scope-locks.js';
13
+ import { normalizeInputHashPaths } from './input-hash.js';
12
14
  import { sanitizeDependsOn, sanitizeJoinPolicy, validateDAG } from './dag.js';
13
15
 
14
16
  export function sanitizeFileWatch(fw) {
@@ -62,6 +64,10 @@ export function executeCreateTask(store, scheduler, args) {
62
64
  swarm: args.swarm !== undefined ? sanitizeSwarmConfig(args.swarm) : undefined,
63
65
  elseTask: args.elseTask ? String(args.elseTask).trim() : undefined,
64
66
  autoHeal: args.autoHeal !== undefined ? Boolean(args.autoHeal) : undefined,
67
+ writeScopes: args.writeScopes !== undefined ? normalizeScopes(args.writeScopes) : undefined,
68
+ inputHashPaths: args.inputHashPaths !== undefined ? normalizeInputHashPaths(args.inputHashPaths) : undefined,
69
+ skipIfUnchanged: args.skipIfUnchanged !== undefined ? Boolean(args.skipIfUnchanged) : undefined,
70
+ lastInputHash: args.lastInputHash ? String(args.lastInputHash).trim() : undefined,
65
71
  selfHealing: args.selfHealing && typeof args.selfHealing === 'object' ? {
66
72
  autoApply: Boolean(args.selfHealing.autoApply),
67
73
  lastPatchedAt: Number(args.selfHealing.lastPatchedAt) || 0,
package/lib/task-patch.js CHANGED
@@ -20,6 +20,8 @@ import { normalizeTaskType, CODE_EXECUTING_TYPES, EXTERNAL_RUNTIMES } from './ru
20
20
  import { PATCHABLE_TASK_FIELDS, validateTaskType } from './task-transfer.js';
21
21
  import { pickPatchableFields, restoreTaskSecrets } from './http-utils.js';
22
22
  import { unknownChannelIds } from './channels.js';
23
+ import { normalizeScopes } from './scope-locks.js';
24
+ import { normalizeInputHashPaths } from './input-hash.js';
23
25
  import { isConfigOwned, configOwnedMessage } from './config-jobs.js';
24
26
 
25
27
  /** True when a patch changes a task into a type that executes code. */
@@ -132,6 +134,18 @@ export function buildTaskPatch(current, body) {
132
134
  if (patch.autoHeal !== undefined) {
133
135
  patch.autoHeal = Boolean(patch.autoHeal);
134
136
  }
137
+ if (patch.writeScopes !== undefined) {
138
+ patch.writeScopes = normalizeScopes(patch.writeScopes);
139
+ }
140
+ if (patch.inputHashPaths !== undefined) {
141
+ patch.inputHashPaths = normalizeInputHashPaths(patch.inputHashPaths);
142
+ }
143
+ if (patch.skipIfUnchanged !== undefined) {
144
+ patch.skipIfUnchanged = Boolean(patch.skipIfUnchanged);
145
+ }
146
+ if (patch.lastInputHash !== undefined) {
147
+ patch.lastInputHash = String(patch.lastInputHash || '').trim();
148
+ }
135
149
  if (patch.selfHealing !== undefined && patch.selfHealing && typeof patch.selfHealing === 'object') {
136
150
  patch.selfHealing = {
137
151
  autoApply: Boolean(patch.selfHealing.autoApply),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-cron",
3
- "version": "0.3.30",
3
+ "version": "0.3.32",
4
4
  "description": "Background automation runner for DSH: isolated agent runs, script/HTTP/SSH/Docker runtimes, cost guard, notifications, heartbeats.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",