@teamclaws/teamclaw 2026.11.0 → 2026.11.2

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 (128) hide show
  1. package/cli.mjs +368 -13
  2. package/dist/index.js +61 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/config-routes.js +138 -0
  7. package/dist/src/controller/controller-planning.js +1 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-service.js +67 -10
  10. package/dist/src/controller/controller-tools.js +3 -1
  11. package/dist/src/controller/github-auth.js +2 -1
  12. package/dist/src/controller/http-server.js +51 -16
  13. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  14. package/dist/src/controller/message-delivery.js +4 -1
  15. package/dist/src/controller/orchestration-manifest.js +5 -65
  16. package/dist/src/controller/preview-manager.js +51 -3
  17. package/dist/src/controller/profile-switch.js +42 -22
  18. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  19. package/dist/src/controller/provisioning/container-shared.js +64 -0
  20. package/dist/src/controller/provisioning/docker.js +214 -0
  21. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  22. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  23. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  24. package/dist/src/controller/provisioning-config.js +239 -0
  25. package/dist/src/controller/repo-routes.js +70 -4
  26. package/dist/src/controller/report-routes.js +56 -0
  27. package/dist/src/controller/route-table.js +73 -1045
  28. package/dist/src/controller/security.js +775 -0
  29. package/dist/src/controller/status-routes.js +287 -0
  30. package/dist/src/controller/task-assignment.js +5 -2
  31. package/dist/src/controller/task-execution.js +31 -0
  32. package/dist/src/controller/task-results.js +10 -0
  33. package/dist/src/controller/tunnel-manager.js +41 -8
  34. package/dist/src/controller/tunnel-routes.js +225 -0
  35. package/dist/src/controller/websocket.js +6 -2
  36. package/dist/src/controller/webui-routes.js +49 -0
  37. package/dist/src/controller/worker-provisioning.js +39 -949
  38. package/dist/src/controller/workflow-routes.js +407 -0
  39. package/dist/src/controller/workspace-routes.js +200 -0
  40. package/dist/src/git-collaboration.js +4 -9
  41. package/dist/src/identity.js +12 -1
  42. package/dist/src/openclaw-workspace.js +36 -0
  43. package/dist/src/profile-loader.js +119 -1
  44. package/dist/src/profiles/banking.json +26 -2
  45. package/dist/src/profiles/schema.json +82 -2
  46. package/dist/src/prompt-policy.js +18 -6
  47. package/dist/src/protocol.js +66 -3
  48. package/dist/src/shared/clarification-schema.js +65 -0
  49. package/dist/src/shared/github-auth.js +15 -0
  50. package/dist/src/shared/kickoff-prompt.js +37 -0
  51. package/dist/src/shared/utils.js +47 -0
  52. package/dist/src/state.js +89 -3
  53. package/dist/src/teamauto/scanner.js +21 -2
  54. package/dist/src/teamauto/scheduler.js +9 -2
  55. package/dist/src/types.js +15 -1
  56. package/dist/src/ui/app.js +990 -73
  57. package/dist/src/ui/github-login.html +1 -0
  58. package/dist/src/ui/index.html +125 -36
  59. package/dist/src/worker/http-handler.js +59 -0
  60. package/dist/src/worker/skill-installer.js +3 -9
  61. package/dist/src/worker/tools.js +20 -10
  62. package/dist/src/worker/worker-service.js +17 -4
  63. package/index.ts +69 -32
  64. package/openclaw.plugin.json +23 -2
  65. package/package.json +1 -1
  66. package/src/config.ts +24 -0
  67. package/src/controller/auth-routes.ts +157 -0
  68. package/src/controller/clarification-routes.ts +1 -1
  69. package/src/controller/config-routes.ts +152 -0
  70. package/src/controller/controller-planning.ts +8 -0
  71. package/src/controller/controller-routes.ts +237 -0
  72. package/src/controller/controller-service.ts +128 -10
  73. package/src/controller/controller-tools.ts +5 -2
  74. package/src/controller/github-auth.ts +28 -63
  75. package/src/controller/http-server.ts +66 -17
  76. package/src/controller/kickoff-orchestrator.ts +3 -42
  77. package/src/controller/message-delivery.ts +4 -1
  78. package/src/controller/orchestration-manifest.ts +8 -71
  79. package/src/controller/preview-manager.ts +53 -3
  80. package/src/controller/profile-switch.ts +53 -23
  81. package/src/controller/provisioning/backend-contract.ts +51 -0
  82. package/src/controller/provisioning/container-shared.ts +84 -0
  83. package/src/controller/provisioning/docker.ts +260 -0
  84. package/src/controller/provisioning/kubernetes.ts +263 -0
  85. package/src/controller/provisioning/plugin-root.ts +42 -0
  86. package/src/controller/provisioning/process-supervisor.ts +214 -0
  87. package/src/controller/provisioning-config.ts +289 -0
  88. package/src/controller/repo-routes.ts +84 -12
  89. package/src/controller/report-routes.ts +64 -0
  90. package/src/controller/route-table.ts +139 -1152
  91. package/src/controller/security.ts +899 -0
  92. package/src/controller/status-routes.ts +354 -0
  93. package/src/controller/task-assignment.ts +5 -1
  94. package/src/controller/task-execution.ts +43 -0
  95. package/src/controller/task-results.ts +12 -0
  96. package/src/controller/tunnel-manager.ts +45 -8
  97. package/src/controller/tunnel-routes.ts +231 -0
  98. package/src/controller/websocket.ts +20 -3
  99. package/src/controller/webui-routes.ts +55 -0
  100. package/src/controller/worker-provisioning.ts +51 -1117
  101. package/src/controller/workflow-routes.ts +498 -0
  102. package/src/controller/workspace-routes.ts +222 -0
  103. package/src/git-collaboration.ts +4 -9
  104. package/src/identity.ts +13 -1
  105. package/src/openclaw-workspace.ts +47 -0
  106. package/src/profile-loader.ts +167 -1
  107. package/src/profiles/banking.json +26 -2
  108. package/src/profiles/schema.json +82 -2
  109. package/src/prompt-policy.ts +19 -6
  110. package/src/protocol.ts +72 -2
  111. package/src/shared/clarification-schema.ts +81 -0
  112. package/src/shared/github-auth.ts +92 -0
  113. package/src/shared/kickoff-prompt.ts +47 -0
  114. package/src/shared/utils.ts +51 -0
  115. package/src/state.ts +92 -3
  116. package/src/teamauto/github-client.ts +2 -1
  117. package/src/teamauto/repo-sync.ts +2 -1
  118. package/src/teamauto/scanner.ts +22 -3
  119. package/src/teamauto/scheduler.ts +11 -3
  120. package/src/teamauto/store.ts +5 -0
  121. package/src/types.ts +130 -1
  122. package/src/ui/app.js +990 -73
  123. package/src/ui/github-login.html +1 -0
  124. package/src/ui/index.html +125 -36
  125. package/src/worker/http-handler.ts +64 -1
  126. package/src/worker/skill-installer.ts +3 -9
  127. package/src/worker/tools.ts +21 -10
  128. package/src/worker/worker-service.ts +18 -4
package/src/state.ts CHANGED
@@ -93,9 +93,67 @@ function migrateState(raw: unknown): TeamState | null {
93
93
  }
94
94
  }
95
95
 
96
+ // Issue #23: device-pairing security state (additive optional field). No
97
+ // `security` key = protection off (L0 zero-friction default). A malformed
98
+ // persisted shape is sanitized in place, mirroring the transition policy
99
+ // above: devices without a usable identity/tokenHash are dropped (such a
100
+ // device could never authenticate again anyway), and malformed pairing
101
+ // codes / observation records are discarded.
102
+ if (state.security !== undefined) {
103
+ const security = state.security as Record<string, unknown>;
104
+ if (!security || typeof security !== "object" || Array.isArray(security)) {
105
+ delete state.security;
106
+ } else {
107
+ if (security.enabledAt !== undefined && typeof security.enabledAt !== "number") {
108
+ delete security.enabledAt;
109
+ }
110
+ security.devices = Array.isArray(security.devices)
111
+ ? security.devices.filter(isValidPersistedSecurityDevice)
112
+ : [];
113
+ if (security.pairingCode !== undefined) {
114
+ const pairingCode = security.pairingCode as Record<string, unknown>;
115
+ const codeOk = typeof pairingCode?.code === "string" && /^[A-Z2-7]{8}$/.test(pairingCode.code);
116
+ const expiresOk = typeof pairingCode?.expiresAt === "number";
117
+ const purposeOk = typeof pairingCode?.purpose === "string" && Boolean(pairingCode.purpose.trim());
118
+ const usedOk = pairingCode?.usedAt === undefined || typeof pairingCode.usedAt === "number";
119
+ if (!codeOk || !expiresOk || !purposeOk || !usedOk) {
120
+ delete security.pairingCode;
121
+ }
122
+ }
123
+ if (security.lastNonLanPeer !== undefined) {
124
+ const observation = security.lastNonLanPeer as Record<string, unknown>;
125
+ if (
126
+ typeof observation?.ip !== "string" ||
127
+ typeof observation?.at !== "number" ||
128
+ typeof observation?.path !== "string"
129
+ ) {
130
+ delete security.lastNonLanPeer;
131
+ }
132
+ }
133
+ }
134
+ }
135
+
96
136
  return state as unknown as TeamState;
97
137
  }
98
138
 
139
+ /**
140
+ * Issue #23: persisted-device structural guard for the migration above. A
141
+ * device needs a non-empty id, a sha256-hex tokenHash (64 lowercase hex
142
+ * chars) and a creation timestamp; anything else is corrupt state and is
143
+ * dropped rather than half-loaded.
144
+ */
145
+ function isValidPersistedSecurityDevice(entry: unknown): boolean {
146
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
147
+ return false;
148
+ }
149
+ const device = entry as Record<string, unknown>;
150
+ return (
151
+ typeof device.id === "string" && Boolean(device.id.trim()) &&
152
+ typeof device.tokenHash === "string" && /^[0-9a-f]{64}$/.test(device.tokenHash) &&
153
+ typeof device.createdAt === "number"
154
+ );
155
+ }
156
+
99
157
  function resolvePluginStateDir(): string {
100
158
  const explicitStateDir = process.env.OPENCLAW_STATE_DIR?.trim();
101
159
  if (explicitStateDir) {
@@ -152,9 +210,35 @@ async function ensureDir(dir: string): Promise<void> {
152
210
  await fs.mkdir(dir, { recursive: true });
153
211
  }
154
212
 
213
+ /**
214
+ * Issue #255 P1-4: every file written through this helper is controller
215
+ * state that can carry plaintext secrets - team-state.json holds the device
216
+ * pairingCode and each provisioned worker's launchToken, the archived team
217
+ * envelopes and worker-identity.json ride the same path. Writes are now
218
+ * owner-only (0600), matching the github-auth.ts auth-store precedent:
219
+ * - the tmp file is created with mode 0600 and the rename carries that
220
+ * mode onto the final path, and
221
+ * - an existing file from an older build (created 0644 by this same
222
+ * helper before the mode existed) is pre-tightened before the rewrite
223
+ * (#242 process-supervisor pattern: chmod first, ENOENT tolerated for
224
+ * first writes).
225
+ */
155
226
  async function writeFileAtomically(filePath: string, contents: string): Promise<void> {
156
227
  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
157
- await fs.writeFile(tmpPath, contents, "utf8");
228
+ try {
229
+ await fs.chmod(filePath, 0o600);
230
+ } catch (error) {
231
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
232
+ throw error;
233
+ }
234
+ }
235
+ await fs.writeFile(tmpPath, contents, { encoding: "utf8", mode: 0o600 });
236
+ try {
237
+ await fs.chmod(tmpPath, 0o600);
238
+ } catch {
239
+ // Best-effort: the write itself already requested mode 0600; some
240
+ // filesystems (e.g. network mounts) reject explicit chmod.
241
+ }
158
242
  await fs.rename(tmpPath, filePath);
159
243
  }
160
244
 
@@ -280,7 +364,7 @@ async function saveTeamState(state: TeamState): Promise<void> {
280
364
  // ---------------------------------------------------------------------------
281
365
 
282
366
  const ARCHIVED_TEAMS_DIR_NAME = "archived";
283
- const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)\.json$/;
367
+ const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)(?:-([a-z0-9]+))?\.json$/;
284
368
 
285
369
  /** Embedded profile snapshot stored alongside the archived team state. */
286
370
  export type ArchivedTeamProfileSnapshot = {
@@ -331,7 +415,12 @@ async function archiveTeamState(
331
415
  ): Promise<string> {
332
416
  const dir = archivedTeamsDirPath();
333
417
  await ensureDir(dir);
334
- const fileName = `${state.profileId}-${Date.now()}.json`;
418
+ // #251: a short random suffix disambiguates same-millisecond archives
419
+ // (two switches inside one ms would otherwise silently overwrite each
420
+ // other). Capture groups 1/2 keep their original semantics; group 3 is
421
+ // the optional suffix, so pre-#251 archive names still parse.
422
+ const suffix = Math.random().toString(36).slice(2, 8).padEnd(6, "0");
423
+ const fileName = `${state.profileId}-${Date.now()}-${suffix}.json`;
335
424
  const filePath = path.join(dir, fileName);
336
425
  const envelope: ArchivedTeamEnvelope = {
337
426
  archivedAt: Date.now(),
@@ -1,4 +1,5 @@
1
- import type { GithubAuthManager } from "../controller/github-auth.js";
1
+ // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
2
+ import type { GithubAuthManager } from "../shared/github-auth.js";
2
3
 
3
4
  /**
4
5
  * Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
@@ -3,7 +3,8 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
5
 
6
- import type { GithubAuthManager } from "../controller/github-auth.js";
6
+ // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
7
+ import type { GithubAuthManager } from "../shared/github-auth.js";
7
8
  import { repoSlugToDirName, resolveTeamAutoPaths } from "./store.js";
8
9
 
9
10
  const exec = promisify(execFile);
@@ -102,12 +102,25 @@ export async function sweepRepo(
102
102
  repo: TeamAutoRepo,
103
103
  client: TeamAutoGithubClient,
104
104
  now = Date.now(),
105
- ): Promise<{ candidates: Candidate[]; issues: SweepableIssue[]; pulls: SweepablePull[] }> {
105
+ ): Promise<{ candidates: Candidate[]; issues: SweepableIssue[]; pulls: SweepablePull[]; newCommits: { sha: string; message: string }[]; commits: { sha: string; message: string }[] }> {
106
106
  const [owner, name] = repo.id.split("/");
107
107
  const issues = await client.listIssues(owner, name, repo.cursors.lastIssueSince, repo.cursors.etags);
108
108
  const pulls = repo.policy.actions.prReview
109
109
  ? await client.listPulls(owner, name, repo.cursors.etags)
110
110
  : [];
111
+ // #265: the commits leg was dead code (listCommits had zero callers,
112
+ // lastCommitSha never advanced) - the designed third signal source never
113
+ // ran. Wire it as an observation-only feed: fetch, filter past the cursor,
114
+ // and surface the delta. Cursor advance happens in advanceCursors (with
115
+ // the other legs, so dry-run semantics stay intact); it produces no task
116
+ // candidates (issue/pull policies stay the sole candidate sources).
117
+ const commits = await client.listCommits(owner, name, repo.cursors.lastCommitSha);
118
+ // Newest-first feed: when the cursor is set, stop the delta at the first
119
+ // entry whose sha equals it (that commit and everything after is already
120
+ // known). An unset cursor means first sweep: observe only, report nothing.
121
+ const newCommits = repo.cursors.lastCommitSha
122
+ ? commits.slice(0, (() => { const i = commits.findIndex((c) => c.sha === repo.cursors.lastCommitSha); return i === -1 ? commits.length : i; })())
123
+ : [];
111
124
  const candidates: Candidate[] = [];
112
125
 
113
126
  for (const issue of issues) {
@@ -220,17 +233,23 @@ export async function sweepRepo(
220
233
  }
221
234
  }
222
235
 
223
- return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
236
+ return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls, newCommits, commits };
224
237
  }
225
238
 
226
239
  /** Advance cursors after tasks were enqueued (or observed on first sweep). */
227
- export function advanceCursors(repo: TeamAutoRepo, issues: SweepableIssue[], pulls: SweepablePull[], now = Date.now()): void {
240
+ export function advanceCursors(repo: TeamAutoRepo, issues: SweepableIssue[], pulls: SweepablePull[], now = Date.now(), commits: { sha: string; message: string }[] = []): void {
228
241
  for (const issue of issues) {
229
242
  repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
230
243
  }
231
244
  for (const pull of pulls) {
232
245
  repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
233
246
  }
247
+ // Commit cursor: the feed is newest-first, so when anything came back the
248
+ // HEAD entry IS the new cursor. Empty feed keeps the old cursor (nothing
249
+ // new to advance to).
250
+ if (commits.length > 0) {
251
+ repo.cursors.lastCommitSha = commits[0].sha;
252
+ }
234
253
  // Cap the seen map so it cannot grow unbounded.
235
254
  const entries = Object.entries(repo.cursors.seen);
236
255
  if (entries.length > 2000) {
@@ -1,7 +1,8 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
 
3
3
  import type { PluginLogger } from "../../api.js";
4
- import type { GithubAuthManager } from "../controller/github-auth.js";
4
+ // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
5
+ import type { GithubAuthManager } from "../shared/github-auth.js";
5
6
  // Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
6
7
  // validate against the ACTIVE profile and default to its defaultRole instead
7
8
  // of hardcoded software role literals.
@@ -408,7 +409,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
408
409
  }
409
410
  sweeping.add(repo.id);
410
411
  try {
411
- const { candidates, issues, pulls } = await sweepRepo(repo, client);
412
+ const { candidates, issues, pulls, newCommits, commits } = await sweepRepo(repo, client);
412
413
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
413
414
  if (dryRun) {
414
415
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -421,7 +422,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
421
422
  // Advance only for acting sweeps: a dry-run must leave the cursors
422
423
  // untouched so the reported actions are actually performed next time
423
424
  // instead of being marked as already-seen.
424
- advanceCursors(repo, issues, pulls);
425
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
425
426
  }
426
427
  // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
427
428
  // pull candidates, so a busy repo would otherwise starve them forever
@@ -432,6 +433,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
432
433
  const capped = [...fullReviews, ...regular];
433
434
  let created = 0;
434
435
  const summary: string[] = [`found ${candidates.length} candidate(s)`];
436
+ // #265: surface the commits delta so the third signal source is
437
+ // observable in sweep summaries (was silently dead before).
438
+ if (newCommits.length > 0) {
439
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
440
+ }
435
441
 
436
442
  if (capped.length && dryRun) {
437
443
  summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
@@ -469,6 +475,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
469
475
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
470
476
  }
471
477
  repo.sweepFailures = 0;
478
+ repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
472
479
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
473
480
  await saveTeamAutoStore(s);
474
481
  if (created > 0) {
@@ -486,6 +493,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
486
493
  // backoff below, and a success clears the state in the block above.
487
494
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
488
495
  repo.lastSweepErrorAt = Date.now();
496
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
489
497
  repo.pausedReason = `sweep failed: ${message}`;
490
498
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
491
499
  await saveTeamAutoStore(s).catch(() => {});
@@ -70,6 +70,11 @@ export type TeamAutoRepo = {
70
70
  sweepFailures?: number;
71
71
  /** Epoch ms of the last auto-pausing sweep failure. */
72
72
  lastSweepErrorAt?: number;
73
+ /** Epoch ms of the last sweep ATTEMPT (success or failure), #266:
74
+ * lastSweepAt/lastSweepSummary stay success-scoped while lastAttemptAt
75
+ * answers "did the scheduler try recently" without the two surfaces
76
+ * contradicting each other when read side by side. */
77
+ lastAttemptAt?: number;
73
78
  dryRunDone: boolean;
74
79
  /** Bind-time provisioning state; ready/undefined means sweepable. */
75
80
  provision?: TeamAutoRepoProvision;
package/src/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TEAMCLAW_PUBLISHED_RUNTIME_IMAGE } from "./install-defaults.js";
2
- import { DEFAULT_GITHUB_CLIENT_ID } from "./controller/github-auth.js";
2
+ import { DEFAULT_GITHUB_CLIENT_ID } from "./shared/github-auth.js";
3
3
  // Safe value import: roles.js only pulls prompt-policy.js -> openclaw-workspace.js
4
4
  // at runtime (its types.js import is type-only), so no module cycle is formed.
5
5
  import { DEFAULT_ROLE } from "./roles.js";
@@ -158,6 +158,37 @@ export type TaskInfo = {
158
158
  /** Surviving progress snapshot for interrupted executions (resume support). */
159
159
  checkpoint?: TaskCheckpoint;
160
160
  resumeAttempt?: number;
161
+ /**
162
+ * Design 2.4 workflow-chain membership: set ONLY by the workflow engine
163
+ * (controller/workflow-routes.ts) when it creates a step task, never by
164
+ * client task creation (the create route builds TaskInfo field-by-field
165
+ * and does not accept this field). The task-completion hook reads it to
166
+ * route the chain by the step's conclusion. The task chain itself is the
167
+ * workflow run state - there is no separate run registry by design.
168
+ */
169
+ workflow?: TaskWorkflowContext;
170
+ };
171
+
172
+ /**
173
+ * Workflow-chain context carried on each design-2.4 step task. `visitCounts`
174
+ * is the loop guard for return edges (e.g. 退回补充材料 -> step 0) and the
175
+ * routed* fields are the once-only routing latch: exactly one completion of
176
+ * a step task may spawn the follow-up task.
177
+ */
178
+ export type TaskWorkflowContext = {
179
+ /** Profile workflow template id (e.g. "credit-approval"). */
180
+ workflowId: string;
181
+ /** Run nonce shared by every task of one started workflow instance. */
182
+ runId: string;
183
+ /** String form of the executed step's id (numeric spine or branch key). */
184
+ stepKey: string;
185
+ /** Visits per step key so return edges cannot loop forever. */
186
+ visitCounts?: Record<string, number>;
187
+ /** Routing latch: step key the completion hook routed to (chain end = ""). */
188
+ routedToStepKey?: string;
189
+ routedAt?: number;
190
+ /** Conclusion phrase that drove the routing (observability/audit). */
191
+ routedConclusion?: string;
161
192
  };
162
193
 
163
194
  export type TaskExecutionEvent = {
@@ -565,6 +596,19 @@ export type PluginConfig = {
565
596
  */
566
597
  githubClientSecret: string;
567
598
  agentIsolationMode: AgentIsolationMode;
599
+ /**
600
+ * Issue #23: controller device-pairing security options. Parsed with
601
+ * safe defaults (autoPair: true) so hand-built configs without the key
602
+ * keep the L1 zero-input LAN pairing behavior.
603
+ */
604
+ security?: SecurityConfig;
605
+ /**
606
+ * Issue #23 (client wave): device token this instance presents to a
607
+ * protected controller (X-TeamClaw-Token on every API call). Written by
608
+ * `teamclaw pair` / the desktop pairing flow; empty string = unpaired L0
609
+ * behavior. NEVER logged or echoed back through config UIs.
610
+ */
611
+ securityToken: string;
568
612
  workerProvisioningType: WorkerProvisioningType;
569
613
  workerProvisioningDisabled: boolean;
570
614
  workerProvisioningControllerUrl: string;
@@ -597,6 +641,68 @@ export type WorkerIdentity = {
597
641
  registeredAt: number;
598
642
  };
599
643
 
644
+ // ===========================================================================
645
+ // Device pairing security (issue #23, backend wave).
646
+ //
647
+ // Zero-friction ladder (product semantics, FIXED):
648
+ // L0 local - no devices persisted => no authentication at all (the
649
+ // historical behavior; a state without `security` is L0)
650
+ // L1 LAN - LAN peers (loopback / RFC1918 / ULA / link-local) may
651
+ // self-pair via POST /api/v1/security/pair-auto while
652
+ // config.security.autoPair is true (default)
653
+ // L2 exposed - one-shot 60s pairing codes minted by an authenticated
654
+ // device or the loopback console
655
+ // The user never configures a token and the UI never shows a login page.
656
+ // Tokens are 32-byte hex secrets returned to the pairing caller EXACTLY
657
+ // ONCE; only their sha256 hex digest is persisted.
658
+ // ===========================================================================
659
+
660
+ export type SecurityDeviceKind = "web" | "worker" | "desktop" | "cli";
661
+
662
+ export type SecurityDevice = {
663
+ id: string;
664
+ name: string;
665
+ kind: SecurityDeviceKind;
666
+ /** sha256 hex of the device token. The plaintext token is never persisted. */
667
+ tokenHash: string;
668
+ createdAt: number;
669
+ /** Epoch ms of the last authenticated request (throttled persistence). */
670
+ lastSeenAt?: number;
671
+ /** Where the device paired from (peer IP, or "loopback" for the console). */
672
+ origin?: string;
673
+ };
674
+
675
+ export type SecurityPairingCode = {
676
+ /** 8-character uppercase base32 (RFC 4648) code, displayed once to a human. */
677
+ code: string;
678
+ /** Absolute expiry (epoch ms); pairing codes live 60 seconds. */
679
+ expiresAt: number;
680
+ purpose: string;
681
+ /** Set when consumed; a used code can never pair a second device. */
682
+ usedAt?: number;
683
+ };
684
+
685
+ export type NonLanPeerObservation = {
686
+ ip: string;
687
+ at: number;
688
+ path: string;
689
+ };
690
+
691
+ export type TeamSecurityState = {
692
+ /** Set when protection was first enabled (first device minted); the suggestion signal below may exist without it while still L0. */
693
+ enabledAt?: number;
694
+ /** Protection is ON iff this array is non-empty (the L0/L1/L2 ladder switch). */
695
+ devices: SecurityDevice[];
696
+ pairingCode?: SecurityPairingCode;
697
+ /** Suggestion signal: latest non-LAN peer observed while protection is off. */
698
+ lastNonLanPeer?: NonLanPeerObservation;
699
+ };
700
+
701
+ export type SecurityConfig = {
702
+ /** Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto). */
703
+ autoPair: boolean;
704
+ };
705
+
600
706
  /**
601
707
  * Phase 2.1 (vertical-team-profiles-design.md section 2.3): the transition
602
708
  * state machine for an in-flight team profile switch. Persisted inside
@@ -638,6 +744,13 @@ export type TeamState = {
638
744
  provisioning?: TeamProvisioningState;
639
745
  previews?: Record<string, DynamicPreviewRecord>;
640
746
  reports?: Record<string, DeliveryReportRecord>;
747
+ /**
748
+ * Issue #23: device-pairing security state. ABSENT or carrying an empty
749
+ * devices array = protection off (L0 zero-friction default, the exact
750
+ * pre-issue behavior); a non-empty devices array turns the auth
751
+ * middleware on (see controller/security.ts).
752
+ */
753
+ security?: TeamSecurityState;
641
754
  createdAt: number;
642
755
  updatedAt: number;
643
756
  };
@@ -807,6 +920,20 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
807
920
  ? raw.agentIsolationMode
808
921
  : "independent";
809
922
 
923
+ // Issue #23: security.autoPair defaults to true (L1 zero-input LAN
924
+ // pairing); only an explicit boolean false disables pair-auto.
925
+ const rawSecurity = raw.security;
926
+ const rawAutoPair = rawSecurity && typeof rawSecurity === "object" && !Array.isArray(rawSecurity)
927
+ ? (rawSecurity as { autoPair?: unknown }).autoPair
928
+ : undefined;
929
+ const security: SecurityConfig = {
930
+ autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : true,
931
+ };
932
+
933
+ // Issue #23 (client wave): the paired device token, if this instance
934
+ // paired with a protected controller. Empty/absent keeps L0 behavior.
935
+ const securityToken = typeof raw.securityToken === "string" ? raw.securityToken.trim() : "";
936
+
810
937
  const rawWorkerProvisioningType = parseProvisioningType(raw.workerProvisioningType);
811
938
  const workerProvisioningDisabled = raw.workerProvisioningDisabled === true;
812
939
  // Legacy local installs often persisted workerProvisioningType="none" without
@@ -914,6 +1041,8 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
914
1041
  githubClientId,
915
1042
  githubClientSecret,
916
1043
  agentIsolationMode,
1044
+ security,
1045
+ securityToken,
917
1046
  workerProvisioningType,
918
1047
  workerProvisioningDisabled,
919
1048
  workerProvisioningControllerUrl,