opencode-windows-scheduler 0.0.0-stage → 1.0.0

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.
Files changed (172) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/CROSS_PLATFORM.md +113 -0
  3. package/LICENSE +21 -0
  4. package/README.md +173 -2
  5. package/README.ru.md +131 -0
  6. package/ROADMAP-STRATEGY.md +217 -0
  7. package/ROADMAP.md +87 -0
  8. package/dist/core/cron-to-schtasks.d.ts +20 -0
  9. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  10. package/dist/core/cron-to-schtasks.js +233 -0
  11. package/dist/core/dry-run.d.ts +44 -0
  12. package/dist/core/dry-run.d.ts.map +1 -0
  13. package/dist/core/dry-run.js +252 -0
  14. package/dist/core/file-watcher.d.ts +31 -0
  15. package/dist/core/file-watcher.d.ts.map +1 -0
  16. package/dist/core/file-watcher.js +128 -0
  17. package/dist/core/lock.d.ts +43 -0
  18. package/dist/core/lock.d.ts.map +1 -0
  19. package/dist/core/lock.js +118 -0
  20. package/dist/core/matrix.d.ts +167 -0
  21. package/dist/core/matrix.d.ts.map +1 -0
  22. package/dist/core/matrix.js +687 -0
  23. package/dist/core/ps-wrapper.d.ts +60 -0
  24. package/dist/core/ps-wrapper.d.ts.map +1 -0
  25. package/dist/core/ps-wrapper.js +538 -0
  26. package/dist/core/record-history.d.ts +14 -0
  27. package/dist/core/record-history.d.ts.map +1 -0
  28. package/dist/core/record-history.js +360 -0
  29. package/dist/core/scheduler/index.d.ts +20 -0
  30. package/dist/core/scheduler/index.d.ts.map +1 -0
  31. package/dist/core/scheduler/index.js +32 -0
  32. package/dist/core/scheduler/linux.d.ts +32 -0
  33. package/dist/core/scheduler/linux.d.ts.map +1 -0
  34. package/dist/core/scheduler/linux.js +115 -0
  35. package/dist/core/scheduler/logs.d.ts +11 -0
  36. package/dist/core/scheduler/logs.d.ts.map +1 -0
  37. package/dist/core/scheduler/logs.js +34 -0
  38. package/dist/core/scheduler/mac.d.ts +39 -0
  39. package/dist/core/scheduler/mac.d.ts.map +1 -0
  40. package/dist/core/scheduler/mac.js +175 -0
  41. package/dist/core/scheduler/posix.d.ts +40 -0
  42. package/dist/core/scheduler/posix.d.ts.map +1 -0
  43. package/dist/core/scheduler/posix.js +86 -0
  44. package/dist/core/scheduler/registry.d.ts +36 -0
  45. package/dist/core/scheduler/registry.d.ts.map +1 -0
  46. package/dist/core/scheduler/registry.js +56 -0
  47. package/dist/core/scheduler/types.d.ts +63 -0
  48. package/dist/core/scheduler/types.d.ts.map +1 -0
  49. package/dist/core/scheduler/types.js +1 -0
  50. package/dist/core/scheduler/windows.d.ts +47 -0
  51. package/dist/core/scheduler/windows.d.ts.map +1 -0
  52. package/dist/core/scheduler/windows.js +375 -0
  53. package/dist/core/wrappers/bash.d.ts +58 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -0
  55. package/dist/core/wrappers/bash.js +223 -0
  56. package/dist/db/history-repo.d.ts +69 -0
  57. package/dist/db/history-repo.d.ts.map +1 -0
  58. package/dist/db/history-repo.js +150 -0
  59. package/dist/db/index.d.ts +47 -0
  60. package/dist/db/index.d.ts.map +1 -0
  61. package/dist/db/index.js +120 -0
  62. package/dist/db/metrics-repo.d.ts +43 -0
  63. package/dist/db/metrics-repo.d.ts.map +1 -0
  64. package/dist/db/metrics-repo.js +95 -0
  65. package/dist/db/migrate.d.ts +24 -0
  66. package/dist/db/migrate.d.ts.map +1 -0
  67. package/dist/db/migrate.js +237 -0
  68. package/dist/db/recovery.d.ts +11 -0
  69. package/dist/db/recovery.d.ts.map +1 -0
  70. package/dist/db/recovery.js +38 -0
  71. package/dist/db/schema.d.ts +24 -0
  72. package/dist/db/schema.d.ts.map +1 -0
  73. package/dist/db/schema.js +97 -0
  74. package/dist/db/settings-repo.d.ts +8 -0
  75. package/dist/db/settings-repo.d.ts.map +1 -0
  76. package/dist/db/settings-repo.js +27 -0
  77. package/dist/db/tasks-repo.d.ts +26 -0
  78. package/dist/db/tasks-repo.d.ts.map +1 -0
  79. package/dist/db/tasks-repo.js +120 -0
  80. package/dist/db/templates-repo.d.ts +17 -0
  81. package/dist/db/templates-repo.d.ts.map +1 -0
  82. package/dist/db/templates-repo.js +57 -0
  83. package/dist/gui-experimental.cjs +1 -0
  84. package/dist/history.d.ts +53 -0
  85. package/dist/history.d.ts.map +1 -0
  86. package/dist/history.js +57 -0
  87. package/dist/index.d.ts +156 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +2077 -0
  90. package/dist/notifications.d.ts +45 -0
  91. package/dist/notifications.d.ts.map +1 -0
  92. package/dist/notifications.js +135 -0
  93. package/dist/rpc.d.ts +2052 -0
  94. package/dist/rpc.d.ts.map +1 -0
  95. package/dist/rpc.js +863 -0
  96. package/dist/schtasks.d.ts +32 -0
  97. package/dist/schtasks.d.ts.map +1 -0
  98. package/dist/schtasks.js +45 -0
  99. package/dist/server.d.ts +106 -0
  100. package/dist/server.d.ts.map +1 -0
  101. package/dist/server.js +1478 -0
  102. package/dist/settings.d.ts +43 -0
  103. package/dist/settings.d.ts.map +1 -0
  104. package/dist/settings.js +96 -0
  105. package/dist/shared/jobs-view.d.ts +21 -0
  106. package/dist/shared/jobs-view.d.ts.map +1 -0
  107. package/dist/shared/jobs-view.js +28 -0
  108. package/dist/skill.d.ts +15 -0
  109. package/dist/skill.d.ts.map +1 -0
  110. package/dist/skill.js +93 -0
  111. package/dist/task-transfer.d.ts +176 -0
  112. package/dist/task-transfer.d.ts.map +1 -0
  113. package/dist/task-transfer.js +442 -0
  114. package/dist/templates.d.ts +57 -0
  115. package/dist/templates.d.ts.map +1 -0
  116. package/dist/templates.js +16 -0
  117. package/dist/types.d.ts +78 -0
  118. package/dist/types.d.ts.map +1 -0
  119. package/dist/types.js +88 -0
  120. package/dist/workspaces.d.ts +55 -0
  121. package/dist/workspaces.d.ts.map +1 -0
  122. package/dist/workspaces.js +183 -0
  123. package/docs/ARCHITECTURE.md +302 -0
  124. package/docs/FEATURES.md +288 -0
  125. package/docs/MIGRATION.md +266 -0
  126. package/docs/dashboard.png +0 -0
  127. package/gui-experimental.cjs +2 -0
  128. package/index.js +1 -0
  129. package/package.json +92 -4
  130. package/scripts/demo-dashboard.mjs +199 -0
  131. package/skills/scheduled-job-best-practices/SKILL.md +155 -0
  132. package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
  133. package/src/core/cron-to-schtasks.ts +269 -0
  134. package/src/core/dry-run.ts +315 -0
  135. package/src/core/file-watcher.ts +171 -0
  136. package/src/core/lock.ts +134 -0
  137. package/src/core/matrix.ts +907 -0
  138. package/src/core/ps-wrapper.ts +572 -0
  139. package/src/core/record-history.ts +493 -0
  140. package/src/core/scheduler/index.ts +44 -0
  141. package/src/core/scheduler/linux.ts +125 -0
  142. package/src/core/scheduler/logs.ts +37 -0
  143. package/src/core/scheduler/mac.ts +222 -0
  144. package/src/core/scheduler/posix.ts +111 -0
  145. package/src/core/scheduler/registry.ts +93 -0
  146. package/src/core/scheduler/types.ts +67 -0
  147. package/src/core/scheduler/windows.ts +469 -0
  148. package/src/core/wrappers/bash.ts +282 -0
  149. package/src/db/history-repo.ts +303 -0
  150. package/src/db/index.ts +166 -0
  151. package/src/db/metrics-repo.ts +158 -0
  152. package/src/db/migrate.ts +322 -0
  153. package/src/db/recovery.ts +46 -0
  154. package/src/db/schema.ts +109 -0
  155. package/src/db/settings-repo.ts +31 -0
  156. package/src/db/tasks-repo.ts +162 -0
  157. package/src/db/templates-repo.ts +77 -0
  158. package/src/gui.tsx +2725 -0
  159. package/src/history.ts +107 -0
  160. package/src/index.ts +2672 -0
  161. package/src/notifications.ts +174 -0
  162. package/src/rpc.ts +933 -0
  163. package/src/schtasks.ts +75 -0
  164. package/src/server.ts +1663 -0
  165. package/src/settings.ts +157 -0
  166. package/src/shared/jobs-view.ts +38 -0
  167. package/src/skill.ts +113 -0
  168. package/src/task-transfer.ts +648 -0
  169. package/src/templates.ts +67 -0
  170. package/src/tui.tsx +46 -0
  171. package/src/types.ts +145 -0
  172. package/src/workspaces.ts +236 -0
@@ -0,0 +1,155 @@
1
+ ---
2
+ name: Scheduled Job Best Practices
3
+ description: Use when the user wants recurring or event-driven automation (cron, file changes, MCP events), multi-repository fan-out, or agent pipelines. Covers safe defaults, prompt design, Quality Gates, matrix builds, DAG dependencies and post-incident diagnosis with the scheduler tools.
4
+ ---
5
+
6
+ # Scheduled Job Best Practices
7
+
8
+ Use this skill whenever the user asks to automate something on a schedule, on a file change,
9
+ on an MCP event, or as a multi-step pipeline. The goal is automation that is safe, cheap,
10
+ idempotent and debuggable a month later.
11
+
12
+ Respond in the user's language. This document is in English for portability.
13
+
14
+ ## 1. Start by looking at what already exists
15
+
16
+ Call `list_tasks` before creating anything. If a similar task exists, prefer `update_task`
17
+ (partial update, matrix clones are synchronized) over delete + create. Automation that
18
+ silently duplicates work is worse than no automation.
19
+
20
+ Check the returned fields: schedule, trigger, working directory, model, dependencies, matrix
21
+ summary, last run.
22
+
23
+ ## 2. Choose the simplest shape that works
24
+
25
+ | User need | Shape | Why |
26
+ | --- | --- | --- |
27
+ | "Every morning / every hour / weekly" | `schedule_task` with cron | Durable OS-level schedule, survives restarts |
28
+ | "When this file changes" | `triggerType: "file"` + `watchPath` | No polling; the watcher debounces bursts |
29
+ | "When my MCP server reports an event" | `triggerType: "mcp-event"` + `mcpEvent` | Event-driven, no wasted runs |
30
+ | "Same work in N repositories" | `matrix.workspaceIds` | One definition, isolated clones, aggregated status |
31
+ | "A then B then C" | `dependsOn` + `nextTaskOnSuccess` / `nextTaskOnError` | Explicit DAG, failures stop the line |
32
+ | "Try again if it fails" | `retryCount` + `retryDelay` | Handles flaky networks and rate limits |
33
+
34
+ Do not use a 5-field cron for a one-off reminder. Do not build a pipeline with chained
35
+ prompts inside a single task when `dependsOn` exists: a failed step would be invisible.
36
+
37
+ ## 3. Write prompts that survive without context
38
+
39
+ Every run starts from a clean slate: no chat history, no memory of the previous run, nobody
40
+ to answer questions. A good prompt states:
41
+
42
+ 1. **Goal** — the outcome in one sentence.
43
+ 2. **Scope** — exact paths, repositories or modules to touch.
44
+ 3. **Constraints** — what must not change, tool limits, style rules.
45
+ 4. **Verification** — the command that proves success (this is the Quality Gate).
46
+ 5. **Output** — where to write the report and what to include (counts, links, failures).
47
+
48
+ Bad: `Check the repo and fix problems.`
49
+ Good: `In ./services/api run the test suite. If tests fail, fix only failures caused by
50
+ type errors, then re-run until green or 20 minutes elapse. Write a summary to
51
+ reports/nightly-api.md with the failing test names and the commit you started from.`
52
+
53
+ Never ask the agent to "ask the user" in a scheduled prompt — nobody is there. If a decision
54
+ is genuinely ambiguous, tell it to stop and write the question into the report.
55
+
56
+ ## 4. Safety defaults
57
+
58
+ - **Least privilege**: set `allowedTools` / `deniedTools`. Read-only monitoring jobs should
59
+ not be allowed to `write` or run destructive shell commands.
60
+ - **Timeout**: always set `timeoutSeconds` for jobs that call networks or models. Default
61
+ timeouts are a safety net, not a plan.
62
+ - **Quality Gate**: pass `qualityGate` whenever a machine-checkable success criterion exists
63
+ (`npm test`, `pytest -q`, `curl -f`, `git diff --quiet`). A run that "looks successful" is
64
+ not evidence.
65
+ - **No secrets in prompts**: prompts are stored in plain text and appear in logs. Reference
66
+ environment variables or files instead.
67
+ - **Idempotent by design**: a job may run twice (retry, catch-up after downtime, manual run).
68
+ Prefer "ensure state" over "append" — e.g. rewrite a report file rather than appending.
69
+ - **Blast radius**: avoid `git push --force`, `rm -rf`, mass dependency upgrades or
70
+ production deploys without a Quality Gate and a manual `run_task_now` smoke test first.
71
+
72
+ ## 5. Matrix builds (multi-repository)
73
+
74
+ Use a matrix when the same prompt must run in several workspaces:
75
+
76
+ - `matrix.workspaceIds` — the repositories, referenced by workspace ID (call
77
+ `manage_workspaces` with `action: "list"` to discover them).
78
+ - `matrix.strategy` — `parallel` (default) or `sequential`.
79
+ - `matrix.failureMode` — `continue` (default, aggregated as `partial`) or `stop`.
80
+ - `matrix.concurrency` — cap simultaneous clones; respect machine and API limits. Keep it
81
+ small (2–4) unless the work is purely local.
82
+ - `matrix.overrides` — per-workspace prompt/model/qualityGate/hooks when one repository
83
+ differs (different package manager, stricter gate).
84
+ - `matrix.createAggregator` — creates a follow-up task that runs once after all clones.
85
+
86
+ Rules of thumb:
87
+
88
+ - The matrix parent never runs itself; only its clones do. Do not set `workspaceId` on the
89
+ parent — it is a validation error to combine it with `matrix`.
90
+ - A dependency on a matrix parent waits for **all** clones to succeed.
91
+ - If clones are inherently independent (linting, docs), `failureMode: "continue"` gives a
92
+ useful aggregate. If one failure makes the rest pointless (deploy), use `"stop"`.
93
+ - After editing a matrix parent with `update_task`, clones are diffed and synchronized;
94
+ running clones are left alone.
95
+
96
+ ## 6. DAG rules
97
+
98
+ - `dependsOn` lists task names that must have succeeded (their latest run) before this task
99
+ starts.
100
+ - `nextTaskOnSuccess` / `nextTaskOnError` chain a single follow-up run; use them for
101
+ notifications and rollbacks.
102
+ - Keep chains short and named by intent (`deploy` → `smoke-tests` → `notify-release`).
103
+ - Cycles and self-dependencies are rejected; if a chain grows past 4–5 nodes, consider one
104
+ task with an explicit internal checklist instead.
105
+
106
+ ## 7. Validate before you commit
107
+
108
+ 1. `dry_run` with the task name (or without a name for the whole pipeline): shows order,
109
+ dependencies, matrix fan-out, estimated duration and cost. Nothing is executed.
110
+ 2. Create the task with `schedule_task`.
111
+ 3. `run_task_now` once and inspect `get_history` / `get_task_logs`. A schedule that has never
112
+ run successfully is a liability.
113
+ 4. Only then tell the user it is ready, and state the cron expression in plain language
114
+ ("every weekday at 09:00 local time").
115
+
116
+ ## 8. Diagnosing failures later
117
+
118
+ - `get_history` filtered by `taskName` and `status` — statuses: `running`, `success`, `error`,
119
+ `timeout`, `partial`.
120
+ - `get_task_logs` with `lines` — tail of the wrapper log; use it to distinguish model failure,
121
+ Quality Gate failure, timeout and lock-skip.
122
+ - Matrix problems: `matrix_control` with `action: "results"` for counters, `action: "cancel"`
123
+ to stop pending clones, `action: "cleanup"` to remove clones whose parent is gone.
124
+ - A timeout usually means the prompt is too broad. Split it or raise `timeoutSeconds`
125
+ deliberately.
126
+ - A skipped run (`already running`) means the previous run overran its interval; shorten the
127
+ prompt, raise the interval, or set a smaller timeout.
128
+
129
+ ## 9. Anti-patterns
130
+
131
+ | Anti-pattern | Consequence | Fix |
132
+ | --- | --- | --- |
133
+ | `* * * * *` with a heavy prompt | Runs overlap, lock-skips, cost spikes | Realistic interval + timeout |
134
+ | Prompt depending on chat context | Nonsense output at 03:00 | Self-contained prompt with paths |
135
+ | No Quality Gate on a "fixer" job | Broken code reported as success | `qualityGate: "npm test"` |
136
+ | Matrix with 20 workspaces, no concurrency cap | Machine and API saturation | `matrix.concurrency: 2–4` |
137
+ | Secrets inside the prompt | Leak into DB, logs and dashboard | Env vars or files |
138
+ | Deleting a matrix parent's clone by hand | Orphaned history, broken aggregate | `update_task` on the parent |
139
+ | Creating a duplicate instead of updating | Double runs, conflicting writes | `update_task` |
140
+
141
+ ## 10. Final checklist
142
+
143
+ Before saying the job is done, confirm:
144
+
145
+ - [ ] `list_tasks` checked; no duplicate exists.
146
+ - [ ] Trigger type matches the need (cron / file / MCP event).
147
+ - [ ] Prompt states goal, scope, constraints, verification and output.
148
+ - [ ] `timeoutSeconds` set; `qualityGate` set when checkable.
149
+ - [ ] `allowedTools` / `deniedTools` follow least privilege.
150
+ - [ ] Matrix: workspaces correct, concurrency capped, failure mode justified.
151
+ - [ ] `dry_run` reviewed.
152
+ - [ ] One successful `run_task_now` with clean `get_history`.
153
+ - [ ] Cron expressed in words for the user.
154
+
155
+ See `references/recipes.md` for complete examples.
@@ -0,0 +1,123 @@
1
+ # Recipes
2
+
3
+ Complete, copy-ready examples. Values in `<angle brackets>` are placeholders.
4
+
5
+ ## 1. Nightly dependency and test run
6
+
7
+ ```json
8
+ {
9
+ "name": "nightly-deps",
10
+ "schedule": "0 2 * * *",
11
+ "prompt": "In the repository root run `npm outdated` and `npm audit --omit=dev`. Do not upgrade majors. Apply only patch/minor security fixes, run `npm test` after each upgrade, and revert a package if tests fail. Write a summary to reports/nightly-deps.md: upgraded packages with versions, rejected upgrades and why, final test result.",
12
+ "workingDirectory": "<absolute path to repository>",
13
+ "timeoutSeconds": 2400,
14
+ "qualityGate": "npm test",
15
+ "retryCount": 1,
16
+ "retryDelay": 300,
17
+ "allowedTools": ["read", "write", "bash"],
18
+ "deniedTools": ["webfetch"]
19
+ }
20
+ ```
21
+
22
+ Why: bounded scope (no majors), machine-checkable gate, report for the morning.
23
+
24
+ ## 2. Weekday morning digest
25
+
26
+ ```json
27
+ {
28
+ "name": "morning-digest",
29
+ "schedule": "0 9 * * 1-5",
30
+ "prompt": "Collect: commits to main since the last working day (`git log --since=yesterday`), open pull requests (`gh pr list --state open`), and failed CI runs (`gh run list --status failure --limit 10`). Write a Russian-language digest to reports/digest-<date>.md with sections Commits / PRs / CI failures. If a command is unavailable, record that instead of failing.",
31
+ "workingDirectory": "<absolute path to repository>",
32
+ "timeoutSeconds": 900,
33
+ "allowedTools": ["read", "bash"]
34
+ }
35
+ ```
36
+
37
+ Why: read-only, tolerant of missing CLIs, output is the product.
38
+
39
+ ## 3. Regenerate a client when the API contract changes
40
+
41
+ ```json
42
+ {
43
+ "name": "regenerate-api-client",
44
+ "prompt": "openapi.yaml changed. Run `npm run generate:client`, then `npm run typecheck` and `npm test -- --runInBand`. If generation fails because of a schema error, do not edit the schema: write the failing path and reason to reports/api-client-error.md and stop. On success write the list of regenerated files to reports/api-client.md.",
45
+ "triggerType": "file",
46
+ "watchPath": "<absolute path to openapi.yaml>",
47
+ "workingDirectory": "<absolute path to client repository>",
48
+ "timeoutSeconds": 1200,
49
+ "qualityGate": "npm run typecheck",
50
+ "allowedTools": ["read", "write", "bash"]
51
+ }
52
+ ```
53
+
54
+ Why: event-driven instead of polling, explicit "do not touch the contract" constraint.
55
+
56
+ ## 4. Multi-repository lint and test matrix
57
+
58
+ ```json
59
+ {
60
+ "name": "repo-health",
61
+ "schedule": "0 6 * * 1",
62
+ "prompt": "Run the project's lint and test commands. Write a short report to reports/weekly-health.md with the command output summary. Fix nothing; only report.",
63
+ "timeoutSeconds": 1800,
64
+ "matrix": {
65
+ "workspaceIds": ["<frontend-id>", "<backend-id>", "<mobile-id>"],
66
+ "strategy": "parallel",
67
+ "failureMode": "continue",
68
+ "concurrency": 2,
69
+ "aggregation": "summary",
70
+ "overrides": {
71
+ "<mobile-id>": {
72
+ "qualityGate": "flutter test",
73
+ "prompt": "Run `flutter analyze` and `flutter test`. Write the summary to reports/weekly-health.md. Fix nothing."
74
+ }
75
+ }
76
+ },
77
+ "allowedTools": ["read", "bash"]
78
+ }
79
+ ```
80
+
81
+ Why: one definition, per-repository deviation in `overrides`, capped parallelism, partial
82
+ results still actionable.
83
+
84
+ ## 5. Deploy pipeline with gate and rollback
85
+
86
+ Tasks, in order:
87
+
88
+ 1. `deploy` — `schedule: "0 3 * * *"`, prompt builds and deploys, `qualityGate: "npm run smoke"`,
89
+ `timeoutSeconds: 1800`, `nextTaskOnSuccess: "notify-release"`,
90
+ `nextTaskOnError: "rollback"`.
91
+ 2. `notify-release` — posts a release message, `timeoutSeconds: 300`, read-only tools.
92
+ 3. `rollback` — restores the previous release, `qualityGate: "npm run smoke"`,
93
+ `triggerType: "file"` (started only by the chain), `timeoutSeconds: 1200`.
94
+
95
+ Verify the chain with `dry_run` for `deploy`: the output must show `deploy → notify-release`
96
+ and the error branch.
97
+
98
+ ## 6. Weekly cleanup of stale branches
99
+
100
+ ```json
101
+ {
102
+ "name": "stale-branches",
103
+ "schedule": "0 10 * * 5",
104
+ "prompt": "List merged remote branches older than 30 days (`git branch -r --merged main`). Do not delete `main`, `develop`, `release/*` or branches whose last commit is younger than 30 days. Delete the rest with `git push origin --delete`. Write the deleted and kept branches to reports/stale-branches.md with reasons.",
105
+ "workingDirectory": "<absolute path to repository>",
106
+ "timeoutSeconds": 600,
107
+ "qualityGate": "git diff --quiet",
108
+ "allowedTools": ["read", "bash"],
109
+ "deniedTools": ["write"]
110
+ }
111
+ ```
112
+
113
+ Why: explicit protected list, dry-run first, auditable report. Ask the user to run
114
+ `run_task_now` and confirm the report before enabling the schedule.
115
+
116
+ ## 7. Diagnosing a `partial` matrix
117
+
118
+ 1. `matrix_control` with `action: "results"` and the parent name → counters and the failing clones.
119
+ 2. `get_history` with `taskName: "<parent>-matrix-<workspace>"` and `status: "error"`.
120
+ 3. `get_task_logs` for that clone, `lines: 120`.
121
+ 4. Fix the cause (`update_task` on the parent for a definition bug, or the repository itself).
122
+ 5. Re-run only the failed clone with `run_task_now`, then confirm the aggregate becomes
123
+ `success`.
@@ -0,0 +1,269 @@
1
+ import type { CronConversion } from "../types.js";
2
+
3
+ /**
4
+ * Сообщение об ошибке, возвращаемое при встрече неподдерживаемого cron-выражения.
5
+ * Содержит описание поддерживаемого подмножества.
6
+ * Собрано конкатенацией, чтобы избежать последовательности закрывающего комментария внутри строк.
7
+ */
8
+ const UNSUPPORTED_ERROR =
9
+ "Неподдерживаемое cron-выражение.\n" +
10
+ "\n" +
11
+ "Поддерживаемое подмножество cron (5 полей: минута час день_месяца месяц день_недели):\n" +
12
+ " * * * * * -> MINUTE, каждую минуту (/mo 1)\n" +
13
+ " */N * * * * -> MINUTE, каждые N минут (/mo N)\n" +
14
+ " M H * * * -> DAILY, ежедневно в HH:MM (/st HH:MM)\n" +
15
+ " M H * * D -> WEEKLY, по неделям в день D в HH:MM (/d D /st HH:MM)\n" +
16
+ "\n" +
17
+ "Не поддерживаются: диапазоны (1-5), списки (1,2,3), комбинации месяца и дня недели,\n" +
18
+ "*/N на месяце или дне недели, а также любые другие сложные выражения.\n" +
19
+ "Пожалуйста, упростите расписание, используя одно из поддерживаемых выше выражений.";
20
+
21
+ /** Дни недели для schtasks /d (0 и 7 = воскресенье). */
22
+ const DAY_OF_WEEK_MAP: Record<string, string> = {
23
+ "0": "SUN",
24
+ "1": "MON",
25
+ "2": "TUE",
26
+ "3": "WED",
27
+ "4": "THU",
28
+ "5": "FRI",
29
+ "6": "SAT",
30
+ "7": "SUN",
31
+ };
32
+
33
+ /**
34
+ * Проверяет, является ли строка звездочкой "*".
35
+ */
36
+ function isStar(value: string): boolean {
37
+ return value === "*";
38
+ }
39
+
40
+ /**
41
+ * Проверяет, является ли строка шаблоном звездочка-слэш-N (N — положительное целое).
42
+ * Возвращает N или undefined.
43
+ */
44
+ function parseStep(value: string): number | undefined {
45
+ const match = value.match(/^\*\/(\d+)$/);
46
+ if (!match) return undefined;
47
+ const n = parseInt(match[1], 10);
48
+ return n > 0 ? n : undefined;
49
+ }
50
+
51
+ /**
52
+ * Проверяет, является ли строка одиночным целым числом в диапазоне [min, max].
53
+ * Возвращает число или undefined.
54
+ */
55
+ function parseIntInRange(value: string, min: number, max: number): number | undefined {
56
+ if (!/^\d+$/.test(value)) return undefined;
57
+ const n = parseInt(value, 10);
58
+ return n >= min && n <= max ? n : undefined;
59
+ }
60
+
61
+ /**
62
+ * Валидирует и преобразует 5-полевое cron-выражение во флаги schtasks.
63
+ * Возвращает CronConversion или выбрасывает Error с понятным сообщением.
64
+ */
65
+ export function convertCronToSchTasks(cron: string): CronConversion {
66
+ const fields = cron.trim().split(/\s+/);
67
+
68
+ if (fields.length !== 5) {
69
+ throw new Error(
70
+ "Ожидалось 5 полей cron-выражения (минута час день_месяца месяц день_недели), получено " +
71
+ fields.length +
72
+ ".\n\n" +
73
+ UNSUPPORTED_ERROR
74
+ );
75
+ }
76
+
77
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
78
+
79
+ // --- ПАТТЕРН 1: * * * * * -> MINUTE /mo 1 ---
80
+ if (
81
+ isStar(minute) &&
82
+ isStar(hour) &&
83
+ isStar(dayOfMonth) &&
84
+ isStar(month) &&
85
+ isStar(dayOfWeek)
86
+ ) {
87
+ return {
88
+ sc: "MINUTE",
89
+ extraFlags: ["/mo", "1"],
90
+ };
91
+ }
92
+
93
+ // --- ПАТТЕРН 2: */N * * * * -> MINUTE /mo N ---
94
+ const stepN = parseStep(minute);
95
+ if (
96
+ stepN !== undefined &&
97
+ isStar(hour) &&
98
+ isStar(dayOfMonth) &&
99
+ isStar(month) &&
100
+ isStar(dayOfWeek)
101
+ ) {
102
+ if (stepN > 1439) {
103
+ throw new Error(
104
+ "Интервал /mo " +
105
+ stepN +
106
+ " минут превышает максимально допустимый для schtasks (1439 минут).\n\n" +
107
+ UNSUPPORTED_ERROR
108
+ );
109
+ }
110
+ return {
111
+ sc: "MINUTE",
112
+ extraFlags: ["/mo", String(stepN)],
113
+ };
114
+ }
115
+
116
+ // --- ПАТТЕРН 3: M * * * * -> HOURLY /mo 1 /st 00:MM (каждый час в минуту M) ---
117
+ const mHourly = parseIntInRange(minute, 0, 59);
118
+ if (
119
+ mHourly !== undefined &&
120
+ isStar(hour) &&
121
+ isStar(dayOfMonth) &&
122
+ isStar(month) &&
123
+ isStar(dayOfWeek)
124
+ ) {
125
+ return {
126
+ sc: "HOURLY",
127
+ extraFlags: ["/mo", "1"],
128
+ startTime: "00:" + String(mHourly).padStart(2, "0"),
129
+ };
130
+ }
131
+
132
+ // --- ПАТТЕРН 4: M H * * * -> DAILY /st HH:MM ---
133
+ const m = parseIntInRange(minute, 0, 59);
134
+ const h = parseIntInRange(hour, 0, 23);
135
+ if (
136
+ m !== undefined &&
137
+ h !== undefined &&
138
+ isStar(dayOfMonth) &&
139
+ isStar(month) &&
140
+ isStar(dayOfWeek)
141
+ ) {
142
+ const startTime = String(h).padStart(2, "0") + ":" + String(m).padStart(2, "0");
143
+ return {
144
+ sc: "DAILY",
145
+ extraFlags: [],
146
+ startTime,
147
+ };
148
+ }
149
+
150
+ // --- ПАТТЕРН 4: M H * * D -> WEEKLY /d D /st HH:MM ---
151
+ const d = parseIntInRange(dayOfWeek, 0, 7);
152
+ if (
153
+ m !== undefined &&
154
+ h !== undefined &&
155
+ isStar(dayOfMonth) &&
156
+ isStar(month) &&
157
+ d !== undefined
158
+ ) {
159
+ const startTime = String(h).padStart(2, "0") + ":" + String(m).padStart(2, "0");
160
+ const dayName = DAY_OF_WEEK_MAP[String(d)];
161
+ return {
162
+ sc: "WEEKLY",
163
+ extraFlags: ["/d", dayName],
164
+ startTime,
165
+ days: dayName,
166
+ };
167
+ }
168
+
169
+ // Ни один поддерживаемый паттерн не совпал.
170
+ throw new Error(UNSUPPORTED_ERROR);
171
+ }
172
+
173
+ /**
174
+ * Вычисляет ближайшее прошедшее (<= now) время срабатывания для поддерживаемых
175
+ * cron-выражений. Нужно для восстановления пропущенных запусков (catch-up):
176
+ * сравнивая это время с историей, можно понять, выполнялась ли задача.
177
+ *
178
+ * Возвращает null, если выражение не поддерживается или не распознано.
179
+ */
180
+ export function previousRunTime(cron: string, now: Date = new Date()): Date | null {
181
+ const fields = cron.trim().split(/\s+/);
182
+ if (fields.length !== 5) return null;
183
+
184
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
185
+ const star = (value: string) => value === "*";
186
+ const intIn = (value: string, min: number, max: number): number | undefined => {
187
+ if (!/^\d+$/.test(value)) return undefined;
188
+ const n = parseInt(value, 10);
189
+ return n >= min && n <= max ? n : undefined;
190
+ };
191
+ const nowMs = now.getTime();
192
+
193
+ // * * * * * — каждую минуту: последняя граница минуты.
194
+ if (star(minute) && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
195
+ return new Date(Math.floor(nowMs / 60000) * 60000);
196
+ }
197
+
198
+ // */N * * * * — каждые N минут (выравнивание по эпохе, как /mo N в schtasks).
199
+ const step = /^\*\/(\d+)$/.exec(minute);
200
+ if (step && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
201
+ const n = parseInt(step[1], 10);
202
+ if (n > 0) {
203
+ const minutes = Math.floor(nowMs / 60000);
204
+ return new Date((minutes - (minutes % n)) * 60000);
205
+ }
206
+ return null;
207
+ }
208
+
209
+ // M * * * * — каждый час в минуту M.
210
+ const hourlyMinute = intIn(minute, 0, 59);
211
+ if (
212
+ hourlyMinute !== undefined &&
213
+ star(hour) &&
214
+ star(dayOfMonth) &&
215
+ star(month) &&
216
+ star(dayOfWeek)
217
+ ) {
218
+ const result = new Date(now);
219
+ result.setSeconds(0, 0);
220
+ result.setMinutes(hourlyMinute);
221
+ if (result.getTime() > nowMs) result.setHours(result.getHours() - 1);
222
+ return result;
223
+ }
224
+
225
+ const m = intIn(minute, 0, 59);
226
+ const h = intIn(hour, 0, 23);
227
+ if (m === undefined || h === undefined || !star(dayOfMonth) || !star(month)) {
228
+ return null;
229
+ }
230
+
231
+ // M H * * * — ежедневно в HH:MM.
232
+ if (star(dayOfWeek)) {
233
+ const result = new Date(now);
234
+ result.setSeconds(0, 0);
235
+ result.setHours(h, m, 0, 0);
236
+ if (result.getTime() > nowMs) result.setDate(result.getDate() - 1);
237
+ return result;
238
+ }
239
+
240
+ // M H * * D — еженедельно в день D (0 и 7 — воскресенье) в HH:MM.
241
+ const dow = intIn(dayOfWeek, 0, 7);
242
+ if (dow === undefined) return null;
243
+ const targetDow = dow === 7 ? 0 : dow;
244
+ const result = new Date(now);
245
+ result.setSeconds(0, 0);
246
+ result.setHours(h, m, 0, 0);
247
+ // Не больше 8 итераций: одна неделя гарантированно содержит нужный день.
248
+ for (let i = 0; i <= 8; i += 1) {
249
+ if (result.getTime() <= nowMs && result.getDay() === targetDow) return result;
250
+ result.setDate(result.getDate() - 1);
251
+ }
252
+ return null;
253
+ }
254
+
255
+ /**
256
+ * Формирует массив флагов расписания для schtasks на основе CronConversion.
257
+ * Включает /sc, /st (если есть), и дополнительные флаги (/mo, /d).
258
+ */
259
+ export function buildScheduleFlags(conversion: CronConversion): string[] {
260
+ const flags: string[] = ["/sc", conversion.sc];
261
+
262
+ if (conversion.startTime) {
263
+ flags.push("/st", conversion.startTime);
264
+ }
265
+
266
+ flags.push(...conversion.extraFlags);
267
+
268
+ return flags;
269
+ }