@goodandready/dsh-goal 0.2.17 → 0.2.19

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.
@@ -10,9 +10,19 @@ export const DEFAULT_SETTINGS = {
10
10
  showQuickLaunchButton: true,
11
11
  consecutiveToolFailureLimit: 3,
12
12
  enableBrowserNotifications: true,
13
+ maxTokenBudget: 0,
14
+ budgetWarningThreshold: 80,
15
+ autoCheckpointOnMilestone: false,
13
16
  storagePath: '',
14
17
  };
15
18
 
19
+ export const NUMERIC_FIELDS = {
20
+ maxIterations: 1,
21
+ consecutiveToolFailureLimit: 0,
22
+ maxTokenBudget: 0,
23
+ budgetWarningThreshold: 0,
24
+ };
25
+
16
26
  /**
17
27
  * Parse numeric settings field:
18
28
  * - empty string / null / undefined -> undefined (reset override)
@@ -50,28 +60,14 @@ export function getFieldStatus(field, draftValue, snap) {
50
60
  let invalid = false;
51
61
  let isDirty = false;
52
62
 
53
- if (field === 'maxIterations') {
63
+ if (field in NUMERIC_FIELDS) {
54
64
  if (draftValue !== undefined) {
55
65
  if (draftValue === '') {
56
66
  invalid = false;
57
67
  isDirty = userVal !== undefined;
58
68
  } else {
59
- const parsed = parseNumberField(draftValue, 1);
60
- if (Number.isNaN(parsed)) {
61
- invalid = true;
62
- isDirty = true;
63
- } else {
64
- isDirty = parsed !== (userVal !== undefined ? userVal : baseVal);
65
- }
66
- }
67
- }
68
- } else if (field === 'consecutiveToolFailureLimit') {
69
- if (draftValue !== undefined) {
70
- if (draftValue === '') {
71
- invalid = false;
72
- isDirty = userVal !== undefined;
73
- } else {
74
- const parsed = parseNumberField(draftValue, 0);
69
+ const min = NUMERIC_FIELDS[field];
70
+ const parsed = parseNumberField(draftValue, min);
75
71
  if (Number.isNaN(parsed)) {
76
72
  invalid = true;
77
73
  isDirty = true;
@@ -86,7 +82,7 @@ export function getFieldStatus(field, draftValue, snap) {
86
82
  isDirty = cleanVal !== (userVal !== undefined ? userVal : (baseVal || ''));
87
83
  }
88
84
  } else {
89
- // boolean fields (autoDrive, enableSound, showQuickLaunchButton, enableBrowserNotifications)
85
+ // boolean fields (autoDrive, enableSound, showQuickLaunchButton, enableBrowserNotifications, autoCheckpointOnMilestone)
90
86
  if (draftValue !== undefined) {
91
87
  isDirty = Boolean(draftValue) !== (userVal !== undefined ? Boolean(userVal) : Boolean(baseVal));
92
88
  }
@@ -119,6 +115,9 @@ export function computeSavePlan(draft, snap) {
119
115
  'showQuickLaunchButton',
120
116
  'consecutiveToolFailureLimit',
121
117
  'enableBrowserNotifications',
118
+ 'maxTokenBudget',
119
+ 'budgetWarningThreshold',
120
+ 'autoCheckpointOnMilestone',
122
121
  'storagePath',
123
122
  ];
124
123
 
@@ -129,17 +128,11 @@ export function computeSavePlan(draft, snap) {
129
128
  if (status.invalid) continue;
130
129
 
131
130
  if (status.isDirty) {
132
- if (f === 'maxIterations') {
133
- if (draft[f] === '') {
134
- writes.push([f, undefined]);
135
- } else {
136
- writes.push([f, parseNumberField(draft[f], 1)]);
137
- }
138
- } else if (f === 'consecutiveToolFailureLimit') {
131
+ if (f in NUMERIC_FIELDS) {
139
132
  if (draft[f] === '') {
140
133
  writes.push([f, undefined]);
141
134
  } else {
142
- writes.push([f, parseNumberField(draft[f], 0)]);
135
+ writes.push([f, parseNumberField(draft[f], NUMERIC_FIELDS[f])]);
143
136
  }
144
137
  } else if (f === 'storagePath') {
145
138
  const clean = typeof draft[f] === 'string' ? draft[f].trim() : '';
package/lib/client.js CHANGED
@@ -3794,153 +3794,125 @@ window.__ModuleLoader__.load({
3794
3794
  // --- SETTINGS FORM LOGIC ---
3795
3795
 
3796
3796
  const DEFAULT_SETTINGS = {
3797
-
3798
3797
  maxIterations: 25,
3799
-
3800
3798
  autoDrive: true,
3801
-
3802
3799
  enableSound: true,
3803
-
3804
3800
  showQuickLaunchButton: true,
3805
-
3806
3801
  consecutiveToolFailureLimit: 3,
3807
-
3808
3802
  enableBrowserNotifications: true,
3809
-
3803
+ maxTokenBudget: 0,
3804
+ budgetWarningThreshold: 80,
3805
+ autoCheckpointOnMilestone: false,
3806
+ storagePath: '',
3810
3807
  };
3811
3808
 
3812
- function parseNumberField(raw) {
3809
+ const NUMERIC_FIELDS = {
3810
+ maxIterations: 1,
3811
+ consecutiveToolFailureLimit: 0,
3812
+ maxTokenBudget: 0,
3813
+ budgetWarningThreshold: 0,
3814
+ };
3813
3815
 
3816
+ function parseNumberField(raw, min = 1) {
3814
3817
  if (raw === '' || raw === null || raw === undefined) {
3815
-
3816
3818
  return undefined;
3817
-
3818
3819
  }
3819
-
3820
3820
  const n = Number(raw);
3821
-
3822
- if (!Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
3823
-
3821
+ if (!Number.isFinite(n) || n < min || !Number.isInteger(n)) {
3824
3822
  return NaN;
3825
-
3826
3823
  }
3827
-
3828
3824
  return n;
3829
-
3830
3825
  }
3831
3826
 
3832
3827
  function getFieldStatus(field, draftValue, snap) {
3833
-
3834
3828
  const baseVal = snap?.base?.[field] ?? DEFAULT_SETTINGS[field];
3835
-
3836
3829
  const userVal = snap?.user?.[field];
3837
-
3838
3830
  const effectiveVal = snap?.value?.[field] ?? baseVal;
3839
3831
 
3840
3832
  const isOverridden = userVal !== undefined && userVal !== null;
3841
-
3842
3833
  const currentVal = draftValue !== undefined ? draftValue : effectiveVal;
3843
3834
 
3844
3835
  let invalid = false;
3845
-
3846
3836
  let isDirty = false;
3847
3837
 
3848
- if (field === 'maxIterations') {
3849
-
3838
+ if (field in NUMERIC_FIELDS) {
3850
3839
  if (draftValue !== undefined) {
3851
-
3852
3840
  if (draftValue === '') {
3853
-
3854
3841
  invalid = false;
3855
-
3856
3842
  isDirty = userVal !== undefined;
3857
-
3858
3843
  } else {
3859
-
3860
- const parsed = parseNumberField(draftValue);
3861
-
3844
+ const min = NUMERIC_FIELDS[field];
3845
+ const parsed = parseNumberField(draftValue, min);
3862
3846
  if (Number.isNaN(parsed)) {
3863
-
3864
3847
  invalid = true;
3865
-
3866
3848
  isDirty = true;
3867
-
3868
3849
  } else {
3869
-
3870
3850
  isDirty = parsed !== (userVal !== undefined ? userVal : baseVal);
3871
-
3872
3851
  }
3873
-
3874
3852
  }
3875
-
3876
3853
  }
3877
-
3854
+ } else if (field === 'storagePath') {
3855
+ if (draftValue !== undefined) {
3856
+ const cleanVal = typeof draftValue === 'string' ? draftValue.trim() : '';
3857
+ isDirty = cleanVal !== (userVal !== undefined ? userVal : (baseVal || ''));
3858
+ }
3878
3859
  } else {
3879
-
3880
3860
  if (draftValue !== undefined) {
3881
-
3882
3861
  isDirty = Boolean(draftValue) !== (userVal !== undefined ? Boolean(userVal) : Boolean(baseVal));
3883
-
3884
3862
  }
3885
-
3886
3863
  }
3887
3864
 
3888
3865
  return {
3889
-
3890
3866
  value: currentVal,
3891
-
3892
3867
  baseValue: baseVal,
3893
-
3894
3868
  userValue: userVal,
3895
-
3896
3869
  isOverridden,
3897
-
3898
3870
  isDirty,
3899
-
3900
3871
  invalid,
3901
-
3902
3872
  };
3903
-
3904
3873
  }
3905
3874
 
3906
3875
  function computeSavePlan(draft, snap) {
3907
-
3908
3876
  if (!draft) return [];
3909
3877
 
3910
- const fields = ['maxIterations', 'autoDrive', 'enableSound', 'showQuickLaunchButton'];
3878
+ const fields = [
3879
+ 'maxIterations',
3880
+ 'autoDrive',
3881
+ 'enableSound',
3882
+ 'showQuickLaunchButton',
3883
+ 'consecutiveToolFailureLimit',
3884
+ 'enableBrowserNotifications',
3885
+ 'maxTokenBudget',
3886
+ 'budgetWarningThreshold',
3887
+ 'autoCheckpointOnMilestone',
3888
+ 'storagePath',
3889
+ ];
3911
3890
 
3912
3891
  const writes = [];
3913
3892
 
3914
3893
  for (const f of fields) {
3915
-
3916
3894
  if (draft[f] === undefined) continue;
3917
3895
 
3918
3896
  const status = getFieldStatus(f, draft[f], snap);
3919
-
3920
3897
  if (status.invalid) continue;
3921
3898
 
3922
3899
  if (status.isDirty) {
3923
-
3924
- if (f === 'maxIterations' && draft[f] === '') {
3925
-
3926
- writes.push([f, undefined]);
3927
-
3928
- } else if (f === 'maxIterations') {
3929
-
3930
- writes.push([f, parseNumberField(draft[f])]);
3931
-
3900
+ if (f in NUMERIC_FIELDS) {
3901
+ if (draft[f] === '') {
3902
+ writes.push([f, undefined]);
3903
+ } else {
3904
+ writes.push([f, parseNumberField(draft[f], NUMERIC_FIELDS[f])]);
3905
+ }
3906
+ } else if (f === 'storagePath') {
3907
+ const clean = typeof draft[f] === 'string' ? draft[f].trim() : '';
3908
+ writes.push([f, clean ? clean : undefined]);
3932
3909
  } else {
3933
-
3934
3910
  writes.push([f, Boolean(draft[f])]);
3935
-
3936
3911
  }
3937
-
3938
3912
  }
3939
-
3940
3913
  }
3941
3914
 
3942
3915
  return writes;
3943
-
3944
3916
  }
3945
3917
 
3946
3918
  // --- SETTINGS CARD ---
@@ -4138,17 +4110,11 @@ window.__ModuleLoader__.load({
4138
4110
  };
4139
4111
 
4140
4112
  const resetFieldToDefault = (field) => {
4141
-
4142
- if (field === 'maxIterations') {
4143
-
4113
+ if (field in NUMERIC_FIELDS) {
4144
4114
  edit(field, '');
4145
-
4146
4115
  } else {
4147
-
4148
4116
  edit(field, snap?.base?.[field] ?? DEFAULT_SETTINGS[field]);
4149
-
4150
4117
  }
4151
-
4152
4118
  };
4153
4119
 
4154
4120
  const save = async () => {
@@ -4612,7 +4578,7 @@ window.__ModuleLoader__.load({
4612
4578
 
4613
4579
  title: t('resetField') || 'Reset to default',
4614
4580
 
4615
- onClick: () => edit('consecutiveToolFailureLimit', snap?.base?.consecutiveToolFailureLimit ?? DEFAULT_SETTINGS.consecutiveToolFailureLimit),
4581
+ onClick: () => resetFieldToDefault('consecutiveToolFailureLimit'),
4616
4582
 
4617
4583
  },
4618
4584
 
@@ -4644,7 +4610,7 @@ window.__ModuleLoader__.load({
4644
4610
 
4645
4611
  className: 'dsh-goal-card-input',
4646
4612
 
4647
- onChange: (e) => edit('consecutiveToolFailureLimit', parseNumberField(e.target.value)),
4613
+ onChange: (e) => edit('consecutiveToolFailureLimit', e.target.value),
4648
4614
 
4649
4615
  }),
4650
4616
 
@@ -4680,7 +4646,7 @@ window.__ModuleLoader__.load({
4680
4646
  type: 'button',
4681
4647
  className: 'dsh-goal-btn-inline-reset',
4682
4648
  title: t('resetField') || 'Reset to default',
4683
- onClick: () => edit('maxTokenBudget', snap?.base?.maxTokenBudget ?? DEFAULT_SETTINGS.maxTokenBudget),
4649
+ onClick: () => resetFieldToDefault('maxTokenBudget'),
4684
4650
  },
4685
4651
  React.createElement(IconRotateCcw, { size: 12 }),
4686
4652
  t('resetField') || 'Default'
@@ -4697,7 +4663,7 @@ window.__ModuleLoader__.load({
4697
4663
  value: budgetStatus.value !== undefined ? String(budgetStatus.value) : '',
4698
4664
  disabled,
4699
4665
  className: 'dsh-goal-card-input',
4700
- onChange: (e) => edit('maxTokenBudget', parseNumberField(e.target.value)),
4666
+ onChange: (e) => edit('maxTokenBudget', e.target.value),
4701
4667
  })
4702
4668
  ),
4703
4669
 
@@ -4721,7 +4687,7 @@ window.__ModuleLoader__.load({
4721
4687
  type: 'button',
4722
4688
  className: 'dsh-goal-btn-inline-reset',
4723
4689
  title: t('resetField') || 'Reset to default',
4724
- onClick: () => edit('budgetWarningThreshold', snap?.base?.budgetWarningThreshold ?? DEFAULT_SETTINGS.budgetWarningThreshold),
4690
+ onClick: () => resetFieldToDefault('budgetWarningThreshold'),
4725
4691
  },
4726
4692
  React.createElement(IconRotateCcw, { size: 12 }),
4727
4693
  t('resetField') || 'Default'
@@ -4738,7 +4704,7 @@ window.__ModuleLoader__.load({
4738
4704
  value: budgetWarnStatus.value !== undefined ? String(budgetWarnStatus.value) : '',
4739
4705
  disabled,
4740
4706
  className: 'dsh-goal-card-input',
4741
- onChange: (e) => edit('budgetWarningThreshold', parseNumberField(e.target.value)),
4707
+ onChange: (e) => edit('budgetWarningThreshold', e.target.value),
4742
4708
  })
4743
4709
  ),
4744
4710
 
@@ -1,4 +1,45 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { getSafeCwd } from './goal-engine-constants.js';
4
+
5
+ /**
6
+ * Check if directory is inside a valid git repository
7
+ * @param {string} workspaceRoot
8
+ * @returns {boolean}
9
+ */
10
+ export function isGitRepository(workspaceRoot) {
11
+ if (!workspaceRoot || typeof workspaceRoot !== 'string') return false;
12
+ try {
13
+ const safePath = getSafeCwd(workspaceRoot);
14
+ if (!fs.existsSync(safePath)) return false;
15
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], {
16
+ cwd: safePath,
17
+ stdio: ['ignore', 'pipe', 'ignore'],
18
+ timeout: 2000,
19
+ });
20
+ return true;
21
+ } catch (err) {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Validate that a git ref name is safe to pass to git commands
28
+ * Prevents flag injection (-*), path traversal, and illegal ref characters
29
+ * @param {string} ref
30
+ * @returns {boolean}
31
+ */
32
+ export function isValidGitRef(ref) {
33
+ if (!ref || typeof ref !== 'string') return false;
34
+ const trimmed = ref.trim();
35
+ if (!trimmed || trimmed.startsWith('-') || trimmed.endsWith('/') || trimmed.endsWith('.lock')) return false;
36
+ // Disallow control characters, whitespace, and git-forbidden special characters
37
+ if (/[\x00-\x20\x7f~^:?*\[\\ ]/.test(trimmed)) return false;
38
+ // Disallow consecutive dots or slashes, and reflog syntax @{
39
+ if (/\.\.|\/\/|@\{/.test(trimmed)) return false;
40
+ // Must match valid git ref character set
41
+ return /^[a-zA-Z0-9._/-]+$/.test(trimmed);
42
+ }
2
43
 
3
44
  /**
4
45
  * Format a sanitized git branch name from goal title
@@ -21,9 +62,11 @@ export function sanitizeBranchSlug(title) {
21
62
  * @returns {string} branch name or 'HEAD'
22
63
  */
23
64
  export function getCurrentGitBranch(cwd = process.cwd()) {
65
+ const safeCwd = getSafeCwd(cwd);
66
+ if (!isGitRepository(safeCwd)) return 'main';
24
67
  try {
25
68
  return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
26
- cwd,
69
+ cwd: safeCwd,
27
70
  encoding: 'utf8',
28
71
  stdio: ['ignore', 'pipe', 'ignore'],
29
72
  }).trim();
@@ -39,10 +82,12 @@ export function getCurrentGitBranch(cwd = process.cwd()) {
39
82
  * @returns {boolean} success
40
83
  */
41
84
  export function createGoalBranch(cwd = process.cwd(), branchName) {
42
- if (!branchName) return false;
85
+ if (!isValidGitRef(branchName)) return false;
86
+ const safeCwd = getSafeCwd(cwd);
87
+ if (!isGitRepository(safeCwd)) return false;
43
88
  try {
44
89
  execFileSync('git', ['checkout', '-b', branchName], {
45
- cwd,
90
+ cwd: safeCwd,
46
91
  encoding: 'utf8',
47
92
  stdio: ['ignore', 'pipe', 'pipe'],
48
93
  });
@@ -60,15 +105,17 @@ export function createGoalBranch(cwd = process.cwd(), branchName) {
60
105
  * @returns {boolean} success
61
106
  */
62
107
  export function mergeGoalBranch(cwd = process.cwd(), branchName, targetBranch = 'main') {
63
- if (!branchName) return false;
108
+ if (!isValidGitRef(branchName) || !isValidGitRef(targetBranch)) return false;
109
+ const safeCwd = getSafeCwd(cwd);
110
+ if (!isGitRepository(safeCwd)) return false;
64
111
  try {
65
- execFileSync('git', ['checkout', targetBranch], {
66
- cwd,
112
+ execFileSync('git', ['checkout', '--', targetBranch], {
113
+ cwd: safeCwd,
67
114
  encoding: 'utf8',
68
115
  stdio: ['ignore', 'pipe', 'pipe'],
69
116
  });
70
- execFileSync('git', ['merge', '--no-ff', '-m', `chore(goal): merge ${branchName}`, branchName], {
71
- cwd,
117
+ execFileSync('git', ['merge', '--no-ff', '-m', `chore(goal): merge ${branchName}`, '--', branchName], {
118
+ cwd: safeCwd,
72
119
  encoding: 'utf8',
73
120
  stdio: ['ignore', 'pipe', 'pipe'],
74
121
  });
@@ -86,15 +133,17 @@ export function mergeGoalBranch(cwd = process.cwd(), branchName, targetBranch =
86
133
  * @returns {boolean} success
87
134
  */
88
135
  export function discardGoalBranch(cwd = process.cwd(), branchName, targetBranch = 'main') {
89
- if (!branchName) return false;
136
+ if (!isValidGitRef(branchName) || !isValidGitRef(targetBranch)) return false;
137
+ const safeCwd = getSafeCwd(cwd);
138
+ if (!isGitRepository(safeCwd)) return false;
90
139
  try {
91
- execFileSync('git', ['checkout', targetBranch], {
92
- cwd,
140
+ execFileSync('git', ['checkout', '--', targetBranch], {
141
+ cwd: safeCwd,
93
142
  encoding: 'utf8',
94
143
  stdio: ['ignore', 'pipe', 'pipe'],
95
144
  });
96
- execFileSync('git', ['branch', '-D', branchName], {
97
- cwd,
145
+ execFileSync('git', ['branch', '-D', '--', branchName], {
146
+ cwd: safeCwd,
98
147
  encoding: 'utf8',
99
148
  stdio: ['ignore', 'pipe', 'pipe'],
100
149
  });
@@ -74,31 +74,37 @@ export function updateChecklistInMarkdown(markdown, itemText, done) {
74
74
  * @returns {{ token?: string, baseUrl: string }}
75
75
  */
76
76
  export function resolveGiteaAuth(options = {}) {
77
- const defaultUrl = options.baseUrl || process.env.GITEA_BASE_URL || 'http://127.0.0.1:3005';
77
+ const baseUrl = options.baseUrl || process.env.GITEA_BASE_URL || "";
78
78
  if (options.token) {
79
- return { token: options.token, baseUrl: defaultUrl };
79
+ return { token: options.token, baseUrl };
80
80
  }
81
81
  if (process.env.GITEA_TOKEN) {
82
- return { token: process.env.GITEA_TOKEN, baseUrl: defaultUrl };
82
+ return { token: process.env.GITEA_TOKEN, baseUrl };
83
83
  }
84
84
 
85
- const credPath = process.env.DSH_GITEA_CREDENTIALS || '/mnt/external/Project/DEV/.gitea-agent-credentials.json';
86
- try {
87
- if (fs.existsSync(credPath)) {
88
- const raw = fs.readFileSync(credPath, 'utf8');
89
- const creds = JSON.parse(raw);
90
- const agent = creds?.agents?.['deepseek-harness'] || creds?.agents?.antigravity;
91
- if (agent?.token) {
92
- return {
93
- token: agent.token,
94
- baseUrl: options.baseUrl || agent.http_remote_base || defaultUrl,
95
- };
85
+ const credPath = process.env.DSH_GITEA_CREDENTIALS;
86
+ if (credPath && typeof credPath === "string") {
87
+ try {
88
+ if (fs.existsSync(credPath)) {
89
+ const raw = fs.readFileSync(credPath, "utf8");
90
+ const creds = JSON.parse(raw);
91
+ const agentName = process.env.DSH_GITEA_AGENT;
92
+ const agent = (agentName && creds?.agents?.[agentName])
93
+ || creds?.agents?.["deepseek-harness"]
94
+ || creds?.agents?.antigravity
95
+ || creds;
96
+ if (agent?.token) {
97
+ return {
98
+ token: agent.token,
99
+ baseUrl: baseUrl || agent.http_remote_base || "",
100
+ };
101
+ }
96
102
  }
103
+ } catch (err) {
104
+ // Non-fatal credential read error
97
105
  }
98
- } catch (err) {
99
- // Non-fatal credential read error
100
106
  }
101
- return { baseUrl: defaultUrl };
107
+ return { baseUrl };
102
108
  }
103
109
 
104
110
  /**
@@ -122,9 +128,9 @@ export function resolveRepoInfo(cwd = process.cwd(), options = {}) {
122
128
  return { owner: match[1], repo: match[2] };
123
129
  }
124
130
  } catch (err) {
125
- // Fallback to default repository
131
+ // Fallback to options or empty
126
132
  }
127
- return { owner: 'goodandready', repo: 'dsh-goal' };
133
+ return { owner: options.owner || "", repo: options.repo || "" };
128
134
  }
129
135
 
130
136
  /**
@@ -140,11 +146,14 @@ export async function syncMilestoneWithIssue(goal, milestone, options = {}) {
140
146
  }
141
147
 
142
148
  const auth = resolveGiteaAuth(options);
143
- if (!auth.token) {
144
- return { synced: false, error: 'No Gitea API token available' };
149
+ if (!auth.token || !auth.baseUrl) {
150
+ return { synced: false, error: 'No Gitea API token or base URL available' };
145
151
  }
146
152
 
147
153
  const repoInfo = resolveRepoInfo(goal.cwd || process.cwd(), options);
154
+ if (!repoInfo.owner || !repoInfo.repo) {
155
+ return { synced: false, error: "No Gitea repository owner or name available" };
156
+ }
148
157
  const issueNum = goal.issueRef.issueNumber;
149
158
  const issueApiUrl = `${auth.baseUrl}/api/v1/repos/${repoInfo.owner}/${repoInfo.repo}/issues/${issueNum}`;
150
159
 
@@ -206,14 +206,14 @@ export function createMilestoneCheckpoint(milestone, sessionId = 'default', cwd)
206
206
  }).trim();
207
207
 
208
208
  if (status) {
209
- execFileSync('git', ['add', '-A'], {
209
+ execFileSync('git', ['add', '-u'], {
210
210
  stdio: ['ignore', 'ignore', 'ignore'],
211
211
  timeout: 3000,
212
212
  cwd: cwd || undefined,
213
213
  });
214
214
  const cleanTitle = (milestone.title || '').replace(/[\"\`\$]/g, '');
215
215
  const msg = `checkpoint(goal): [${milestone.id}] ${cleanTitle}`;
216
- execFileSync('git', ['commit', '-m', msg, '--no-verify'], {
216
+ execFileSync('git', ['commit', '-m', msg], {
217
217
  stdio: ['ignore', 'ignore', 'ignore'],
218
218
  timeout: 5000,
219
219
  cwd: cwd || undefined,
@@ -21,7 +21,7 @@ export class GitSnapshotManager {
21
21
  timeout: 2000,
22
22
  });
23
23
  return true;
24
- } catch {
24
+ } catch (err) {
25
25
  return false;
26
26
  }
27
27
  }
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  /**
2
4
  * Enums and helpers for DSH Goal Engine
3
5
  */
@@ -244,3 +246,47 @@ export function buildSnapshot(goal, sid, engine) {
244
246
  enableVoiceAnnouncements: engine.enableVoiceAnnouncements ?? false,
245
247
  };
246
248
  }
249
+
250
+
251
+ /**
252
+ * Check if child path is inside parent directory or equal to it
253
+ * @param {string} parent
254
+ * @param {string} child
255
+ * @returns {boolean}
256
+ */
257
+ export function isPathInsideOrEqual(parent, child) {
258
+ if (!parent || !child) return false;
259
+ const rel = path.relative(path.resolve(parent), path.resolve(child));
260
+ return !rel || (!rel.startsWith("..") && !path.isAbsolute(rel));
261
+ }
262
+
263
+ /**
264
+ * Validate and confine working directory to ensure it exists and is allowed
265
+ * @param {string} requestedCwd
266
+ * @param {string[]} [allowedRoots=[]]
267
+ * @returns {string} resolved safe cwd
268
+ */
269
+ export function getSafeCwd(requestedCwd, allowedRoots = []) {
270
+ const defaultRoot = allowedRoots[0] || process.cwd();
271
+ if (!requestedCwd || typeof requestedCwd !== "string" || !requestedCwd.trim()) {
272
+ return defaultRoot;
273
+ }
274
+
275
+ try {
276
+ const resolved = path.resolve(requestedCwd.trim());
277
+ const st = fs.statSync(resolved);
278
+ if (!st.isDirectory()) {
279
+ return null;
280
+ }
281
+
282
+ const roots = allowedRoots.length > 0 ? allowedRoots : [process.cwd()];
283
+ const isAllowed = roots.some((root) => isPathInsideOrEqual(root, resolved));
284
+ if (!isAllowed) {
285
+ return null;
286
+ }
287
+
288
+ return resolved;
289
+ } catch (err) {
290
+ return null;
291
+ }
292
+ }
@@ -1,4 +1,4 @@
1
- import { GoalState, MilestoneStatus, formatElapsed, formatETA, detectLanguage, sessionIdOf, calculateElapsedSeconds, calculateRemainingSeconds, buildSnapshot } from './goal-engine-constants.js';
1
+ import { GoalState, MilestoneStatus, formatElapsed, formatETA, detectLanguage, sessionIdOf, calculateElapsedSeconds, calculateRemainingSeconds, buildSnapshot, getSafeCwd } from './goal-engine-constants.js';
2
2
  import { getGitCurrentCommit, exportReportMarkdown, exportReportGitHubPR, createMilestoneCheckpoint, rollbackToCheckpoint, saveGoalArtifact } from './engine-reports.js';
3
3
  import { EngineStore } from './engine-store.js';
4
4
  import { buildStatePromptInjection } from './engine-prompt.js';
@@ -193,7 +193,7 @@ export class GoalEngine {
193
193
  title: cleanTitle,
194
194
  description: options.description?.trim() || '',
195
195
  lang: options.lang || detectLanguage(cleanTitle),
196
- cwd: options.cwd ? String(options.cwd).trim() : null,
196
+ cwd: options.cwd ? getSafeCwd(options.cwd) : null,
197
197
  state: GoalState.RUNNING,
198
198
  startedAt: now,
199
199
  pausedAt: null,
@@ -227,8 +227,9 @@ export class GoalEngine {
227
227
 
228
228
  if (this.autoBranchOnGoalStart && options.autoBranch !== false && this.storagePath !== null && process.env.NODE_ENV !== 'test') {
229
229
  const slug = sanitizeBranchSlug(cleanTitle);
230
- const parentBranch = getCurrentGitBranch(options.cwd);
231
- if (createGoalBranch(options.cwd, slug)) {
230
+ const targetCwd = goal.cwd || process.cwd();
231
+ const parentBranch = getCurrentGitBranch(targetCwd);
232
+ if (createGoalBranch(targetCwd, slug)) {
232
233
  goal.gitBranch = slug;
233
234
  goal.gitParentBranch = parentBranch;
234
235
  }
package/lib/index.js CHANGED
@@ -1,6 +1,17 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
3
  import z from '@deepseek-ai/schemastery';
4
+ // Polyfill volatile schema modifier if running against schemastery < 3.18.4
5
+ if (typeof z.Schema?.prototype?.volatile !== 'function') {
6
+ const proto = z.Schema ? z.Schema.prototype : (typeof z === 'function' ? Object.getPrototypeOf(z.string?.() || {}) : null);
7
+ if (proto && typeof proto.extra === 'function' && typeof proto.volatile !== 'function') {
8
+ proto.volatile = function volatile() {
9
+ if (this.meta?.volatile) throw new TypeError('volatile schema is already wrapped');
10
+ return this.extra('volatile', true);
11
+ };
12
+ }
13
+ }
14
+
4
15
  import { AddonStore } from './addon-store.js';
5
16
  import { TokenBudgetGuard } from './token-budget-guard.js';
6
17
  import { GitSnapshotManager } from './git-snapshot-manager.js';
@@ -63,34 +74,35 @@ export function safeService(ctx, name) {
63
74
  return ctx.reflect.get(name, false) || null;
64
75
  }
65
76
  return ctx[name] || null;
66
- } catch {
77
+ } catch (err) {
67
78
  return null;
68
79
  }
69
80
  }
70
81
 
71
82
  export function apply(ctx, config = {}) {
72
83
  const sseClients = new Map();
84
+ const cfg = plainConfig(config || {});
73
85
 
74
86
  let currentSettings = {
75
- maxIterations: config?.maxIterations ?? 25,
76
- autoDrive: config?.autoDrive ?? true,
77
- enableSound: config?.enableSound ?? true,
78
- showQuickLaunchButton: config?.showQuickLaunchButton ?? true,
79
- consecutiveToolFailureLimit: config?.consecutiveToolFailureLimit ?? 3,
80
- enableBrowserNotifications: config?.enableBrowserNotifications ?? true,
81
- maxTokenBudget: config?.maxTokenBudget ?? 0,
82
- budgetWarningThreshold: config?.budgetWarningThreshold ?? 80,
83
- autoCheckpointOnMilestone: config?.autoCheckpointOnMilestone ?? false,
84
- enableLiveActivityFeed: config?.enableLiveActivityFeed ?? true,
85
- enablePreplanning: config?.enablePreplanning ?? true,
86
- autoBranchOnGoalStart: config?.autoBranchOnGoalStart ?? true,
87
- enablePostGoalRetrospective: config?.enablePostGoalRetrospective ?? true,
88
- autoScaleBudgetNearCompletion: config?.autoScaleBudgetNearCompletion ?? false,
89
- enableTemplatesDrawer: config?.enableTemplatesDrawer ?? true,
90
- enableMilestoneDependencies: config?.enableMilestoneDependencies ?? true,
91
- soundScheme: config?.soundScheme ?? 'default',
92
- enableVoiceAnnouncements: config?.enableVoiceAnnouncements ?? false,
93
- storagePath: config?.storagePath,
87
+ maxIterations: cfg?.maxIterations ?? 25,
88
+ autoDrive: cfg?.autoDrive ?? true,
89
+ enableSound: cfg?.enableSound ?? true,
90
+ showQuickLaunchButton: cfg?.showQuickLaunchButton ?? true,
91
+ consecutiveToolFailureLimit: cfg?.consecutiveToolFailureLimit ?? 3,
92
+ enableBrowserNotifications: cfg?.enableBrowserNotifications ?? true,
93
+ maxTokenBudget: cfg?.maxTokenBudget ?? 0,
94
+ budgetWarningThreshold: cfg?.budgetWarningThreshold ?? 80,
95
+ autoCheckpointOnMilestone: cfg?.autoCheckpointOnMilestone ?? false,
96
+ enableLiveActivityFeed: cfg?.enableLiveActivityFeed ?? true,
97
+ enablePreplanning: cfg?.enablePreplanning ?? true,
98
+ autoBranchOnGoalStart: cfg?.autoBranchOnGoalStart ?? true,
99
+ enablePostGoalRetrospective: cfg?.enablePostGoalRetrospective ?? true,
100
+ autoScaleBudgetNearCompletion: cfg?.autoScaleBudgetNearCompletion ?? false,
101
+ enableTemplatesDrawer: cfg?.enableTemplatesDrawer ?? true,
102
+ enableMilestoneDependencies: cfg?.enableMilestoneDependencies ?? true,
103
+ soundScheme: cfg?.soundScheme ?? 'default',
104
+ enableVoiceAnnouncements: cfg?.enableVoiceAnnouncements ?? false,
105
+ storagePath: cfg?.storagePath,
94
106
  };
95
107
 
96
108
  const defaultStorageDir = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
@@ -298,6 +310,23 @@ export function apply(ctx, config = {}) {
298
310
  if (typeof patch.storagePath === 'string' && patch.storagePath.trim()) {
299
311
  addonStore.setStoragePath(patch.storagePath.trim());
300
312
  }
313
+ if (fallbackEngine && typeof fallbackEngine.updateConfig === 'function') {
314
+ fallbackEngine.updateConfig({
315
+ defaultMaxIterations: currentSettings.maxIterations,
316
+ autoDrive: currentSettings.autoDrive,
317
+ consecutiveToolFailureLimit: currentSettings.consecutiveToolFailureLimit,
318
+ maxTokenBudget: currentSettings.maxTokenBudget,
319
+ budgetWarningThreshold: currentSettings.budgetWarningThreshold,
320
+ autoCheckpointOnMilestone: currentSettings.autoCheckpointOnMilestone,
321
+ enableLiveActivityFeed: currentSettings.enableLiveActivityFeed,
322
+ enablePreplanning: currentSettings.enablePreplanning,
323
+ autoBranchOnGoalStart: currentSettings.autoBranchOnGoalStart,
324
+ enablePostGoalRetrospective: currentSettings.enablePostGoalRetrospective,
325
+ autoScaleBudgetNearCompletion: currentSettings.autoScaleBudgetNearCompletion,
326
+ enableTemplatesDrawer: currentSettings.enableTemplatesDrawer,
327
+ enableMilestoneDependencies: currentSettings.enableMilestoneDependencies,
328
+ });
329
+ }
301
330
  };
302
331
 
303
332
  // DSH hands the plugin the entry config, whose .volatile() fields hold Volatile
package/lib/routes.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { MilestoneStatus, detectLanguage, sessionIdOf } from './goal-engine-constants.js';
3
+ import { MilestoneStatus, detectLanguage, sessionIdOf, isPathInsideOrEqual, getSafeCwd } from './goal-engine-constants.js';
4
+ import { isValidGitRef } from './engine-git-branch.js';
4
5
  import { saveGoalArtifact, rollbackToCheckpoint } from './engine-reports.js';
5
6
  import { getTemplatesCatalogue, instantiateTemplate } from './engine-templates.js';
6
7
  import { parseIssueChecklist } from './engine-issue-sync.js';
@@ -19,31 +20,42 @@ export function isLoopback(value) {
19
20
 
20
21
  export function isTrustedCaller(req) {
21
22
  if (!req) return false;
22
- const remote = req.socket?.remoteAddress || req.connection?.remoteAddress || '';
23
- if (isLoopback(remote)) return true;
24
-
25
- const host = String(req.headers?.host || '').toLowerCase();
26
- const origin = String(req.headers?.origin || '').trim().toLowerCase();
27
- if (origin) {
28
- try {
29
- const u = new URL(origin);
30
- if (u.host === host) return true;
31
- } catch (err) { /* invalid url */ }
23
+ const remote = req.socket?.remoteAddress || req.connection?.remoteAddress || "";
24
+ const site = req.headers?.["sec-fetch-site"];
25
+
26
+ // 1. Cross-site and same-site browser requests are rejected
27
+ if (site === "cross-site" || site === "same-site") return false;
28
+
29
+ // 2. Same-origin browser UI requests (operator UI on LAN or localhost)
30
+ if (site === "same-origin") {
31
+ const host = String(req.headers?.host || "").toLowerCase();
32
+ const origin = String(req.headers?.origin || "").trim().toLowerCase();
33
+ if (origin && host) {
34
+ try {
35
+ const u = new URL(origin);
36
+ if (u.host === host) return true;
37
+ } catch (err) {
38
+ return false;
39
+ }
40
+ }
41
+ const referer = String(req.headers?.referer || "").trim().toLowerCase();
42
+ if (referer && host) {
43
+ try {
44
+ const u = new URL(referer);
45
+ if (u.host === host) return true;
46
+ } catch (err) {
47
+ return false;
48
+ }
49
+ }
32
50
  return false;
33
51
  }
34
52
 
35
- const referer = String(req.headers?.referer || '').trim().toLowerCase();
36
- if (referer) {
37
- try {
38
- const u = new URL(referer);
39
- if (u.host === host) return true;
40
- } catch (err) { /* invalid url */ }
41
- return false;
42
- }
53
+ // 3. No declared site: only loopback remote clients (CLI, reverse proxy) are trusted
54
+ if (isLoopback(remote)) return true;
43
55
 
44
- // Fallback for tests or local CLI without socket where host header targets loopback
45
- if (!remote && host) {
46
- const hostName = host.split(':')[0];
56
+ // 4. Fallback for test harnesses without remote socket where host header explicitly targets loopback
57
+ if (!remote && req.headers?.host) {
58
+ const hostName = String(req.headers.host).split(":")[0];
47
59
  if (isLoopback(hostName)) {
48
60
  return true;
49
61
  }
@@ -52,36 +64,7 @@ export function isTrustedCaller(req) {
52
64
  return false;
53
65
  }
54
66
 
55
- export function isPathInsideOrEqual(parent, child) {
56
- if (!parent || !child) return false;
57
- const rel = path.relative(path.resolve(parent), path.resolve(child));
58
- return !rel || (!rel.startsWith('..') && !path.isAbsolute(rel));
59
- }
60
-
61
- export function getSafeCwd(requestedCwd, allowedRoots = []) {
62
- const defaultRoot = allowedRoots[0] || process.cwd();
63
- if (!requestedCwd || typeof requestedCwd !== 'string' || !requestedCwd.trim()) {
64
- return defaultRoot;
65
- }
66
-
67
- try {
68
- const resolved = path.resolve(requestedCwd.trim());
69
- const st = fs.statSync(resolved);
70
- if (!st.isDirectory()) {
71
- return null;
72
- }
73
-
74
- const roots = allowedRoots.length > 0 ? allowedRoots : [process.cwd()];
75
- const isAllowed = roots.some((root) => isPathInsideOrEqual(root, resolved));
76
- if (!isAllowed) {
77
- return null;
78
- }
79
-
80
- return resolved;
81
- } catch (err) {
82
- return null;
83
- }
84
- }
67
+ export { isPathInsideOrEqual, getSafeCwd };
85
68
 
86
69
  /**
87
70
  * Register webServer HTTP routes and SSE stream for DSH Goal
@@ -583,6 +566,14 @@ export function registerRoutes(ctx, {
583
566
  case 'branch_action': {
584
567
  const op = String(data.operation || data.branchOperation || 'merge').toLowerCase();
585
568
  const targetBranch = String(data.targetBranch || 'main');
569
+ if (!isValidGitRef(targetBranch)) {
570
+ res.statusCode = 400;
571
+ return res.end(JSON.stringify({ error: `Invalid targetBranch ref: "${targetBranch}"` }));
572
+ }
573
+ if (op !== 'merge' && op !== 'discard') {
574
+ res.statusCode = 400;
575
+ return res.end(JSON.stringify({ error: `Invalid branch operation: "${op}". Allowed: merge, discard` }));
576
+ }
586
577
  if (engine) {
587
578
  if (op === 'merge') {
588
579
  const ok = engine.mergeGoalBranch(targetBranch, sid);
package/lib/tools.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { MilestoneManager } from './milestone-manager.js';
2
2
  import { AddonStore } from './addon-store.js';
3
+ import { getSafeCwd } from './goal-engine-constants.js';
3
4
 
4
5
  /**
5
6
  * Tools module for @goodandready/dsh-goal (Core Addon).
@@ -83,9 +84,10 @@ export function registerTools(ctx, { milestoneManager, goalsService, logger = co
83
84
  if (!milestoneId) {
84
85
  throw new Error('milestoneId is required for complete action');
85
86
  }
86
- const completed = await mm.completeMilestone(goalId, milestoneId, {
87
- cwd: toolCtx?.session?.cwd || toolCtx?.cwd || process.cwd(),
88
- });
87
+ const rawCwd = toolCtx?.session?.cwd || toolCtx?.cwd || process.cwd();
88
+ const safeCwd = getSafeCwd(rawCwd);
89
+ const notes = typeof args.notes === 'string' ? args.notes : '';
90
+ const completed = await mm.completeMilestone(goalId, milestoneId, notes, safeCwd);
89
91
  return { ok: true, goalId, milestoneId, milestone: completed };
90
92
  }
91
93
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-goal",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "description": "Core Goal Addon (Token Budget, Milestones, Git Snapshots & Retrospective Reports) for DeepSeek Harness",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -19,7 +19,7 @@
19
19
  "LICENSE"
20
20
  ],
21
21
  "scripts": {
22
- "test": "node --test test/*.test.mjs"
22
+ "test": "NODE_ENV=test node --test test/*.test.mjs"
23
23
  },
24
24
  "keywords": [
25
25
  "dsh",