dsh-plan-steps 0.1.4 → 0.1.11

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.en.md CHANGED
@@ -16,11 +16,12 @@ plugin is a rewrite against DSH's event and slot model, not a port.
16
16
 
17
17
  | Piece | Effect |
18
18
  | --- | --- |
19
- | `plan_write` | Records a two-level plan: `level` 0 phases, `level` 1 sub-steps, an optional stable `step_id`, exactly one current item. A rewrite is checked for continuity: an existing id is never dropped, the current item is never removed or moved back to pending, and completed history keeps its position. |
19
+ | `plan_write` | Records a two-level plan: `level` 0 phases, `level` 1 sub-steps, an optional stable `step_id`, exactly one current item. A rewrite is checked for continuity: an existing id is never dropped, the current item is never removed or moved back to pending, and completed history keeps its position — once every item is completed the plan is history and a new one may replace it. |
20
20
  | `complete_step` | Signs the current `in_progress` item off, appends the advanced list as a `todo/write` snapshot (the panel follows), and names the next step. A phase signs off only after its sub-steps. |
21
21
  | guard | Refuses a `plan_write` / `todo_write` that turns an item `completed` while the host still has it open. |
22
22
  | turn hold | Steers the turn back when it is about to close with open items — once per turn. |
23
23
  | `wait_for_user` | Declares a wait, so that turn may end with the item open. |
24
+ | `abandon_plan` | Drops the current plan: the list clears, the panel disappears, and the required `reason` stays in the transcript. The only write that bypasses the rewrite continuity rules. |
24
25
  | request state | Carries the host list into the request when the visible window has lost it. |
25
26
  | dock panel | Replaces the pinned task panel with `计划 · 第 N / M 步` + the current step + a segmented bar, expanded into a nested list. |
26
27
  | step row | The same position on every `complete_step` tool row. |
@@ -106,7 +107,7 @@ dsh plugin --profile desktop add github:GrounzerLiu/dsh-plan-steps
106
107
  ```
107
108
 
108
109
  The bundle inserts one row, `include:plan-steps`, and puts `plan_write`,
109
- `complete_step` and `wait_for_user` into the model's toolset.
110
+ `plan_write`, `complete_step`, `wait_for_user` and `abandon_plan` into the model's toolset.
110
111
 
111
112
  **The `client:` half needs a tarball / git install.** With `link:` the Web host
112
113
  cannot serve `/plugins/<id>/client.js` (the path resolves outside the profile and
@@ -116,7 +117,7 @@ the boot graph.
116
117
 
117
118
  ## Configure
118
119
 
119
- The three switches live on the **plugin's own page**: find the `plan-steps` row in
120
+ The five switches live on the **plugin's own page**: find the `plan-steps` row in
120
121
  the Plugin Manager and press Configure.
121
122
 
122
123
  | Switch | Default | Effect |
@@ -124,6 +125,8 @@ the Plugin Manager and press Configure.
124
125
  | Refuse unsigned completions | on | off: `plan_write` / `todo_write` may mark an item completed itself |
125
126
  | Pull a turn back while items are open | on | off: a turn may end with the list still open |
126
127
  | Rebuild the panel snapshot each turn | on | off: after `turn/start` the panel waits for the model's next write |
128
+ | Remind when the plan goes stale | on | after N steps without touching the list, the request carries a "keep the plan moving" note |
129
+ | Stale reminder threshold (steps) | 20 | how many steps count as stale, and the minimum gap between reminders |
127
130
 
128
131
  The same fields can be set under the row's `config` in the profile's
129
132
  `cordis.patch.yml` as deployment defaults; the plugin page wins. The tools stay
package/README.md CHANGED
@@ -15,11 +15,12 @@
15
15
 
16
16
  | 部件 | 作用 |
17
17
  | --- | --- |
18
- | `plan_write` | 记录两级计划:`level` 0 是阶段,`level` 1 是它的子步骤,每项可带稳定 `step_id`,全表只有一个当前项。重写时执行连续性校验:已有的 id 不能丢、当前项不能被删或降级、已完成项保持原位。 |
18
+ | `plan_write` | 记录两级计划:`level` 0 是阶段,`level` 1 是它的子步骤,每项可带稳定 `step_id`,全表只有一个当前项。重写时执行连续性校验:已有的 id 不能丢、当前项不能被删或降级、已完成项保持原位;上一份计划全部完成后可以直接写新计划。 |
19
19
  | `complete_step` | 签掉当前 `in_progress` 那一项,宿主推进列表并写入 `todo/write` 快照(面板随之更新),再把下一步告诉你。阶段必须等子步骤全部完成后才能签。 |
20
20
  | 守卫 | 列表里还开着的项被 `plan_write` / `todo_write` 直接标成 `completed` 时拒绝。 |
21
21
  | 收尾拉回 | 轮末列表还有未完成项时,用 `agent.steer()` 把这一轮拉回来——每轮最多一次。 |
22
22
  | `wait_for_user` | 声明「在等用户」,这一轮就不会被拉回。 |
23
+ | `abandon_plan` | 放弃当前计划:清空列表、面板消失,`reason` 必填并留在会话记录里。这是唯一绕过重写连续性校验的写入。 |
23
24
  | 上下文召回 | 可见窗口里没有当前列表时,把「Host task state」块注入请求。 |
24
25
  | 面板 | 接管输入框上方的任务面板,显示「计划 · 第 N / M 步」+ 当前项 + 分段进度条,展开是两级缩进列表。 |
25
26
  | 工具行 | 每次 `complete_step` 也会带同样的位置信息。 |
@@ -99,8 +100,8 @@ dsh plugin --profile desktop add github:GrounzerLiu/dsh-plan-steps
99
100
  # 再把 dsh-plan-steps 加进 profile 的 dsh.profile.bundles
100
101
  ```
101
102
 
102
- bundle 会插入一行 `include:plan-steps`,并让 `plan_write`、`complete_step`、
103
- `wait_for_user` 三个工具进入模型工具集。
103
+ bundle 会插入一行 `include:plan-steps`,并让 `plan_write`、`complete_step`、`wait_for_user`、
104
+ `abandon_plan` 四个工具进入模型工具集。
104
105
 
105
106
  **客户端半需要 tarball / git 安装。** `link:` 安装时 Web 端取不到
106
107
  `/plugins/<id>/client.js`(路径落在 profile 之外,浏览器 404),面板不会变样;
@@ -108,13 +109,15 @@ bundle 会插入一行 `include:plan-steps`,并让 `plan_write`、`complete_st
108
109
 
109
110
  ## 配置
110
111
 
111
- 三个开关在**插件自己的页面**上:插件管理器里找到 `plan-steps` 那一行,点右侧的「配置」进入,页面上直接勾选/取消。
112
+ 五个开关在**插件自己的页面**上:插件管理器里找到 `plan-steps` 那一行,点右侧的「配置」进入,页面上直接勾选/取消。
112
113
 
113
114
  | 开关 | 默认 | 作用 |
114
115
  | --- | --- | --- |
115
116
  | 拒绝未签核的完成 | 开 | 关掉后 `plan_write` / `todo_write` 可以自己把项标成完成 |
116
117
  | 列表开着时拉回一轮 | 开 | 关掉后轮末不再 steer,列表开着也能结束 |
117
118
  | 每轮重建面板快照 | 开 | 关掉后 `turn/start` 之后面板要等模型自己写一次才恢复 |
119
+ | 计划久未更新时提醒 | 开 | 连续若干步没碰计划且还有未完成项时,往请求里塞一句「记得推进」的提示 |
120
+ | 提醒阈值(步) | 20 | 上面那条的步数,同时也是两次提醒之间的最小间隔 |
118
121
 
119
122
  同样的字段也可以写在 profile 的 `cordis.patch.yml` 里该行的 `config` 下,作为部署默认;插件页上的值优先。关掉开关不影响工具注册。
120
123
 
package/client.js CHANGED
@@ -89,11 +89,14 @@ window.__ModuleLoader__.load({
89
89
  const position = i + 1
90
90
  const current = !allDone && position === index
91
91
  const filled = items[i].status === 'completed'
92
+ // A phase cell is tall and wide, a sub-step cell short and narrow, so the
93
+ // bar shows the two levels the list already shows.
94
+ const nested = (items[i].level ?? 0) === 1
92
95
  cells.push(
93
96
  h('span', {
94
97
  key: i,
95
98
  style: {
96
- width: '14px',
99
+ width: nested ? '8px' : '14px',
97
100
  height: '4px',
98
101
  borderRadius: '2px',
99
102
  background: current ? TOKENS.accent : filled ? TOKENS.done : TOKENS.idle,
@@ -104,26 +107,6 @@ window.__ModuleLoader__.load({
104
107
  return h('span', { style: { display: 'inline-flex', gap: '3px', alignItems: 'center', flex: 'none' } }, cells)
105
108
  }
106
109
 
107
- function Glyph({ status }) {
108
- const color = status === 'completed' ? TOKENS.done : status === 'in_progress' ? TOKENS.accent : TOKENS.idle
109
- return h(
110
- 'span',
111
- {
112
- style: {
113
- width: '16px',
114
- height: '16px',
115
- flex: 'none',
116
- display: 'grid',
117
- placeItems: 'center',
118
- color,
119
- fontSize: '13px',
120
- lineHeight: 1,
121
- },
122
- },
123
- status === 'completed' ? '✓' : status === 'in_progress' ? '◍' : '○',
124
- )
125
- }
126
-
127
110
  function TaskPanel({ useProjection }) {
128
111
  // The shipped projection keeps only content and status, so the level rides
129
112
  // inside the content as a zero-width marker and is stripped here.
package/docs/DETAIL.md CHANGED
@@ -77,14 +77,15 @@ The tools stay registered either way.
77
77
  node --test test/
78
78
  ```
79
79
 
80
- Nineteen cases over the pure helpers: name normalisation, step resolution
80
+ Thirty-two cases over the pure helpers: name normalisation, step resolution
81
81
  (`step_id` before name before position), the flat and two-level advance rules
82
82
  (next sibling, phase sign-off last, phase with open sub-steps refused, next
83
83
  phase's first sub-step), serial validation (single current item, phase made
84
84
  current too early, pending work with no current item), call replay, step
85
- identity, the stored-state parser, and the state block — plus the four
85
+ identity, the stored-state parser, the state block, and every refusal a sign-off
86
+ can raise — plus the four
86
87
  continuity rules a rewrite must respect (id preserved, current item kept and not
87
- regressed, completed history in place, first write and additive replan allowed).
88
+ regressed, completed history in place, first write and additive replan allowed, and a fully completed plan replaced outright).
88
89
 
89
90
  ## Verification
90
91
 
@@ -106,13 +107,6 @@ Checked in a live session:
106
107
  Three things a fuller implementation would have are left out on purpose. Each
107
108
  one is a decision, not a gap waiting to be found.
108
109
 
109
- **No step ids.** The shipped task list stores a name and a status, so the name
110
- is the only identity an item has. This plugin could mint ids in a side table
111
- keyed by name — but a rename breaks that key anyway, and owning an id would mean
112
- owning the list's write format, which is the shipped tool's job. The guard's
113
- "completed count first, names second" rule is the cheapest thing that still
114
- distinguishes a relabel from a completion.
115
-
116
110
  **The hold is soft.** A turn is pulled back at most once, and a second stop is
117
111
  allowed. DSH has no core "waiting on the user" state a gate could key on, so a
118
112
  hard gate would have to infer intent from text — and a model that is genuinely
@@ -120,16 +114,22 @@ blocked would be trapped in a loop it cannot leave. One hold plus `wait_for_user
120
114
  gets the behaviour without that failure mode: a model that ignores the list still
121
115
  ends its turn, just visibly.
122
116
 
123
- **The panel stays the shipped one.** The `todos` projection resets at
124
- `turn/start` by design, so this plugin writes the open list back at the boundary
125
- instead of replacing the panel. Owning a cross-turn panel means a Client module,
126
- a wire view and a second source of truth in the UI; that is a different plugin,
127
- and two panels showing different lists would be worse than one that restores.
117
+ **The panel rides the shipped projection.** The `todos` projection resets at
118
+ `turn/start` by design, and its schema keeps only content and status. The plugin
119
+ replaces the panel, but reads that projection and writes the open list back at the
120
+ boundary instead of owning a second source of truth; the sub-step level rides in
121
+ the content as a zero-width marker because the projection would otherwise drop
122
+ it.
123
+
124
+ **Nothing is cached in plugin memory.** The list is the latest `todo/write` event,
125
+ so a fold, a fork, or a restart derives the same list. A cache would be faster and
126
+ would eventually disagree with the log.
128
127
 
129
- A fourth omission is not a decision but an accepted consequence: any other writer
130
- of `todo/write` — plan mode seeding, a direct `todo_write` — replaces the list
131
- wholesale. The host reads the last snapshot, so the two views realign at the next
132
- write; nothing drifts permanently.
128
+ Two more behaviours are accepted consequences rather than decisions: any other
129
+ writer of `todo/write` — plan mode seeding, a direct `todo_write` — replaces the
130
+ list wholesale, and the two views realign at the next write; and an abandoned
131
+ plan leaves an empty snapshot behind, so the history of what was dropped lives in
132
+ the `abandon_plan` result rather than in the list.
133
133
 
134
134
  ## Limits
135
135
 
@@ -148,10 +148,10 @@ write; nothing drifts permanently.
148
148
  draws a user bubble, the content is at least attributed to the host in the log.
149
149
  - The shipped task projection resets on `turn/start`, so the panel shows the
150
150
  list only once this turn has written one.
151
- - Item identity is the item's name, because the shipped task list has no step
152
- ids. A rewrite that adds no completion may rename freely; one that adds a
153
- completion is checked name by name, so renaming *and* closing in one write is
154
- still refused.
151
+ - A list written by the shipped `todo_write` has no step ids, so the guard falls
152
+ back to names: a rewrite that adds no completion may rename freely, while one
153
+ that adds a completion is checked name by name. Lists written by `plan_write`
154
+ carry ids and are matched by them first.
155
155
  - The list is read through the plugin's own `sessionProjections` unit
156
156
  (`plan-steps/todos`); `deriveMessages()` is still read directly for the
157
157
  visible-window check, and a host without the projection seam falls back to
package/index.js CHANGED
@@ -56,11 +56,16 @@ export const Config = Schema.object({
56
56
  guardUnsignedCompletions: Schema.boolean().default(true).volatile(),
57
57
  holdOpenList: Schema.boolean().default(true).volatile(),
58
58
  restorePanel: Schema.boolean().default(true).volatile(),
59
+ remindStalePlan: Schema.boolean().default(true).volatile(),
60
+ stalePlanSteps: Schema.number().default(20).volatile(),
59
61
  })
60
62
 
61
63
  /** Turns already held once, so a model that will not update its list still ends. */
62
64
  const heldTurn = new WeakMap()
63
65
 
66
+ /** Last step that touched the plan, and the step last reminded, per session. */
67
+ const planClock = new WeakMap()
68
+
64
69
  /** Sessions that declared they are waiting on the user this turn. */
65
70
  const waitingSessions = new WeakSet()
66
71
 
@@ -91,6 +96,40 @@ function normalize(text) {
91
96
  return String(text ?? '').trim().replace(/\s+/g, ' ')
92
97
  }
93
98
 
99
+ /**
100
+ * The guard's message for a rewrite that closes an item the host still holds
101
+ * open. It names the item the way `complete_step` wants it, so the reader can
102
+ * copy one identifier instead of guessing which step was meant.
103
+ * @param previous - the list the host holds.
104
+ * @param submitted - the submitted payload.
105
+ * @returns a refusal reason, or undefined when the rewrite adds no completion.
106
+ */
107
+ function unsignedCompletion(previous, submitted) {
108
+ const done = previous.filter((item) => item.status === 'completed').length
109
+ const nextDone = submitted.filter((item) => item?.status === 'completed').length
110
+ if (nextDone <= done) return undefined
111
+ const already = new Set(previous.filter((item) => item.status === 'completed').map((item) => normalize(item.content)))
112
+ for (const item of submitted) {
113
+ if (item?.status !== 'completed') continue
114
+ const key = normalize(item.content)
115
+ if (already.has(key)) continue
116
+ const known = previous.find((candidate) => normalize(candidate.content) === key)
117
+ const index = known === undefined ? -1 : previous.indexOf(known) + 1
118
+ const identified =
119
+ known?.stepId === undefined
120
+ ? index === -1
121
+ ? ''
122
+ : ` (item ${index} of ${previous.length}, step: ${JSON.stringify(known.content)})`
123
+ : ` (step_id ${JSON.stringify(known.stepId)}, item ${index} of ${previous.length})`
124
+ return (
125
+ `blocked: todo ${JSON.stringify(item.content)}${identified} is newly completed with no complete_step sign-off. ` +
126
+ 'Call complete_step for it first — the host marks it completed and advances the list for you — ' +
127
+ 'or send todo_write again leaving that item in_progress.'
128
+ )
129
+ }
130
+ return undefined
131
+ }
132
+
94
133
  /**
95
134
  * One stored item. The mirrored fields — `level` and `stepId` — are the ones a
96
135
  * two-level plan needs; a flat list simply has neither.
@@ -407,6 +446,9 @@ function findSame(item, list) {
407
446
  */
408
447
  function continuityProblem(previous, next) {
409
448
  if (previous === null || previous.length === 0) return null
449
+ // A finished plan is history, not state: once every item is completed there is
450
+ // no completion left to keep attached, so a new plan may replace it outright.
451
+ if (previous.every((item) => item.status === 'completed')) return null
410
452
  for (const item of previous) {
411
453
  if (item.stepId === undefined) continue
412
454
  if (next.some((candidate) => candidate.stepId === item.stepId)) continue
@@ -528,17 +570,167 @@ function stepSeqOf(events) {
528
570
  return null
529
571
  }
530
572
 
573
+ /**
574
+ * Mark the plan as touched at the current step: every write or sign-off resets
575
+ * the staleness clock.
576
+ * @param session - the owning session.
577
+ * @param step - the step seq this happened in, or null when unknown.
578
+ */
579
+ function stepIndex(events) {
580
+ if (!Array.isArray(events)) return null
581
+ let count = 0
582
+ for (const event of events) if (event?.type === 'step/start') count += 1
583
+ return count
584
+ }
585
+
586
+ function touchPlan(session, step) {
587
+ if (step === null || step === undefined) return
588
+ const clock = planClock.get(session)
589
+ if (clock === undefined) planClock.set(session, { touch: step, remind: -Infinity })
590
+ else clock.touch = Math.max(clock.touch, step)
591
+ }
592
+
593
+ /**
594
+ * Whether a stale-plan reminder is due, and which one.
595
+ * @param clock - the session's clock, or undefined before the first touch.
596
+ * @param current - the seq of the step about to run.
597
+ * @param options - threshold, open count, and whether the turn is waiting.
598
+ * @returns the reminder text, or undefined when none is due.
599
+ */
600
+ function staleReminder(clock, current, options) {
601
+ if (!options.enabled || options.waiting || options.open === 0) return undefined
602
+ if (clock === undefined || current === null) return undefined
603
+ const threshold = options.threshold
604
+ const sinceTouch = current - clock.touch
605
+ if (sinceTouch < threshold) return undefined
606
+ if (current - clock.remind < threshold) return undefined
607
+ const noun = options.open === 1 ? 'item is' : 'items are'
608
+ return (
609
+ `Plan check: the task list has not changed for about ${threshold} steps and ${options.open} ${noun} still open. ` +
610
+ 'If a step is finished, call complete_step now; if the list is out of date, rewrite it with plan_write. ' +
611
+ 'If you are waiting on the user, call wait_for_user instead of ending the turn silently.'
612
+ )
613
+ }
614
+
615
+ /**
616
+ * The sentence an abandonment returns: what was dropped, and the reason kept in
617
+ * the transcript.
618
+ * @param items - the list being abandoned.
619
+ * @param reason - why it is abandoned.
620
+ * @returns the tool's message.
621
+ */
622
+ function abandonMessage(items, reason) {
623
+ const done = items.filter((item) => item.status === 'completed').length
624
+ const carried = done === 0 ? 'nothing was completed' : `${done} of ${items.length} had been completed`
625
+ const plural = items.length === 1 ? '' : 's'
626
+ return (
627
+ `Plan abandoned: ${JSON.stringify(reason)}. ${items.length} item${plural} dropped (${carried}). ` +
628
+ 'The list is now empty; write a new plan with plan_write when the next piece of work starts.'
629
+ )
630
+ }
631
+
632
+ /**
633
+ * Resolve the item a sign-off cites and refuse the cases that are not a
634
+ * sign-off: no list, no result, an unresolvable citation, a phase with open
635
+ * sub-steps, or an item that is not the current one. Pulled out of the tool so
636
+ * each refusal is a unit test instead of a live run.
637
+ * @param items - the parsed list, or null when the session has none.
638
+ * @param args - the tool arguments.
639
+ * @param options - { unreadable } adds the host caveat to the no-list message.
640
+ * @returns { at, said, item } or { already: true, item }.
641
+ */
642
+ function signOffStep(items, args, options) {
643
+ if (items === null || items.length === 0) {
644
+ throw new Error(
645
+ 'this session holds no task list yet; call plan_write with the plan, then sign each step off as you finish it' +
646
+ (options?.unreadable === true ? ' (this host exposes neither a projection nor a session log to the plugin)' : ''),
647
+ )
648
+ }
649
+ const said = String(args?.result ?? '').trim()
650
+ if (said === '') {
651
+ throw new Error('`result` is required — state what is now true after finishing this step')
652
+ }
653
+ const cited = args?.step ?? args?.step_id ?? ''
654
+ const at = locate(items, args?.step_id, args?.step, args?.index)
655
+ if (at === -1) {
656
+ throw new Error(
657
+ `${cited === '' ? 'no step was cited and no in_progress item is current' : `step ${JSON.stringify(cited)} matches no task-list item`}; the list is: ${inventory(items)}`,
658
+ )
659
+ }
660
+ const openSub = firstUnfinishedSubStep(items, at)
661
+ if (openSub >= 0) {
662
+ throw new Error(
663
+ `${JSON.stringify(items[at].content)} is a phase whose sub-steps are unfinished; complete sub-step ` +
664
+ `${JSON.stringify(items[openSub].content)} first, then sign the phase off`,
665
+ )
666
+ }
667
+ const item = items[at]
668
+ if (item.status === 'completed') return { already: true, item }
669
+ if (item.status !== 'in_progress') {
670
+ const current = currentItem(items)
671
+ throw new Error(
672
+ `step ${JSON.stringify(item.content)} is ${item.status}; complete_step only signs the current in_progress item` +
673
+ (current === undefined
674
+ ? ' — mark the item you are working on with todo_write first'
675
+ : ` — finish ${JSON.stringify(current.content)} first`),
676
+ )
677
+ }
678
+ return { at, said, item }
679
+ }
680
+
681
+ /**
682
+ * Refuse a second sign-off in one step. The claim is taken before the append and
683
+ * before any await, so a second call in the same parallel batch is refused
684
+ * instead of signing a list the first call already moved.
685
+ * @param claimedAt - the step a claim was already taken in, or undefined.
686
+ * @param stepSeq - the step being signed in, or null when unknown.
687
+ * @throws when this step already signed something off.
688
+ */
689
+ function checkClaim(claimedAt, stepSeq) {
690
+ if (stepSeq === null || claimedAt === undefined) return
691
+ if (claimedAt !== stepSeq) return
692
+ throw new Error(
693
+ 'only one complete_step per step: a second sign-off in the same batch signs against the list as it stood ' +
694
+ 'before the first one advanced it. Sign the next item in your next step.',
695
+ )
696
+ }
697
+
531
698
  const DESCRIPTION =
532
699
  'Sign off ONE step of the current task list as done. The host marks that item completed and moves the next ' +
533
700
  'serial unit to in_progress — a sub-step promotes its next sibling, and a phase only becomes current after ' +
534
701
  'every sub-step is done. Cite the item by its step_id (preferred), by name, or by 1-based position. A plan ' +
535
702
  'write that marks a new item completed without a complete_step sign-off is refused.'
536
703
 
704
+ /**
705
+ * Read one config switch. A `.volatile()` field resolves to a live cell
706
+ * ({ get, [write] }) rather than a plain value, and reading it on use is what
707
+ * makes a setting take effect without a remount; a plain value is accepted too.
708
+ * @param cell - the config entry, possibly a cell.
709
+ * @param fallback - the value used when nothing is configured.
710
+ * @returns the current value.
711
+ */
712
+ function readCell(cell, fallback) {
713
+ if (cell === undefined || cell === null) return fallback
714
+ if (typeof cell === 'object' && typeof cell.get === 'function') {
715
+ try {
716
+ return cell.get()
717
+ } catch {
718
+ return fallback
719
+ }
720
+ }
721
+ return cell
722
+ }
723
+
537
724
  export function apply(ctx, config = {}) {
538
725
  // Settings come from the plugin row; an unset key keeps the mechanism on.
539
- const guardEnabled = config.guardUnsignedCompletions !== false
540
- const holdEnabled = config.holdOpenList !== false
541
- const restoreEnabled = config.restorePanel !== false
726
+ const guardEnabled = () => readCell(config.guardUnsignedCompletions, true) !== false
727
+ const holdEnabled = () => readCell(config.holdOpenList, true) !== false
728
+ const restoreEnabled = () => readCell(config.restorePanel, true) !== false
729
+ const remindEnabled = () => readCell(config.remindStalePlan, true) !== false
730
+ const staleSteps = () => {
731
+ const value = Number(readCell(config.stalePlanSteps, 20))
732
+ return Number.isFinite(value) ? Math.max(2, value) : 20
733
+ }
542
734
 
543
735
  // The plan writer. The shipped `todo_write` stores a flat name list; a
544
736
  // two-level plan needs a phase header, ordered sub-steps and stable step ids,
@@ -678,61 +870,25 @@ export function apply(ctx, config = {}) {
678
870
  const agent = exec.agent
679
871
  if (agent === undefined) throw new Error('complete_step requires an owning agent session')
680
872
  const items = listOf(agent.session)
681
- if (items === null || items.length === 0) {
682
- const unreadable = readProjected === null && sessionEvents(agent.session) === undefined
683
- throw new Error(
684
- 'this session holds no task list yet; call plan_write with the plan, then sign each step off as you finish it' +
685
- (unreadable ? ' (this host exposes neither a projection nor a session log to the plugin)' : ''),
686
- )
687
- }
688
- const said = String(args?.result ?? '').trim()
689
- if (said === '') {
690
- throw new Error('`result` is required — state what is now true after finishing this step')
691
- }
692
- const cited = args?.step ?? args?.step_id ?? ''
693
- const at = locate(items, args?.step_id, args?.step, args?.index)
694
- if (at === -1) {
695
- throw new Error(
696
- `${cited === '' ? 'no step was cited and no in_progress item is current' : `step ${JSON.stringify(cited)} matches no task-list item`}; the list is: ${inventory(items)}`,
697
- )
698
- }
699
- if (firstUnfinishedSubStep(items, at) >= 0) {
700
- const sub = firstUnfinishedSubStep(items, at)
701
- throw new Error(
702
- `${JSON.stringify(items[at].content)} is a phase whose sub-steps are unfinished; complete sub-step ` +
703
- `${JSON.stringify(items[sub].content)} first, then sign the phase off`,
704
- )
705
- }
706
- const target = items[at]
707
- if (target.status === 'completed') {
708
- return { message: `Step ${JSON.stringify(target.content)} was already completed; the list is unchanged.` }
709
- }
710
- if (target.status !== 'in_progress') {
711
- const current = currentItem(items)
712
- throw new Error(
713
- `step ${JSON.stringify(target.content)} is ${target.status}; complete_step only signs the current in_progress item` +
714
- (current === undefined
715
- ? ' — mark the item you are working on with todo_write first'
716
- : ` — finish ${JSON.stringify(current.content)} first`),
717
- )
873
+ const unreadable = readProjected === null && sessionEvents(agent.session) === undefined
874
+ const signoff = signOffStep(items, args, { unreadable })
875
+ if (signoff.already === true) {
876
+ return { message: `Step ${JSON.stringify(signoff.item.content)} was already completed; the list is unchanged.` }
718
877
  }
878
+ const at = signoff.at
879
+ const said = signoff.said
880
+ const target = signoff.item
719
881
  // One sign-off per step. The claim is taken before the append and before
720
882
  // any await, so a second call in the same parallel batch is refused
721
883
  // instead of signing a list the first call already moved.
722
884
  const stepSeq = stepSeqOf(sessionEvents(agent.session))
723
- if (stepSeq !== null) {
724
- if (claimedStep.get(agent.session) === stepSeq) {
725
- throw new Error(
726
- 'only one complete_step per step: a second sign-off in the same batch signs against the list as it stood ' +
727
- 'before the first one advanced it. Sign the next item in your next step.',
728
- )
729
- }
730
- claimedStep.set(agent.session, stepSeq)
731
- }
885
+ checkClaim(claimedStep.get(agent.session), stepSeq)
886
+ if (stepSeq !== null) claimedStep.set(agent.session, stepSeq)
732
887
  const advanced = advance(items, at)
733
888
  // Persist the advance as the same snapshot the shipped tool writes, so
734
889
  // the task panel and every log reader see the step close here and now.
735
890
  agent.session.append(TODO_WRITE, { todos: snapshotOf(advanced) })
891
+ touchPlan(agent.session, stepIndex(sessionEvents(agent.session)))
736
892
  const next = currentItem(advanced)
737
893
  const remaining = advanced.filter((item) => item.status !== 'completed').length
738
894
  const tail =
@@ -817,6 +973,61 @@ export function apply(ctx, config = {}) {
817
973
  }),
818
974
  })
819
975
 
976
+ ctx.tools.register({
977
+ name: 'abandon_plan',
978
+ description:
979
+ 'Abandon the current task list instead of completing it. Use it when the plan is wrong, superseded, or the ' +
980
+ 'work is dropped: the list is cleared, the panel disappears, and the reason stays in the transcript. This is ' +
981
+ 'the only write that bypasses the rewrite continuity rules, so the reason is required — signing steps off ' +
982
+ 'with complete_step remains the path for work that was actually finished.',
983
+ parameters: {
984
+ type: 'object',
985
+ additionalProperties: false,
986
+ properties: {
987
+ reason: {
988
+ type: 'string',
989
+ description: 'One line saying why the plan is abandoned; the user reads it in the transcript.',
990
+ },
991
+ },
992
+ required: ['reason'],
993
+ },
994
+ output: {
995
+ schema: {
996
+ type: 'object',
997
+ additionalProperties: false,
998
+ properties: {
999
+ message: { type: 'string' },
1000
+ },
1001
+ required: ['message'],
1002
+ },
1003
+ render: (_args, value) => [{ type: 'text', text: String(value?.message ?? '') }],
1004
+ },
1005
+ execute: async (args, exec) => {
1006
+ const agent = exec.agent
1007
+ if (agent === undefined) throw new Error('abandon_plan requires an owning agent session')
1008
+ const reason = String(args?.reason ?? '').trim()
1009
+ if (reason === '') throw new Error('`reason` is required — say in one line why the plan is abandoned')
1010
+ if (reason.length < 4) throw new Error('`reason` is too short to be useful; name what changed')
1011
+ const items = listOf(agent.session)
1012
+ if (items === null || items.length === 0) {
1013
+ throw new Error('there is no task list to abandon; write one with plan_write when work starts')
1014
+ }
1015
+ agent.session.append(TODO_WRITE, { todos: [] })
1016
+ // A dropped list cannot be waiting on the user, and the turn that ended a
1017
+ // plan should not be pulled back for items that no longer exist.
1018
+ waitingSessions.delete(agent.session)
1019
+ heldTurn.delete(agent.session)
1020
+ planClock.delete(agent.session)
1021
+ return { message: abandonMessage(items, reason) }
1022
+ },
1023
+ presentCall: (args) => ({
1024
+ card: 'generic',
1025
+ title: 'Abandon plan',
1026
+ kind: 'other',
1027
+ content: [{ type: 'text', text: String(args?.reason ?? 'Abandoning the task list.') }],
1028
+ }),
1029
+ })
1030
+
820
1031
  // The canonical list as a projection: the incremental read the host keeps for
821
1032
  // every session, so a read no longer rescans the log. A host without the seam
822
1033
  // falls back to the scan in `listOf`.
@@ -840,7 +1051,7 @@ export function apply(ctx, config = {}) {
840
1051
  }
841
1052
  })
842
1053
 
843
- if (guardEnabled) {
1054
+ if (guardEnabled()) {
844
1055
  ctx.tools.guard((exec) => {
845
1056
  if ((exec.name !== 'todo_write' && exec.name !== 'plan_write') || exec.agent === undefined) return undefined
846
1057
  const items = listOf(exec.agent.session)
@@ -850,23 +1061,11 @@ export function apply(ctx, config = {}) {
850
1061
  // A rewrite that does not add a completion is a relabel or a replan, not a
851
1062
  // claim about work: names are the only identity a shipped item has, so a
852
1063
  // completed item renamed must not read as a fresh completion.
853
- const done = items.filter((item) => item.status === 'completed').length
854
- const nextDone = submitted.filter((item) => item?.status === 'completed').length
855
- if (nextDone <= done) return undefined
856
- const already = new Set(
857
- items.filter((item) => item.status === 'completed').map((item) => normalize(item.content)),
858
- )
859
- for (const item of submitted) {
860
- if (item?.status !== 'completed') continue
861
- const key = normalize(item.content)
862
- if (already.has(key)) continue
863
- return {
864
- reason:
865
- `blocked: todo ${JSON.stringify(item.content)} is newly completed with no complete_step sign-off. ` +
866
- 'Call complete_step for it first — the host marks it completed and advances the list for you — ' +
867
- 'or send todo_write again leaving that item in_progress.',
868
- }
869
- }
1064
+ const reason = unsignedCompletion(items, submitted)
1065
+ if (reason !== undefined) return { reason }
1066
+ // Only a write the guard lets through counts as touching the plan: a
1067
+ // refused one changed nothing, so it must not reset the staleness clock.
1068
+ touchPlan(exec.agent.session, stepIndex(sessionEvents(exec.agent.session)))
870
1069
  return undefined
871
1070
  })
872
1071
  }
@@ -875,7 +1074,7 @@ export function apply(ctx, config = {}) {
875
1074
  // thing that reopens a step: the loop re-reads its inbox, finds this message,
876
1075
  // and runs another step instead of committing the boundary. One hold per turn
877
1076
  // bounds a model that will not update the list — it ends on the second stop.
878
- if (holdEnabled) {
1077
+ if (holdEnabled()) {
879
1078
  ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
880
1079
  if (agent === undefined || signal?.aborted === true) return
881
1080
  if (waitingSessions.has(agent.session)) return
@@ -916,7 +1115,7 @@ export function apply(ctx, config = {}) {
916
1115
  // a turn writes the open list back as its own snapshot: the panel is there
917
1116
  // when the turn starts instead of after the model happens to re-send it.
918
1117
  const restored = restoredTurns.get(session)
919
- if (restoreEnabled && restored !== payload.turn) {
1118
+ if (restoreEnabled() && restored !== payload.turn) {
920
1119
  restoredTurns.set(session, payload.turn)
921
1120
  try {
922
1121
  session.append(TODO_WRITE, { todos: snapshotOf(items) })
@@ -924,11 +1123,34 @@ export function apply(ctx, config = {}) {
924
1123
  // A read-only or closing session keeps its own behaviour.
925
1124
  }
926
1125
  }
927
- if (alreadyStated(payload.agent)) return decision
928
- const text = renderTaskState(items)
929
- if (text === '') return decision
1126
+ const extra = []
1127
+ if (!alreadyStated(payload.agent)) {
1128
+ const text = renderTaskState(items)
1129
+ if (text !== '') extra.push(makeMessage(text))
1130
+ }
1131
+ if (remindEnabled()) {
1132
+ const current = stepIndex(sessionEvents(session))
1133
+ // The clock starts when this plugin first sees the session, so a list that
1134
+ // was already open counts its staleness from now rather than from a write
1135
+ // it may never receive.
1136
+ if (current !== null && planClock.get(session) === undefined) {
1137
+ planClock.set(session, { touch: current, remind: -Infinity })
1138
+ }
1139
+ const text = staleReminder(planClock.get(session), current, {
1140
+ enabled: remindEnabled(),
1141
+ waiting: waitingSessions.has(session),
1142
+ open: items.filter((item) => item.status !== 'completed').length,
1143
+ threshold: staleSteps(),
1144
+ })
1145
+ if (text !== undefined) {
1146
+ extra.push(makeMessage(text))
1147
+ const clock = planClock.get(session)
1148
+ if (clock !== undefined) clock.remind = current
1149
+ }
1150
+ }
1151
+ if (extra.length === 0) return decision
930
1152
  try {
931
- return { ...decision, messages: [...decision.messages, makeMessage(text)] }
1153
+ return { ...decision, messages: [...decision.messages, ...extra] }
932
1154
  } catch {
933
1155
  return decision
934
1156
  }
@@ -941,7 +1163,7 @@ export function apply(ctx, config = {}) {
941
1163
  ctx.on('session/event', (session, event) => {
942
1164
  if (event?.type !== 'turn/start') return
943
1165
  waitingSessions.delete(session)
944
- if (restoreEnabled !== true) return
1166
+ if (restoreEnabled() !== true) return
945
1167
  // Appending inside the turn/start dispatch does not land, so the snapshot is
946
1168
  // written on the next macrotask, once the boundary has committed. The
947
1169
  // pre-step restore stays as the fallback when this one does not run.
@@ -967,4 +1189,4 @@ export function apply(ctx, config = {}) {
967
1189
  }
968
1190
 
969
1191
  /** Pure helpers, exposed for the regression tests in test/. */
970
- export const __testing = { normalize, locate, advance, replayCalls, renderTaskState, stepSeqOf, parseTodos, validateSerial, segmentsOf, firstUnfinishedSubStep, continuityProblem, snapshotOf, toItem }
1192
+ export const __testing = { normalize, locate, advance, replayCalls, renderTaskState, stepSeqOf, parseTodos, validateSerial, segmentsOf, firstUnfinishedSubStep, continuityProblem, snapshotOf, toItem, unsignedCompletion, staleReminder, touchPlan, planClock, readCell, abandonMessage, stepIndex, signOffStep, checkClaim }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plan-steps",
3
- "version": "0.1.4",
3
+ "version": "0.1.11",
4
4
  "type": "module",
5
5
  "description": "Host-owned plan steps: two-level task lists with stable step ids, one sign-off path, and a plan panel.",
6
6
  "exports": {